float to unsigned char conversion looses zero-extend
| Bugzilla Link | 36152 |
| Resolution | INVALID |
| Resolved on | Jan 30, 2018 08:51 |
| Version | 5.0 |
| OS | Windows NT |
| Attachments | example.c, llvm-ir output (for xscale, as an example of an architecture without i8/i16 registers), annotated xscale assembly |
| CC | @efriedma-quic |
Extended Description
On architectures where i8/i16 are not valid register types, legalization wrongly omits a 'zext i8 to i32' for code like 'unsigned char foo(float a) { return a; }'
It seems that for both c and c++, the conversion of a float that does not fit into the destination type results in either an unspecified value (+exception, see Aneex F.4) or undefined behavior (See n4296, 4.9). This means that llvm's behavior is indeed according to the standard.
fptoui returns undef if the result would be out of range, so the high bits are naturally zero, so the backend is doing the right thing.
The interesting question is what the C and C++ standards say about this... are we supposed to promote the unsigned char to an int before we do the implicit conversion? clang's behavior here is a bit inconsistent.
In DAGTypeLegalizer::PromoteIntRes_FP_TO_XInt(...), it is probably sufficient to just return the 'Res', without adding the AssertZext/AssertSext.