For me, it just seems like a funky MOV. What's its purpose and when should I use it?
For me, it just seems like a funky MOV. What's its purpose and when should I use it?
It seems that lots of answers already complete, I'd like to add one more example code for showing how the lea and move instruction work differently when they have the same expression format.
To make a long story short, lea instruction and mov instructions both can be used with the parentheses enclosing the src operand of the instructions. When they are enclosed with the (), the expression in the () is calculated in the same way; however, two instructions will interpret the calculated value in the src operand in a different way.
Whether the expression is used with the lea or mov, the src value is calculated as below.
D ( Rb, Ri, S ) => (Reg[Rb]+S*Reg[Ri]+ D)
However, when it is used with the mov instruction, it tries to access the value pointed to by the address generated by the above expression and store it to the destination.
In contrast of it, when the lea instruction is executed with the above expression, it loads the generated value as it is to the destination.
The below code executes the lea instruction and mov instruction with the same parameter. However, to catch the difference, I added a user-level signal handler to catch the segmentation fault caused by accessing a wrong address as a result of mov instruction.
Example code
#define _GNU_SOURCE 1 /* To pick up REG_RIP */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <signal.h>
uint32_t
register_handler(uint32_t event, void (*handler)(int, siginfo_t *, void *))
{
uint32_t ret = 0;
struct sigaction act;
memset(&act, 0, sizeof(act));
act.sa_sigaction = handler;
act.sa_flags = SA_SIGINFO;
ret = sigaction(event, &act, NULL);
return ret;
}
void segfault_handler(int signum, siginfo_t *info, void *priv)
{
ucontext_t *context = (ucontext_t *)(priv);
uint64_t rip = (uint64_t)(context->uc_mcontext.gregs[REG_RIP]);
uint64_t faulty_addr = (uint64_t)(info->si_addr);
printf("inst at 0x%lx tries to access memory at %ld, but failed\n",
rip, faulty_addr);
exit(1);
}
int main(void)
{
int result_of_lea = 0;
register_handler(SIGSEGV, segfault_handler);
// initialize registers %eax = 1, %ebx = 2
// the compiler will emit something like
// mov $1, %eax
// mov $2, %ebx
// because of the input operands
asm("lea 4(%%rbx, %%rax, 8), %%edx \t\n"
: "=d"(result_of_lea) // output in EDX
: "a"(1), "b"(2) // inputs in EAX and EBX
: // no clobbers
);
// lea 4(rbx, rax, 8),%edx == lea (rbx + 8*rax + 4),%edx == lea(14),%edx
printf("Result of lea instruction: %d\n", result_of_lea);
asm volatile("mov 4(%%rbx, %%rax, 8), %%edx"
:
: "a"(1), "b"(2)
: "edx" // if it didn't segfault, it would write EDX
);
}
Execution result
Result of lea instruction: 14
inst at 0x4007b5 tries to access memory at 14, but failed
LEA is not a funky MOV. When you use MOV, it calculates the address and accesses the memory. LEA just calculates the address, it doesn't actually access memory. This is the difference.
In 8086 and later, LEA just sets a sum of up to two source registers and an immediate value to a destination register. For example, lea bp, [bx+si+3] sets to the bp register the sum of bx plus si plus 3. You cannot achieve this calculation to save the result to a register with MOV.
The 80386 processor introduced a series of scaling modes, in which the index register value can be multiplied by a valid scaling factor to obtain the displacement. The valid scale factors are 1, 2, 4, and 8. Therefore, you can use instructions like lea ebp, [ebx+esi*8+3].
In contrast to LEA, there are instructions LDS and LES, that, to the contrary, load values from memory to the pair of registers: one segment register (DS or ES) and one general register. There are also versions for the other registers: LFS, LGS and LSS for FS, GS and SS segment registers, respectively (introduced in 80386).
So, these instructions load "far" pointer - a pointer consisting of a 16-bit segment selector and a 16-bit (or a 32-bit, depending on the mode) offset, so the total far pointer size was 32-bit in 16-bit mode and 48-bit in 32-bit mode.
These are handy instructions for 16-bit mode, be it 16-bit real mode or 16-bit protected mode.
Under 32-bit mode, there is no need in these instructions since OSes set all segment bases to zero (flat memory model), so there is no need to load segment registers. We just use 32-bit pointers, not 48.
Under 64-bit modes, these instructions are not implemented. Their opcodes give access violation interrupt (exception). Since Intel's implementation of VEX - "vector extensions - (AVX), Intel took their opcodes of LDS and LES and started using them for VEX prefixes. As Peter Cordes pointed out, that is why only x/ymm0..7 are accessible in 32-bit mode (quote): "the VEX prefixes were carefully designed to only overlap with invalid encodings of LDS and LES in 32-bit mode, where R̅ X̅ B̅ are all 1. That's why some of the bits are inverted in VEX prefixes".
All normal "calculating" instructions like adding multiplication, exclusive or set the status flags like zero, sign. If you use a complicated address, AX xor:= mem[0x333 +BX + 8*CX] the flags are set according to the xor operation.
Now you may want to use the address multiple times. Loading such an addres into a register is never intended to set status flags and luckily it doesn't. The phrase "load effective address" makes the programmer aware of that. That is where the weird expression comes from.
It is clear that once the processor is capable of using the complicated address to process its content, it is capable of calculating it for other purposes. Indeed it can be used to perform a transformation x <- 3*x+1 in one instruction. This is a general rule in assembly programming: Use the instructions however it rocks your boat.
The only thing that counts is whether the particular transformation embodied by the instruction is useful for you.
Bottom line
MOV, X| T| AX'| R| BX|
and
LEA, AX'| [BX]
have the same effect on AX but not on the status flags. (This is ciasdis notation.)
Forgive me if someone already mentioned, but in case anyone's wondering about the bad old days of x86 when memory segmentation was still relevant: you will always get the same results from these two instructions:
LEA AX, DS:[0x1234]
and
LEA AX, CS:[0x1234]
The "effective address" is just the offset part of the seg:off logical address. In this case, 0x1234.
LEA does not add the segment base. That would defeat one of the original use-cases, for doing address math to get a pointer (offset) you could actually dereference. Such as lea bx, [array + si]. If that added DS base to give a linear address, a later mov ax, [bx] would add the DS base again.
Also, the 20-bit result would often not fit in a 16-bit register.
See https://www.stevemorse.org/8086/index.html - the architect of 8086 wrote a book about the instruction set, and it's now free on his web site. The section on LEA mentions some of his design intent.