Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gcc optimisation with LEA [duplicate]

I'm fiddling with the gcc's optimisation options and found that these lines:

int bla(int moo) {
  return moo * 384;
}

are translated to these:

0:   8d 04 7f                lea    (%rdi,%rdi,2),%eax
3:   c1 e0 07                shl    $0x7,%eax
6:   c3                      retq

I understand shifting represents a multiplication by 2^7. And the first line must be a multiplication by 3.

So i am utterly perplexed by the "lea" line. Isn't lea supposed to load an address?

like image 908
Banyoghurt Avatar asked Jun 23 '26 13:06

Banyoghurt


1 Answers

lea (%ebx, %esi, 2), %edi does nothing more than computing ebx + esi*2 and storing the result in edi.

Even if lea is designed to compute and store an effective address, it can and it is often used as an optimization trick to perform calculation on something that is not a memory address.

lea    (%rdi,%rdi,2),%eax
shl    $0x7,%eax

is equivalent to :

eax = rdi + rdi*2;
eax = eax * 128;

And since moo is in rdi, it stores moo*384 in eax

like image 57
zakinster Avatar answered Jun 27 '26 01:06

zakinster