<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/64446>64446</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
Aliasing prevents optimization of redundant swaps
</td>
</tr>
<tr>
<th>Labels</th>
<td>
new issue
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
Eisenwave
</td>
</tr>
</table>
<pre>
## Code to Reproduce
```cpp
template <typename T>
void swap(T &a, T &b) {
T t = a;
a = b;
b = t;
}
void alias(int *x, int *y) {
swap(*x, *y);
swap(*x, *y);
}
void noalias(int * __restrict x, int * __restrict y) {
swap(*x, *y);
swap(*x, *y);
}
```
## Compiler Output (`clang++ -O3` trunk)
```asm
alias(int*, int*):
mov eax, dword ptr [rdi]
mov ecx, dword ptr [rsi]
mov dword ptr [rdi], ecx
mov dword ptr [rsi], eax
mov ecx, dword ptr [rdi]
mov dword ptr [rdi], eax
mov dword ptr [rsi], ecx
ret
noalias(int*, int*):
ret
```
*See [live example at Compiler Explorer](https://godbolt.org/z/qdhEErMx4)*
## Explanation
Even though `x` and `y` can alias each other in `alias()`, swapping twice should restore the original value. In fact, if they do alias each other, than `swap` would be a no-op. Essentially, there are two possibilities in this code:
- `x` and `y` point to distinct objects, meaning that they don't alias each other. If so, the codegen must be equivalent to that of `noalias`.
- `x` and `y` point to the same object, in which case a swap is a no-op. Two calls to `swap` are two no-ops.
Perhaps the analysis that's missing here is to identify swaps to be no-ops if aliasing takes place.
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJyUVd-P2jgQ_mvMy2hRcEJIHvLA7oLUh1NPd_teTZKB-OrYqT2BpX_9yQ4UWmh7FyExGU--75tfCXqv9oaoEstnsXyd4cidddVGeTJHPNCstu2pEjIVMoUX2xKwhb9ocLYdGxLJq0jWIk-mXzMMk4epHzQygUhf-DSQwZ7gTaSb6fhgVQv-iIOQxRsImaOQLxCtWsgSxOp5Cg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