<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/66603>66603</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
Behavior of overflowing floating-point to integer conversions
</td>
</tr>
<tr>
<th>Labels</th>
<td>
new issue
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
dzaima
</td>
</tr>
</table>
<pre>
This issue is either:
a) a missed optimization in the x86-64 backend; or
b) a wrong optimization in the aarch64 backend.
Consider the following code:
```c
#include<stdint.h>
#include<stdbool.h>
bool is_i8(double x) {
return x == (int8_t) x;
}
bool is_i32(double x) {
return x == (int32_t)x;
}
```
As per the C standard, these functions invoke undefined behavior if given arguments that, rounded to an integer, don't fit in the desired type. Thus, `is_i8` can always be replaced with `is_i32` ([alive2 proof](https://alive2.llvm.org/ce/z/TokdT9) from the optimized IR).
However, the x86-64 backend does not do this, and thus `is_i8` has an unnecessary `movsx eax, al` instruction that can be eliminated. The aarch64 backend does do this optimization. [compiler explorer](https://godbolt.org/z/Kj5hEjcq5).
GCC preserves the int8_t cast on both x86-64 and ARM64 (and everything else I tested in CE): https://godbolt.org/z/78MbdGbPz.
And while C does allow the optimization in question, it means that `x == (T)x` cannot be used as a check for whether the floating-point value `x` fits in the integer type `T` (even though it would work if the conversion gave any valid value of `T` in place of UB/poison). And, as far as I can tell, there is no alternative way to do a check like this anywhere near as performantly, without writing platform-specific assembly, which is, IMO, a quite problematic issue, though not really a clang-specific one.
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJyUVdtu4zgM_RrlhWjgyrk-5KGXyWyxGOxi0H0eyBIdcyqLHklOmn79grZ7nQKLBYomjkj68PAcyqREh4C4U8trtbydmT43HHfuyVBrZhW78-6-oQSUUo9ACZByg1GVV6q4VcX03yi9BQMtpYQOuMvU0pPJxAEoQG4QHjeri9UCKmMfMDhVXgNHgDG7GrNPkcPh02Rjom1es-dvX33DI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