Reputation: 57
This is the example my teacher gave in C:
while (save[i] == k) i+=1;
Compiled in RISC-V mode, where i
is in x22
, k
in x24
, save
address is in x25
:
slli x10,x22,3
add x10,x10,x25
ld x9, 0(x10)
bne x9,x24, EXIT
addi x22,x22,1
beq x0,x0, Loop
Exit:.....
I don't understand why he used the shift left by immediate (slli
)
Upvotes: 3
Views: 4232
Reputation: 24738
I don't understand why he used the shift left by immediate (
slli
)
Left shifting a number N bits produces the same result as multiplying the number by 2N. Since a multiply instruction is generally more expensive (slower) than a shift instruction, left shifting is used instead of a multiply instruction as an optimization when possible: if one of the operands is a constant power of two.
slli
is used to calculate the offset into the array save
. Since i
corresponds to x22
, then:
slli x10,x22,3
multiplies the value of i
by 8 (i.e., 23, a power of two) and writes this result to x10
.
x25
indicates the base address of the array save
– the address of its first element – save[0]
. Together with x10
, which corresponds to the offset, is used to calculate the address of save[i]
:
add x10,x10,x25
At this point, x10
holds the address of save[i]
. That element is eventually loaded into x9
:
ld x9, 0(x10)
Upvotes: 3