Vin Vin - 3 months ago 57
C# Question

Converting to MIPS assembly Language with arrays

Not the best at converting, especially to MIPS assembly Language.

This was the original Code:

void swap(int v[], int k, int j) {
int temp;
temp = v[k];
v[k] = v[j];
v[j] = temp;
}


With some help we managed to get to this, now i need to convert this to MIPS Assembly code, only just finished learning Java still a noob. Any help is welcome.

k = k << 2;
k = k + v
j = j << 2;
j = j + v
temp0 = load(k)
temp1 = load(j)
store(k) = temp1
store(j) = temp0

Answer

Okay, here's the asm. It is predicated on the pseudo code above, but I wrote it from scratch, based upon the HLL at the top.

It is mips ABI conforming. Thus, it is at liberty to change (i.e. destroy) the argument registers. Thus, if called in a loop, caller must set a0-a3 before each call.

#   void
#   swap(int v[],int k,int j)
#   {
#       int temp;
#
#       temp = v[k];
#       v[k] = v[j];
#       v[j] = temp;
#   }

# swap -- swap two elements in an array
#
# arguments:
#   a0 -- pointer to array
#   a1 -- array index "k"
#   a2 -- array index "j"
#
# registers:
#   t0 -- v[k]
#   t1 -- v[j]
swap:
    sll     $a1,$a1,2               # k <<= 2 (i.e. byte offset)
    addu    $a1,$a1,$a0             # get address of v[k]

    sll     $a2,$a2,2               # j <<= 2 (i.e. byte offset)
    addu    $a2,$a2,$a0             # get address of v[j]

    lw      $t0,0($a1)              # fetch v[k]
    lw      $t1,0($a2)              # fetch v[j]

    sw      $t1,0($a1)              # v[k] = v[j]
    sw      $t0,0($a0)              # v[j] = v[k]

    jr      $ra                     # return