<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/57858>57858</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
new+delete pair deleted by clang at -Oz without accounting for side-effects
</td>
</tr>
<tr>
<th>Labels</th>
<td>
llvm:codegen,
invalid-code-generation
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
hiraditya
</td>
</tr>
</table>
<pre>
code:
```cpp
// Type your code here, or load an example.
//#include<iostream>
#include<cassert>
#include<cstdlib>
int volatile gv = 0;
void* operator new(long unsigned sz ) {
++gv;
return malloc( sz );
}
void operator delete(void *p) noexcept {
--gv;
free(p);
}
class c {
int l;
public:
c() : l(0) {}
int get(){ return l; }
};
int caller( void ){
c *f = new c();
assert( f->get() == 0 );
delete f;
return gv;
}
```
$ clang -std=c++20 -Oz
```asm
operator new(unsigned long): # @operator new(unsigned long)
inc dword ptr [rip + gv]
jmp malloc@PLT # TAILCALL
operator delete(void*): # @operator delete(void*)
dec dword ptr [rip + gv]
jmp free@PLT # TAILCALL
caller(): # @caller()
mov eax, dword ptr [rip + gv]
ret
gv:
.long 0 # 0x0
```
However, at -Os the behavior is different
$ clang -std=c++20 -Os
```asm
operator new(unsigned long): # @operator new(unsigned long)
inc dword ptr [rip + gv]
jmp malloc@PLT # TAILCALL
operator delete(void*): # @operator delete(void*)
dec dword ptr [rip + gv]
jmp free@PLT # TAILCALL
caller(): # @caller()
inc dword ptr [rip + gv]
dec dword ptr [rip + gv]
mov eax, dword ptr [rip + gv]
ret
gv:
.long 0 # 0x0
```
https://godbolt.org/z/hschxza9s
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJztVk2PozgQ_TXkUkpEm3yQA4d094xmpZZ2D_0HjF0kHjkY2Sad5Ndv2YEkoO6enj3tYRDBYLuqXr16RSiNPBVJ-pykG2EkJtnm8pAs08spmqabYd_phNdTg3AyrYWwH3Zo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