Subroutines and MIPS Calling Conventions

Subroutines Definition

  • A subroutine is a sequence of program instructions that performs a specific task and is packaged as a unit.
    • Also Known As: Procedure, function, routine, method, or subprogram.
    • Characteristics:
    • Reusable: Can be called multiple times throughout a program, promoting code efficiency.
    • Feature of High-Level Languages: Translated into machine code utilizing established conventions to ensure proper coordination between different subroutines.

Example of a Subroutine

```c
int SumSquares(int n) {
int sum = 0;
for (int i = 1; i <= n; i++)
sum = sum + i * i;
return sum;
}

- The `SumSquares` function takes an integer `n` and calculates the sum of squares of integers from 1 to `n`.

## Calling a Subroutine  
When calling a subroutine, several steps must be performed:
1. **Caller Responsibilities**:  
   - Make arguments accessible to the called subroutine.  
   - Transfer control to the called subroutine. 
2. **Callee Responsibilities**:  
   - Perform the desired task.  
   - Make the return value accessible to the calling routine.  
   - Return control to the calling routine.

### Specific Steps:
- **Caller**: Place arguments into registers $a0, $a1, $a2, and $a3.  
- **Caller**: Use the instruction `jal Label` to transfer control.  
- **Callee**: Return values are typically placed in registers $v0 and $v1.  
- **Callee**: Return control using `jr $ra`.  

## Use of Registers in Subroutine Calls  
### Caller Saved Registers
- **Registers Not Preserved Across Calls**: $t0 – $t9, $a0 – $a3, $v0, and $v1.  
  - **Callee can freely use these**: If the caller needs these values after the call, they must save them prior to the subroutine call.

### Callee Saved Registers
- **Registers Preserved Across Calls**: $s0 – $s7, $ra, $sp, $fp, and $gp.  
  - **Callee must save and restore** if it uses them.  
  - These registers retain their values after the call, providing stability in function execution.

### Example of Caller Responsibilities
- If you call a function with a signature like: `v = f(a) + f(a + 1);`, where `a` is in $a0, and the result is stored in $v0, the following operations must be done:

assembly

  1. move $s0, $a0 # Save a
  2. jal f # Call f(a)
  3. move $s1, $v0 # Store result of f(a) in $s1
  4. addi $a0, $s0, 1 # Update $a0 to a + 1
  5. jal f # Call f(a + 1)
  6. add $v0, $s1, $v0 # Combine results
    ```
Summary of MIPS Calling Conventions
  1. Argument Registers: Arguments are placed in $a0, $a1, $a2, and $a3.
  2. Return Values: Return values are placed in $v0 and $v1.
  3. Return Address: The return address is stored in $ra.
  4. Calling Subroutines: Use jal Label to call, and jr $ra to return.
  5. Register Preservation: Subroutines must preserve $s0 – $s7, $ra, $sp, $fp and $gp; callers must not assume $t0 – $t9, $a0 – $a3, $v0 or $v1 are preserved.