MIPS Assembly Language CPSC 321 Computer Architecture Andreas
MIPS Assembly Language CPSC 321 Computer Architecture Andreas Klappenecker
Addressing modes lw $s 1, addr # load $s 1 from addr lw $s 1, 8($s 0) # $s 1 = Mem[$s 0+8] register $s 0 contains the base address access the address ($s 0) possibly add an offset 8($s 0)
Branch instructions beqz $s 0, label if $s 0==0 goto label bnez $s 0, label if $s 0!=0 goto label bge $s 0, $s 1, label if $s 0>=$s 1 goto label ble $s 0, $s 1, label if $s 0<=$s 1 goto label blt if $s 0<$s 1 $s 0, $s 1, label goto label beq $s 0, $s 1, label if $s 0==$s 1 goto label bgez $s 0, $s 1, label if $s 0>=0 goto label
Non-leaf procedures n n n Suppose that a procedure proc. A calls another procedure jal proc. B Problem: jal stores return address of procedure proc. B and destroys return address of procedure proc. A Save $ra and all necessary variables onto the stack, call proc. B, and retore
Stack The stack can be used for high address 4($sp) § parameter passing § storing return addresses § storing result variables 8($sp) stack pointer $sp --> low address § stack pointer $sp = $sp - 12 0($sp)
Factorial n n Compute n! Recall that n n 0! = 1 1! = 1 n! = n(n-1)! Store on the stack n n $s 0 = n, the parameter $ra, the return address
factorial: bgtz $a 0, doit # if $a 0>0 goto generic case li $v 0, 1 # base case, 0! = 1 jr $ra # return doit: sub $sp, 8 # make room for $s 0 and $ra sw $s 0, ($sp) # store argument $s 0=n sw $ra, 4($sp) # store return address move $s 0, $a 0 # save argument sub $a 0, 1 # factorial(n-1) jal factorial # v 0 = (n-1)! mul $v 0, $s 0, $v 0 # n*(n-1)! lw $s 0, ($sp) # restore $s 0=n lw $ra, 4($sp) # restore $ra add $sp, 8 # reduce stack size jr $ra # return
Fibonacci fib(0) = 0 fib(1) = 1 fib(n) = fib(n-1) + fib(n-2) 0, 1, 1, 2, 3, 5, 8, 13, 21, …
Fibonacci li $a 0, 10 # call fib(10) jal fib # move $s 0, $v 0 # $s 0 = fib(10) fib is a recursive procedure with one argument $a 0 need to store argument $a 0, temporary register $s 0 for intermediate results, and return address $ra
fib: gen: rreg: subi $sp, 12 # save registers on stack sw $a 0, 0($sp) # save $a 0 = n sw $s 0, 4($sp) # save $s 0 sw $ra, 8($sp) # save return address $ra bgt $a 0, 1, gen # if n>1 then goto generic case move $v 0, $a 0 # output = input if n=0 or n=1 j rreg # goto restore registers subi $a 0, 1 # param = n-1 jal fib # compute fib(n-1) move $s 0, $v 0 # save fib(n-1) sub $a 0, 1 # set param to n-2 jal fib # and make recursive call add $v 0, $s 0 # $v 0 = fib(n-2)+fib(n-1) lw $a 0, 0($sp) # restore registers from stack lw $s 0, 4($sp) # lw $ra, 8($sp) # addi $sp, 12 jr $ra # decrease the stack size
Practice, practice!!! n n Read Chapter 3 and Appendix A Write many programs and test them Get a thorough understanding of all assembly instructions Study the register conventions carefully
- Slides: 11