Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the compiler optimize math expressions?

Does rustc optimize such expressions?

  • 2*x -> x<<1
  • x/2 -> x>>1
  • x % 8 -> x&7
  • and such
like image 462
ArekBulski Avatar asked Mar 11 '26 11:03

ArekBulski


1 Answers

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

like image 90
Inline Avatar answered Mar 14 '26 06:03

Inline