In: Computer Science
1.) Translate the following C code to MIPS assembly code. Assume that the variables f, g, h, i, and j are assigned to registers $s0, $s1, $s2, $s3, and $s4, respectively. Assume that the base address of the arrays A and B are in registers $s6 and $s7, respectively
B[8] = A[i-j];
2.Translate the following C code to MIPS assembly code. Assume that the values of v in $a0, k in $a1, temp in $t0.
// leaf procedure that swaps v[k] and v[k+1]
void swap(int v[], int k)
{
int temp;
temp = v[k];
v[k] = v[k+1];
v[k+1] = temp;
}
(1) Convert the following C language code to Assembly language code:
B[8] = A[i - j];
Suppose that variables i and j are in register $s3 and $s4 respectively. Base address of A and B arrays are assigned to $s6 and $s7 registers.
Answer:
sub $t0, $s3, $s4
sll $t0, $t0, 2
add $t0, $s6, $t0
lw $t1, 0($t0)
sw $t1, 32($s7)
Description:
sub $t0, $s3, $s4 ; subtract $s3 - $s4 and store in $t0 temporary register. $t0 = i - j
sll $t0, $t0, 2 ; shift left logical $t0 register by 2 bits. $t0 = [i-j] * 4
add $t0, $s6, $t0 ; addition of $s6 + $t0 and store in $t0 temporary register. Add array A's address.
lw $t1, 0($t0) ; load word from memory location 0($t0) to $t1 register. $t1 ← A[i - j]
sw $t1, 32($s7) ; store word from $t1 to 32($s7) memory location. $t1 → B[8]
(2) Convert the following C language code to Assembly language code:
Procedure for swapping v[k] and v[k+1] where v, k and temp are assigned to $a0, $a1 and $t0 register respectively.
void swap(int v[], int k)
{
int temp;
temp = v[k];
v[k] = v[k+1];
v[k+1] = temp;
}
Answer:
swap: sll $t1, $a1, 2
add $t1, $a0, $t1
lw $t0, 0($t1)
lw $t2, 4($t1)
sw $t2, 0($t1)
sw $t0, 4($t1)
jr $ra
Description:
swap: sll $t1, $a1, 2 ; shift left logical $a1 register by 2 bits. $t1 = k * 4
add $t1, $a0, $t1 ; Addition of $a0 + $t1 and store in $t1 register. $t1 = v + k * 4
lw $t0, 0($t1) ; load word from memory location 0($t1) to $t0 register. $t0 = v[k]
lw $t2, 4($t1) ; load word from memory location 4($t1) to $t2 register. $t2 = v[k+1]
sw $t2, 0($t1) ; store word from $t2 to 0($t1) memory location. v[k] = $t2
sw $t0, 4($t1) ; store word from $t0 to 4($t1) memory location. v[k+1] = $t0
jr $ra ; jump register to return address in $ra. Return back to the calling routine.