Reputation: 633
The following assembly code is given in my text book.
Loop:
sll $t1, $t0, 2
add $t2, $a0, $t1
sw $zero, 0($t2)
addi $t0, $t0, 1
slt $t3, $t0, $a1
bne $t3, $zero, Loop
# return where we were
jr $ra
From this code I have two question to ask.
The first question is about the second line from the top. I get that the instruction sll
is shift left logical which shifts bit to the left. Since the shift amount is 2, it will make 0000 -> 0100 = 4 in decimal. But I don't get it after the first loop. If we shift this to the left by 2, isn't it multiplied by more than 4??
And the second question is if it is possible to optimize this code?? In my opinion, I can modify sll
and add parts in the code but I am not sure.
Any comment??
Upvotes: 0
Views: 9231
Reputation: 251
Consider the following binary:
0000 0001
If you shift the bits left by 1 digit you get:
0000 0010
If you shift again to the left by 1 digit:
0000 0100
And again:
0000 1000
The binary values above are equivalent to 1; 1x2=2; 2x2=4; 4x2=8. Shifting bits to the left is multiplying the value by 2^N if N is the number of bits you are shifting.
Another example of shifting:
Assume $t1 contains 0000 1111
sll $t0, $t1, 3 # $t0 = $t1 * 2^3
Now $t0 contains 0111 1000
You can verify this by performing decimal multiplication. 15 * 8 = 120.
Upvotes: 0
Reputation: 58437
[is it] possible to optimize this code?
A more compact way of doing the same thing would be:
sll $a1, $a1, 2
addu $a1, $a1, $a0 # $a1 = $a1 * 4 + $a0
Loop:
sw $zero, ($a0)
addiu $a0, $a0, 4
bne $a0, $a1, Loop
I'm making these assumptions:
$a0
and $a1
are not needed anymore after the loop ends. If they are needed, save the original values somewhere (in other registers or on the stack) before entering the loop, and restore them afterwards.$t0
starts out at zero. If not, you'll have to add $t0 * 4
to $a0
before the loop. I'm also assuming that the value of $t0
after exiting the loop is irrelevant.Upvotes: 0
Reputation: 41774
Shifting left will insert 0's, not 1's. So 0000 would still be 0000, 0001 will become 0100 after the shift
Upvotes: 1