Vin - 6 months ago 43

C Question

I was trying to convert C code to MIPS assembly. Here's a snippet. The problem is that i'm not too sure if i am going along the right track. I'm hoping, someone could help.

This was the original question:

`void swap(int v[], int k, int j) {`

int temp;

temp = v[k];

v[k] = v[j];

v[j] = temp;

}

and this is how far i have got:

`swap:`

addi $sp, $sp, -4

sw $s0, 0($sp)

add $s0, $zero, $zero

L1: add $t1, $s0, $a1

lb $t2, 0($t1)

add $t3, $s0, $a0

sb $t2, 0($t3)

beq $t2, $zero, L2

addi $s0, $s0, 1

j L1

L2: lw $s0, 0($sp)

addi $sp, $sp, 4

jr $ra

Alright this is as far as i have got. Am i doing this right or am i completely lost it!?

Answer

break it down and then implement it

v, k and j come in as registers we assume.

you need to build the address v+(k<<2) and v+(j<<2) You can use scratch registers, I assume you can trash the k and j incoming registers too since you wont need them anymore.

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

and you should be able to convert that to asm, can re-arrange some of the instructions and have it still work.

Edit, I will let you figure it out, but I didnt cheat and compile first. But found that gcc produced the same basic sequence of instructions. Two shifts, two adds two loads, then two stores.