Week 6 Questions

Download Report

Transcript Week 6 Questions

CDA 3101 Discussion Section 06
MIPS
Assembly Language
Programming
Function Call and Recursive
1
Problem1
Write a function MinMax(&X, N) to find the minimum and
maximum of an array X of N integers. The address of the
array is passed in $a0, and the number of words in the array
is passed in $a1. The minimum and maximum are returned in
registers $v0 and $v1 respectively.
Also, write a short main program that
1.
Prompts user to enter 10 integers one by one to fill a
global integer array X of size 10
2.
Calls the MinMax function to find and return the
minimum and maximum of the array X.
3.
Prints the minimum and the maximum value.
2
System Calls
3
Problem 2
•
Implement a recursive function that determines if a
string is palindrome. The function should return 1 or 0 to
the calling function to indicate if the given string is
palindrome or not. You can assume that the string has
only characters from the set {a-z, A-Z}.
Note that:
– palindrome(X) = true, if |X| < 2
– palindrome(aXa) = palindrome(X), if |X| >= 2
4
Conventions for Registers
• Following registers should be spilled
to the stack
– $ra ($31)
– $a0-$a3 ($4-$7)
– $t0-$t7 ($8-$15)
Saved by caller on stack
before jal and restored
after returning from jal;
done only for registers
used after jal
– $s0-$s7 ($16-$23) Saved by called
procedure before
– $fp ($30)
rewriting and then
restored back before
returning
Conventions for
Function Call
• Before calling a function, the caller
must
– Save on stack
• $ra
• any $t registers that will be used after the
jal instruction
• Any $a registers that will be used after the
jal instruction
– Move arguments to $a0-$a3
– Execute jal instruction to jump to the
procedure
Conventions for
Function Call
• On entry, the called function must
– Save on stack
• any $s registers that it is going to overwrite
• Before returning, the called function must
– Save results in $v0-$v1
– Restore all $s registers values from the stack if
necessary
– Adjust $sp to point to the address it was
pointing to before this function was called
– Return to calling function by using jr $ra
Conventions for
Function Call
• After the function returns, the caller
must
– Read the results returned by the
function from $v0-$v1
– Restore $ra register values from stack
– Restore $t and $a register values from
stack, if their values were saved on
stack before function call
Key Points
• Dynamically allocate memory
li
$v0, 9
# Memory allocation service
li
$a0, <int>
# Allocate <int> bytes of mem.
syscall
move $t0, $v0
# Move address of array to safety.
• Recursion
self:
…
addi
sw
jal
lw
addi
$sp, $sp, -4
$ra, 0($sp)
self
#
$ra, 0($sp)
$sp, $sp, 4
# Allocate stack space
# Save old return address
Jump to self
# Load old return address
# Restore stack to old state
9