Docsity

MIPS Assembly Code Questions, Exercises of Computer Architecture and Organization

Partial preview of the text

Download MIPS Assembly Code Questions and more Exercises Computer Architecture and Organization in PDF only on Docsity!

MIPS Assembly Code Questions

1. Translate the following C Code into MIPS Assembly code. C Code:

. data 0x sos:. word 3 , 4 , 2 , 5 , 1 , 0 , โˆ’ 2 , โˆ’ 5 mna:. word 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 . text . globl main main: li $s18, 6 # Initialize and define i counter variable for the

for loop - load immediate value 6 to

Register No 18 ($s2)

la $s20, sos # Load array address in to Register No 20 ($s4) la $s21, mna # Load array address in to Register No 21 ($s5) $4 = a, $5 = b, $6 = c lw $4,0($20) # sos[0] lw $5,0($20) # sos[1] lw $6, 4 ($20) # sos[2] jal max sw $2, 0($21) Loop: lw $4,0($20) # sos[i-1] lw $5,4($20) # sos[i] lw $6,8($20) # sos[i+1] addi $20, $20, 4 addi $21, $21, 4 jal max sw $2, 0($21) addi $18, $18, - 1 bne $18, $0, loop lw $4,0($20) # sos[6] lw $5,4($20) # sos[7] lw $6,4($20) # sos[7] addi $20, $20, 4 addi $21, $21, 4

2. Translate the following C Code into MIPS Assembly code. void f (int i, int t []) { int n; for(n = 0; n < 10; n++) t[n] = 10-n; g(i); } void g (int i, int t []) { int n; for(n = 0; n < 10; n++) t[n] = 10-n; g(i); } Useful information: i. Assume that the start address of t is stored already in $ ii. Save $5, $7, $8, $31 to stack iii. Use $29 for $sp to save registers into the stack iv. Hint : $4 means the $a1 which has the number 4 in the MIPS register list. v. In function j : a. store argument n into $ b. store n into $ c. store the result of n < 10 into $ d. store the address of t[n] into $ e. store the value of t[n] into $ vi. In function g : a. store argument k into $ b. store the value 5 into $ c. store n into $

f: addi $29, $29, - 20 # save $5, $7, $8, $31 to stack sw $5,0($29) # $5 is modified for n sw $6,4($29) # $ 6 is modified for n sw $7,8($29) # $ 7 is modified for jal sw $8,12($29) # $ 8 is modified for jal sw $31,16($29) # $ 31 is modified for jal li $5,0 # For loop init: n= testfor: slti $6,$5,10 # For Loop Condition beq $6,$0,exitfor # exit if (n >= 10) sll $7,$5,2 # 4n add $7,$7,$10 # t[] + 4n li $8,10 # 10 sub $8,$8,$5 # 10 โ€“ n sw $8, 0($7) # for body addi $5,$5,1 # update n = n + 1 j testfor # loop for the test exitfor: # for exits to here jal g # call g (argument i is already in $4) sw $5,0($29) # $5 recovered from stack sw $6,4($29) # $ 6 recovered from stack sw $7,8($29) # $ 7 recovered from stack sw $8,12($29) # $ 8 recovered from stack sw $31,16($29) # $ 31 recovered from stack addi $29,$29,20 # adjust stack pointer jr $31 # procedure f returns to caller g: addi $29, $29, - 12 # callee saves registers modified by g sw $ 4 ,0($29) # $ 4