Stacks and Basic Procedure Calls

Procedure calls also map well to a stack: if procedure A calls procedure B, and B calls C, then C will return to B and B will return to A. The sequence of procedure calls and returns maps perfectly to pushes and pops on a stack. Because of this, virtually all processors provide support in the instruction set for stack operations.

Procedure Calls

Finally, there is a set of procedure call instructions:
jsr Jump to Subroutine (and push return address)
bsr Branch to Subroutine (and push return address)
rts Return from Subroutine (Pop return address into PC)

Procedure Call Example

We can see how the procedure call instructions work by using another simple example. In C, the example would be:


int i;

int p1() {
    return(1);
}

int p2() {
    return(p1());
}

main() {
   i = p2();
}

In the hc11, this could be translated to:


RAM     equ   $0000
STACK   equ   $ff
EEPROM  equ   $f800
RESET   equ   $fffe


     org   RAM
i    rmb   1

     org   EEPROM
p1   ldaa  #1       * First Procedure P1()
     rts            *    a = 1;

p2   jsr   p1       * Second Procedure P2()
     rts            *    return P1();

main lds   #STACK
     jsr   p2
     staa  i

end  bra   end

     org   RESET
     fdb   main

However, this does not really pass the outputs, or returns, as parameters. Therefore, let's really pass the outputs as parameters by creating space for them on the stack before calling the routines.

This HC11 code would now look like:


RAM     equ   $0000
STACK   equ   $ff
EEPROM  equ   $f800
RESET   equ   $fffe


     org   RAM
i    rmb   1

     org   EEPROM
p1   tsx            * First Procedure P1()
     ldaa  #1       
     staa  2,x      *    return 1;
     rts            

p2   clra           * Second Procedure P2()
     psha
     jsr   p1       
     pula
     tsx
     staa  2,x      *    return P1();
     rts            

main lds   #STACK   * Main Program
     clrb
     pshb
     jsr   p2       
     pulb
     stab  i        *  i = P2();

end  bra   end

     org   RESET
     fdb   main