user1631224
user1631224

Reputation: 409

How to store offset in the base array of this MIPS code?

I stuck on this problem. I am given a C code and I need to convert it to MIPS.

Here is the C code:

for (c = 0; c < a; c++)
    for (d = 0; d < b; d++)
        D[8*d] = c + d;

assume the values of a, b, c, d are in the registers $s0, $s1, $t0, and $t1. Also the register $s2 contains the base address of array D.

Here is my following MIPS code so far:

       add   $t0, $zero,  $zero     # initialize c = 0
LOOP1: slt   $t2, $t0,    $s0       # temp reg $t2 = 1 if $t0 < $s0
       beq   $t2, $zero,  DONE      # if $t2 = 0, go to DONE
       add   $t1, $zero,  $zero     #initialize d = 0
LOOP2: slt   $t3, $t1,    $s1       # temp reg $t3 = 0 if $t1 < $s1
       beq   $t3, $zero,  L1        # if $t3 = 0, jump to L1 (current iteration of
                                    #LOOP1)
       sll   $t1, $t1,    3         # $t1 = $t1 << 8 where (8 * d)

       ????

       addi  $t1, $t1,    1         # increment d = d + 1
       j     LOOP2                  # jump back to LOOP2
  L1:  addi  $t0, $t0,    1         # increment c = c + 1
       J     LOOP1                  # jump back to LOOP1
DONE:

Where I'm stuck is in the "????" because I dont know how to store $t1 containing 8*d, back into $s2.

Thanks

Upvotes: 0

Views: 298

Answers (1)

One problem is that you overwrite the value that's in d every time through LOOP2 - with the statement sll $t1, $t1, 3 you're saying 'replace d with d * 8'. You should store that in another temp register so you don't clobber your loop counter - ie. sll $t4, $t1, 3.

Next you need to figure out what the address D[8 * d] is. Since you already have 8 * d stored in register $t4, it's just a matter of adding those two registers together - add $t5, $s2, $t4. Now, $t5 contains the address you need to store into.

The only things left are computing the value and storing it - to compute it is simple, it's just c + d so all you need is to store that in another temp register - add $t6, $t0, $t1.

Now, $t6 contains the value, and $t5 the address. You just need to store $t6 into $t5 - sw $t6, ($t5).

Upvotes: 1

Related Questions