2

Take for example the following two instructions:

LEA  rax, [label]
MOV  rax, label

Is there any actual advantage to using the LEA instruction instead of the MOV instruction when it is only a simple address such as this? For instance, might it be faster or a smaller instruction?

Thanks in advance.

Michael Petch
  • 46,082
  • 8
  • 107
  • 198
tilleyd
  • 141
  • 2
  • 8
  • 3
    You might have `rip` relative addressing enabled by default (e.g. for nasm, `default rel`). In that case the `lea` uses that and the `mov` uses absolute. The `lea` will indeed be shorter machine code because it uses 32 bit displacement as opposed to a 64 bit immediate. If you don't use `rip` relative, the `lea` can only address in the low 32 bits. Also note that in position independent code the absolute `mov` is not allowed. – Jester Sep 26 '17 at 15:02
  • @Jester: Huh, that's surprising. NASM does use `mov rax, imm64`. YASM uses `mov rax, imm32` (7 bytes), I guess because it knows the default code model is "small", so all static addresses fit in a 32-bit zero or sign-extended immediate. (i.e. **5-byte `mov eax, label` works in non-PIC code**, but YASM doesn't optimize away useless REX prefixes for you in general, like with `mov rax, 2`.) I was expecting NASM to optimize to `mov eax, imm32` like it usually does for constants that fit, but I guess it's only a link-time constant, not assemble-time. – Peter Cordes Sep 26 '17 at 15:11
  • RIP-relative LEA can only execute on port 1 on Intel Skylake, vs. any port for `mov`-immediate. (http://agner.org/optimize/). It's not a perf win unless you're avoiding a 64-bit immediate. But it's by far the best way to make position-independent code. – Peter Cordes Sep 26 '17 at 15:19

0 Answers0