2
votes

Assuming that the values of variables f, g, h, i, and j are stored in registers $s0, $s1, $s2, $s3, and $s4, respectively. Furthermore the base address of arrays of integers A and B are in registers $s6 and $s7 respectively.

Write MIPS assembly language code for following C language statements: f = g - A[B[4] + 2]

lw $s0, 16($s7)     #$s0 = B[4]
sll $s0, $s0, 2     #$s0 = B[4] * 4 
add $s0, $s6, $s0   #$s0 = A + B[4] * 4
lw $s0, 0($s0)      #$s0 = A[B[4]]
sub $s0, $s1, $s0   #f = g – A[B[4]]

I found the above example online but I don't understand how it really works. Second line, isn't it shift logical left? So why is it used like this in here, doing operation $s= B[4] * 4 instead of adding 2? Third line, why is it adding instead of doing something like first line? Fourth line, 0($s0)... meaning we are getting the index 0? Why?

I was have f = h + B[g] and f = g + A[h + B[1]]. I'm sorry if this is too much question but I just don't get it.

1
I find the shift puzzling as well. Neverminding that, the third works because you have the base address. $s0 has the offset so then it remains to add the two together. This just gets the address, so the fourth line actually loads it. - Ben
f = g – A[B[4]] doesn't seem to match f = g - A[B[4] + 2]... - Mooing Duck
I agree, I think that should be an add instead of sll. Unless I'm missing somethign here - Ben

1 Answers

3
votes

Second line, isn't it shift logical left? So why is it used like this in here, doing operation $s= B[4] * 4 instead of adding 2?

Performing a logical shift left by 2 bits multiplies a value by 4. While there isn't enough context here for me to say for sure, it's most likely that this is necessary because A is an array of 32-bit values, which are 4 bytes each. Thus, B[4] must be multiplied by 4 to turn it from an index into an offset within A.

Fourth line, 0($s0)... meaning we are getting the index 0? Why?

Because, at this point, $s0 is the address of A[B[4]] — in C terminology, it is the pointer &A[B[4]]. Loading the word at an offset of 0 from that address dereferences the pointer.

The sample code you're using appears to be missing the + 2. Adding that should be possible by modifying one instruction from what you have; I'll leave it to you to figure out what.