Does rustc optimize such expressions?
Such trivial optimizations are in the domain of LLVM optimization passes, in fact generated assembly is even better and more correct.
2*x is compiled to single instruction lea rax, [rdi + rdi], which on all modern x86 processors is single uop (relevant question)
x/2 for signed numbers is compiled to fastest and the correct way, which gives right answer in case of -1 (relevant question
mov rax, rdi
shr rax, 63
add rax, rdi
sar rax
but compiles to right shift for unsigned numbers
mov rax, rdi
shr rax
same story goes for x % 8 it compiles to long assembly for signed numbers (for negative cases)
mov rax, rdi
lea rcx, [rdi + 7]
test rdi, rdi
cmovns rcx, rdi
and rcx, -8
sub rax, rcx
ret
and to and instruction for unsigned numbers (relevant question)
mov rax, rdi
and eax, 7
ret
Godbolt link
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With