Can the following code:
float f = sinf(0.5f);
be optimized to the following code (actually pseudocode to give an idea):
float f = 0x1.eaee88p-2f;
feraiseexcept(FE_INEXACT);
The same principle for the other C standard library functions. As I understand, since the "whole language is based on the (rather unhelpful) concept of an "abstract machine" (link), then an "implementation is free to do anything in the ways of optimizations as long as side effects and "the observable behavior" are respected" (the same link).
Some compilers will optimize it to the simple constant expression. It is because the compiler knows how functions from the standard library work. The compiler knows that sinf
does not have side effects.
int main(void)
{
float f = sinf(0.5f);
printf("%f\n", f);
}
.LC1:
.string "%f\n"
main:
sub rsp, 8
mov edi, OFFSET FLAT:.LC1
mov eax, 1
movsd xmm0, QWORD PTR .LC0[rip]
call printf
xor eax, eax
add rsp, 8
ret
.LC0:
.long -2147483648
.long 1071558376