7: MIPS Functions and the Stack Segment Page 1 7 MIPS Functions and the Stack Segment 7.1 Objectives After completing this lab, you will: • Write MIPS functions, pass parameters, and return results • Understand the stack segment, allocate, and free stack frames • Understand the MIPS register usage convention • Write recursive functions in MIPS 7.2 MIPS Functions A function (or a procedure) is a tool that programmers use to structure programs, to make them easier to understand, and to allow the function’s code to be reused. A function is a block of instructions that can be called and used when required at several different points in the program. The function that initiates the call to another function is known as the caller . The function that receives and executes the call is known as the callee . When the callee function finishes execution, control is transferred back to the caller function. A function can receive parameters and return results. The parameters and results act as an interface between a function and the rest of the program. To execute a function, the program must follow these steps: 1. The caller must put the parameters in a place where the callee function can access them 2. Transfer control to the callee function 3. Execute the callee function 4. The callee function must put the results in a place where the caller can access them 5. Return control to the caller (point of origin) next to where the call was made Registers are the fastest place to pass parameters and return results. The MIPS architecture follows the following software conventions for passing parameters and returning results: • $a0-$a3 : four argument registers in which to pass parameters • $v0-$v1 : two value registers in which to return function results • $ra : one return address register to return back to the caller
7: MIPS Functions and the Stack Segment Page 2 The jal (jump-and-link) instruction initiates the call to a function and the jr (jump register) instruction returns control back to the caller. To call a function, use the jal instruction as follows: jal label The jal instruction saves the return address in register $ra and jumps to the first instruction in the function after label . The return address is the address of the next instruction that appears after the jal instruction in the caller function. To return from a function, use the jr instruction as follows: jr $ra The jr instruction jumps to the address stored in $ra . It modifies the program counter PC register according to the value stored in register $ra . An example of a C function that checks whether a character ch is a lowercase letter or not is shown in Figure 7.1. The function is translated into MIPS assembly language as shown to the right. The function islower assumes that the parameter ch is passed in register $a0 . The function result is passed in register $v0 .
You've reached the end of your free preview.
Want to read all 8 pages?
- Spring '13