LEA 指令的目的是什么? [英] What's the purpose of the LEA instruction?

查看:29
本文介绍了LEA 指令的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对我来说,它看起来就像一个时髦的 MOV.它的用途是什么,我应该在什么时候使用它?

For me, it just seems like a funky MOV. What's its purpose and when should I use it?

推荐答案

正如其他人所指出的,LEA(加载有效地址)通常被用作进行某些计算的技巧",但这并不是它的主要目的.x86 指令集旨在支持 Pascal 和 C 等高级语言,其中数组(尤其是整数或小型结构的数组)很常见.例如,考虑一个表示 (x, y) 坐标的结构:

As others have pointed out, LEA (load effective address) is often used as a "trick" to do certain computations, but that's not its primary purpose. The x86 instruction set was designed to support high-level languages like Pascal and C, where arrays—especially arrays of ints or small structs—are common. Consider, for example, a struct representing (x, y) coordinates:

struct Point
{
     int xcoord;
     int ycoord;
};

现在想象一个像这样的语句:

Now imagine a statement like:

int y = points[i].ycoord;

其中 points[]Point 的数组.假设数组的基数已经在EBX中,变量iEAX中,xcoordycoord 都是 32 位(所以 ycoord 在结构体中偏移 4 个字节),这个语句可以编译为:

where points[] is an array of Point. Assuming the base of the array is already in EBX, and variable i is in EAX, and xcoord and ycoord are each 32 bits (so ycoord is at offset 4 bytes in the struct), this statement can be compiled to:

MOV EDX, [EBX + 8*EAX + 4]    ; right side is "effective address"

将在 EDX 中输入 y.比例因子为 8 是因为每个 Point 的大小为 8 个字节.现在考虑与address of"运算符 & 一起使用的相同表达式:

which will land y in EDX. The scale factor of 8 is because each Point is 8 bytes in size. Now consider the same expression used with the "address of" operator &:

int *p = &points[i].ycoord;

在这种情况下,您不需要 ycoord 的值,而是它的地址.这就是LEA(加载有效地址)的用武之地.编译器可以生成

In this case, you don't want the value of ycoord, but its address. That's where LEA (load effective address) comes in. Instead of a MOV, the compiler can generate

LEA ESI, [EBX + 8*EAX + 4]

这将加载 ESI 中的地址.

which will load the address in ESI.

这篇关于LEA 指令的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆