2

Instruction 1:

LEA DX, MESSAGE ; Move the address of MESSAGE in register DX

Instruction 2:

MOV DX, OFFSET MESSAGE ; Move the address of MESSAGE in register DX

Questions:

  • Are the above instructions equal? They seem to work similarly, but I have just started programming assembly so I can not say.
  • If both of them are similar, then which one of above is the better way to do the above task?

Note: I have already read this question

Michael Petch
  • 46,082
  • 8
  • 107
  • 198
Syed Farjad Zia Zaidi
  • 3,302
  • 4
  • 27
  • 50
  • 1
    http://stackoverflow.com/questions/1658294/whats-the-purpose-of-the-lea-instruction – Devolus Dec 03 '14 at 06:44
  • 2
    They are only equivalent if MESSAGE is a global variable. LEA starts to pay off when the variable is stored on the stack or is an element of an array. You get a multiply and an add for free. A C compiler really likes LEA. An assembly programmer not so much. – Hans Passant Dec 03 '14 at 09:11

1 Answers1

4

On my 32-bit system, the instructions match opcodes like this:

8d 15 c8 90 04 08       lea    0x80490c8,%edx
ba c8 90 04 08          mov    $0x80490c8,%edx

So you use a whole extra byte when the code is loaded into memory if you use lea.

I found a reference to AMD chips at one point having lower latency for lea than for mov, but only by one clock cycle (and this will be immaterial if the data is not in L1 cache). I am not sure if that result holds for recent processors.

I have found lea useful when trying to add an offset to a base address like this:

lea message(,%esi,2), %ecx  # put address of message + 2 x ESI in ECX

whereas I can't do this:

mov $message(,%esi,2), %ecx  # fails on bad syntax

and this produces the wrong result:

mov message(,%esi,2), %ecx  # puts _content_ at address, not address, into ECX 

at least in my assembler (GNU as).

Tony
  • 1,645
  • 1
  • 10
  • 13
  • Latency is not very meaningful when the instruction has no input dependencies. It starts a new dependency chain for that register. `mov reg, offset label` is always better, except in 64-bit code where RIP-relative LEA is useful for PIC code, or code loaded outside the low 32 bits (RIP-relative LEA is better than `mov r64, imm64`, but worse than 5-byte `mov r32, imm32` which is usable in position-dependent 64-bit code on Linux.) – Peter Cordes Apr 16 '18 at 05:43