title: Save registers on a stack in a procedure call in Assembly
body: <p>I'm taking an intro course on Assembly and I encountered the following code. I'm not sure how stacks work here. This is the C code that's supposed to be translated into Assembly: (Sorry I forgot to mention we are using MIPS)</p>
  
  <pre><code>int leaf_example (int g, h, i, j) {
       int f;
       f = (g + h) - (i + j);
       return f;
  }
  </code></pre>
  
  <p>In class, the professor says the correct translation should be: (I added my questions in the comments)</p>
  
  <pre><code>leaf_example:
     addi $sp, $sp, -12 # Why do we need to allocate 3 bytes for each register?
     sw $t1, 8($sp) # I don't really understand the meaning of this line and the next two lines
     sw $t0, 4($sp)
     sw $s0, 0($sp)
     add $t0, $a0, $a1
     add $t1, $a2, $a3
     sub $s0, $t0, $t1
     add $v0, $s0, $zero
     lw $s0, 0($sp) # After we sw the registers on the stack, why do we need to load them back?
     lw $t0, 4($sp)
     lw $t1, 8($sp)
     addi $sp, $sp, 12
     jr $ra
  </code></pre>
  
  <p>I think I have a vague understanding of how $s registers differ from $t registers: when calling a function, contents of $s registers stays the same, but contents of $t registers are not guaranteed to stay the same. But how does this fact relate to pushing the registers onto the stack? Thank you very much for your help!</p>