Call functions


A call to a function (subroutine in assembly-speak) causes a transfer of control to another part of program.  There are two instructions to use: jal (jump and link) and ret (return).

jal r1 ads          r1 is link register

The effect is

R[r1] = PC; pc = ads

ret r1

pc = R[r1]

The second important thing is how to pass parameters to subroutines.
1 through global variables
2 through registers
3 through stack

Stack data structure

A stack is a first in last out data structure.  It needs a stack pointer to access the data element.  See the following picture of stack.

Assume the operations are: push 1, push 2, push 3.

top
3
2
1

The operation: pop -> 3
top
2
1

The S2 instructions for stack operations are:

push r1 r2
pop r1 r2

r1 is stack pointer

push is R[r1]++; M[R[r1]] = R[r2]
pop  is R[r2] = M[R[r1]]; R[r1]--

The example how to call a subroutine.

main
  a = 2
  sq(a)

sq(x)
  return x * x

There are two things to be concerned.

1 how to pass parameters via stack
2 how to return a value from sub, through a register

Register convention

r31  stack pointer
r30 display  trap 1 trap 2...
r29 link register
r28 return value

.symbol
  a 100
.code 0
:main
  mv r1 #2
  st a r1     ;; a = 2
  ld r1 a
  push r31 r1
  jal r29 sq  ;; call sq(a)
  mv r30 r27
  trap 1      ;; print return value
  trap 0
:sq
  pop r31 r1
  mul r27 r1 r1
  ret r29

When there is a nested call to subroutines (or the recursive call), the link register must be saved and restored.

sub
....
push sp link
call xyz
...
pop sp link
ret link

fac n
  if n == 0 ret 1
  else return n * fac n -1

A subroutine is an "abstraction" of a program. It is a power tool of thought of programmers.  It is also called "factorization" in Software engineering practice.  It promotes the "reuse" of code among many programs.

End of lecture