[Bug pending/103875] New: Dead writes are not optimized out

lh_mouse at 126 dot com gcc-bugzilla@gcc.gnu.org
Fri Dec 31 13:08:59 GMT 2021


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

            Bug ID: 103875
           Summary: Dead writes are not optimized out
           Product: gcc
           Version: 11.2.1
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: pending
          Assignee: unassigned at gcc dot gnu.org
          Reporter: lh_mouse at 126 dot com
  Target Milestone: ---

I was reading
<https://quuxplusone.github.io/blog/2018/04/17/downsides-of-omitting-trivial-destructor-calls/>,
which I think is a great article. But the issue that was mentioned in that
article seems to be specific to `std::vector`.

Specifically, for this hand-written 'static vector', neither GCC or Clang is
able to optimize out any dead writes (godbolt [1]):

```
struct foo
  {
    using value_type = int;

    unsigned long size;
    value_type data[10];

    value_type&
    back()
      {
        return this->data[this->size-1];
      }

    void
    pop()
      {
        this->size --;
        this->data[this->size].~value_type();   // the last element is
destroyed here
      }
  };

void
use_foo(foo& f)
  {
    f.back() *= 42;   // this write should be dead
    f.pop();
  }
```

```
use_foo(foo&):
        mov     rdx, QWORD PTR [rdi]
        lea     rax, [rdx-1]
        imul    edx, DWORD PTR [rdi+4+rdx*4], 42
        mov     DWORD PTR [rdi+8+rax*4], edx           # dead write is here
        mov     QWORD PTR [rdi], rax
        ret
```


Making `value_type` non-trivial as suggested does not help (godbolt [2]):

```
struct foo
  {
    struct value_type
      {
        int val = 0;
        int& operator*=(int x) { return this->val *= x;  }
        ~value_type() { }  // non-trivial
      };

    unsigned long size;
    value_type data[10];

    value_type&
    back()
      {
        return this->data[this->size-1];
      }

    void
    pop()
      {
        this->size --;
        this->data[this->size].~value_type();
      }
  };

void
use_foo(foo& f)
  {
    f.back() *= 42;
    f.pop();
  }
```

```
use_foo(foo&):
        mov     rdx, QWORD PTR [rdi]
        lea     rax, [rdx-1]
        imul    edx, DWORD PTR [rdi+4+rdx*4], 42
        mov     DWORD PTR [rdi+8+rax*4], edx        # dead write is still here
        mov     QWORD PTR [rdi], rax
        ret
```


[1] https://gcc.godbolt.org/z/f9xx3c6Y7
[2] https://gcc.godbolt.org/z/Ysss5GMjj


More information about the Gcc-bugs mailing list