[llvm-bugs] [Bug 32522] New: Missed optimization: useless write of zero to memory

via llvm-bugs llvm-bugs at lists.llvm.org
Tue Apr 4 12:43:38 PDT 2017


https://bugs.llvm.org/show_bug.cgi?id=32522

            Bug ID: 32522
           Summary: Missed optimization: useless write of zero to memory
           Product: Polly
           Version: unspecified
          Hardware: PC
                OS: Linux
            Status: NEW
          Severity: enhancement
          Priority: P
         Component: Optimizer
          Assignee: polly-dev at googlegroups.com
          Reporter: antoshkka at gmail.com
                CC: llvm-bugs at lists.llvm.org

The following code:

///////////////
#include <new>

template <class T>
struct shared_ptr_like {
    T* ptr;
    shared_ptr_like(shared_ptr_like&& v) noexcept : ptr(v.ptr) { v.ptr = 0; }
    ~shared_ptr_like() { if (ptr) { delete ptr; } }
};

typedef shared_ptr_like<int> test_type;
void relocate(test_type* new_buffer, test_type* old_buffer) {
        new (new_buffer) test_type{ static_cast<test_type&&>(*old_buffer) };
        old_buffer->~test_type();
}
///////////////

Generates suboptimal assembly:

relocate(shared_ptr_like<int>*, shared_ptr_like<int>*):    #
@relocate(shared_ptr_like<int>*, shared_ptr_like<int>*)
        mov     rax, qword ptr [rsi]
        mov     qword ptr [rdi], rax
        mov     qword ptr [rsi], 0 # Remove this
        ret


For that example GCC 7.0.1 20170330 with flags -std=c++17 -O2 generates
following assembly

relocate(shared_ptr_like<int>*, shared_ptr_like<int>*):
        mov     rax, QWORD PTR [rsi]
        mov     QWORD PTR [rdi], rax
        ret

This is allowed by C++ standard because
* [class.dtor] specifies that "Once a destructor is invoked for an object, the
object no longer exists<...>" 
* all the accesses to stored values require an object (if object does not exist
- accessing value is UB) [basic.lval] "If a program attempts to access the
stored value of an object through a glvalue <...>"


Described optimization is essential because code that moves an object to new
location and then destroys it often used in loops (for example
std::vector::reserve does that).


Checked on CLANG 4.0 (tags/RELEASE_400/final 297782) with flags -std=c++1z -O2

-- 
You are receiving this mail because:
You are on the CC list for the bug.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-bugs/attachments/20170404/1571bf1f/attachment.html>


More information about the llvm-bugs mailing list