I've started studying assembly, and I've been tryign to solve this problem:
For the following C statement, what is the corresponding MIPS assembly code? Assume that the variables f, g, h, i, and j are assigned to registers $s0, $s1, $s2, $s3, and $s4, respectively. Assume that the base address of the arrays A and B are in registers $s6 and $s7, respectively:
B[8] = A[i−j];
Source: Computer Organization and Design 5th Edition.
So, I did this:
sub $t0, $s3, $s4 // temp = i - j
sll $t0, $t0, 2 // temp = temp*2^2= 4*temp
add $t0, $t0, $s6 // temp = &A[i-j]
lw $t1, 0($t0) // t1 = temp
sw $t1, 32 ($s7) // B[8] = t1 = temp = A[i-j]
But looking at the book's solution manual to verify that my answer is correct, I got this:
sub $t0, $s3, $s4
add $t0, $s6, $t0
lw $t1, 16($t0)
sw $t1, 32($s7)
I am confused. How did they come up with the third statement lw $t1, 16($t0)
?
-
1\$\begingroup\$ I'm not familiar with MIPS assembly language so I don't know if your code is correct, but there are usually many different ways to solve a single problem. One way is not necessarily better than the other way. \$\endgroup\$jippie– jippie2016年06月04日 10:09:17 +00:00Commented Jun 4, 2016 at 10:09
-
1\$\begingroup\$ Assume: Base address of A =28 And I-J = 3 so we want to access the 3rd element from the array A in this case the desired byte address will be 28+3*4 = 40 according to the book solution manual the accessed byte address will be 28 +3 + 16 = 47 this is not even a number divisible by 4 .So this answer seems wrong \$\endgroup\$Elbehery– Elbehery2016年06月04日 10:26:55 +00:00Commented Jun 4, 2016 at 10:26
-
1\$\begingroup\$ The book's answer also seems incorrect to me. \$\endgroup\$Stack Exchange Broke The Law– Stack Exchange Broke The Law2016年06月04日 10:33:59 +00:00Commented Jun 4, 2016 at 10:33
2 Answers 2
The books solution is wrong:
sub $t0, $s3, $s4
add $t0, $s6, $t0
lw $t1, 16($t0)
sw $t1, 32($s7)
The use of lw
and sw
instruction imply that the arrays A and B are 32 bit in size, otherwise instructions such as lb/lbu, lh/lhu would be used to load 8 or 16 bit wide entities (or LD, SD for 64 bit machines).
However, the address calculation does not take the size of the elements into account. This causes the address calculation to be wrong.
You did it right by scaling the offset into the array using the sll instruction.
I am confused. How did they come up with the third statement lw $t1, 16($t0) ?
The offset of 16 makes no sense in this context. The offset of 32 in the store instruction is fine because it directly addresses element 8 in the B array as it should.
I have the same solution manual. It is not wrong, it is just answering question 2.4.1. The question you are asking about is Exercise 2.4, which is not included in the solution manual. What you did is correct.
-
\$\begingroup\$ It is answering another question, so it is still wrong. \$\endgroup\$Online User– Online User2018年09月18日 17:10:50 +00:00Commented Sep 18, 2018 at 17:10