Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Convert subroutines into x86 assembly Write the following subroutine in x86 asse

ID: 3679166 • Letter: C

Question

Convert subroutines into x86 assembly

Write the following subroutine in x86 assembly: Subroutine arguments are passed on the stack, and can be accessed within the body of the subroutine starting at address EBP+8. At the start of each subroutine: Save EBP on the stack Copy the current value of the stack pointer (ESP) to EBP Create space within the stack for each local variable by subtracting the appropriate value from ESP. For example, if your function uses four integer local variables, each of which contains four bytes, subtract 16 from ESP. Local variables can then be accessed starting at the address EBP-4. A subroutine's return value is typically stored in EAX. Write the following subroutine in x86 assembly: Given a single integer argument, n, return the nth value of the Fibonacci sequence-a sequence in which each value is the sum of the previous two values. The first 15 values are shown below-note that the first value is returned if n is 0, not 1.

Explanation / Answer

Int fib(int n) In assembly fib: subu $sp, $sp, 64 # Allocate stack frame of 64 btyes sw $ra, 20($sp) # Save return address sw $fp, 16($sp) # Save frame pointer sw $s0, 12($sp) # Save s0 addiu $fp, $sp, 28 # Setup stack frame #This is the first condition if (n == 0) then return 0 P1_fib: seq $t0, $a0, $zero beq $t0, $zero, B2_fib # if (n != 0) ==> goto P2 li $v0, 0 # else ==> return zero j exit_fib # This is the second condition if (n == 1) then return 1 P2_fib: seq $t0, $a0, 1 beq $t0, $zero, B3_fib # if (n != 1) ==> goto P3 li $v0, 1 # else ==> return 1 j exit_fib # This is the next condition ->else return fib(n-1) + fib(n-2); P3_fib: subu $s0, $a0, 1 # Save n - 1 in s0 move $a0, $s0 # arg1 = n -1 jal fib subu $a0, $s0, 1 # arg1 = n -2 move $s0, $v0 # Save fib(n-1) jal fib add $v0, $v0, $s0 # Return fib(n-1) + fib(n-2) exit_fib: lw $ra, 20($sp) # Restore return address lw $fp, 16($sp) # Restore frame pointer lw $s0, 12($sp) # Restore s0 addiu $sp, $sp, 32 # Pop stack frame jr $ra # Return to caller