0

我目前正在研究 Armv8 汇编语言,不太明白这里发生了什么。我们假设 vec 保存 64 位整数,而 i 是 64 位整数。我们还假设 vec 的地址在 x0 中,而 i 位于 x1 中。

//The C equivalent: vec[i] = vec[i] * 2

lsl x1, x1, 3 // multiply i by 8 because vec of 8 byte ints
add x0, x0, x1 // add offset to base address of array
ldr x2, [x0, 0] // load item from memory
lsl x2, x2, 1 // multiply it by 2.
str x2, [x0, 0] // store it back to memory

我有点理解 ldr 指令,因为它说将 x0 的值存储到寄存器 x2 中。但我不明白这与我们在 vec 中想要的值是如何对应的,更重要的是为什么我们需要使用逻辑左移以及 add 指令中使用的偏移量?

非常感谢分解这个小型装配程序!

4

1 回答 1

2

数组作为连续元素存储在内存中。

如果@v 是数组的地址,它将是v[0] 的地址。如果数组项为 8 个字节,则 i[1] 将位于 @v+8,i[2] 将位于 @v+16,以此类推。

-------------------------------------------------------------------------------
|    v[0]    |    v[1]    |    v[2]    |    v[3]    |    ....    |    v[i]    |
-------------------------------------------------------------------------------
^            ^            ^            ^                         ^ 
|            |            |            |                         |            
@v           @v+8         @v+16        @v+24                     @v+i*8

我们想做 v[i] = v[i] * 2

认为

  • i 的副本存储在 reg x1 中
  • @v 的副本存储在 x0 中

我们需要做的是

// 1. compute i*8 and put it in x0
lsl x1, x1, 3 // multiply i by 8 because vec of 8 byte ints
// 2. add i*8 to @v in order to compute @v[i] in x0
add x0, x0, x1 // add offset to base address of array
// 2. fetch v[i] === value at @x0 and write it to x2
ldr x2, [x0, 0] // load item from memory
// 3. multiply x2 by 2
lsl x2, x2, 1 // multiply it by 2.
// 4. write back this value at address x0
str x2, [x0, 0] // store it back to memory

请注意,第一条指令将 x1 乘以 8,因为 i 8 == i 2^3 == i<<3。第一条指令可能是这样的

mul x1, x1, 8 // illegal

但是在 arm asm 中不存在立即数乘法,它需要两条指令。

mov x4, 8
mul x1, x1, x4

移位指令是等效的(并且更便宜)。

于 2019-02-21T07:49:22.993 回答