3

I am stumbling over the Exercise 2.3 of Chapter 2, i.e.:

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 $s_0$, $s_1$, $s_2$, $s_3$, and $s_4$, respectively. Assume that the base address of the arrays A and B are in registers $s_6$ and $s_7$, respectively.

B[8] = A[i−j];

So, in the solution (https://github.com/dmohindru/cod5e/blob/master/solutions/CH02_Solution.pdf), it is indicated, that after calculating i-j and adding to the base address

sub t0, s3, s4
add t0, s6, t0

the word is loaded by

lw t1, 16(t0)

But why 16?

In my humble opinion, that should be either shifted left by two or multiplied by four

mul t0, t0, 4
lw t1, 0(t0)

to regard the 4-byte offset.

Or am I wrong?

xskxzr
  • 7,613
  • 5
  • 24
  • 47
lordsnyder
  • 33
  • 3

1 Answers1

2

You are correct. The number of bytes of offset from the base address of array $A$ is $4*(i-j)$ and this multiplication by $4$ can be achieved by doing an sll (shift left) operation by two bits. Here's the assembly code for $B[8] = A[i-j]$:

sub $t0, $s3, $s4   #temp register $t0 = i - j
sll $t0, $t0, 2     #temp register $t0 contains 4*(i-j)
add $t0, $s6, $t0   #t0 = address of A[i-j]
lw $t1, 0($t0)      #t1 = A[i-j]
sw $t1, 32($s7)     #B[8] now equals A[i-j]
Ashwin Ganesan
  • 1,388
  • 7
  • 10