SUBROUTINE &STACK

SUBROUTINE &STACK 

  1.      In  a given program ,it is often necessary to perform a particular task many times on
 different data values .When a program branches to a subroutine, we say that it is calling the 
subroutine .The instruction that performs the branch operation is called a call_subroutine 
instruction.After a subroutine has been executed, subroutine is said to return to the program 
that called it  by executing a Return instruction .The calling program must resume 
execution , continuing  immediately after the instruction that called the subroutine.



Call subroutine is a special branch instruction that performs the following operations
store the contents of the PC in the link register (LR)
branch to the target address specified by the instruction
The return from a subroutine branches to the address contained in the link register .

Subroutine Nesting and The Processor Stack

When one subroutine calls another,The return address of the second call is also stored in 
the link register .It is essential to save the content of the link register in another location 
before issuing a new call ,otherwise the return address of the first subroutine will be 
lost . A stack data structure can be used to store the return addresses associated with 
subroutine calls .Call-subroutine pushes the content of the PC onto the stack and loads 
the subroutine address into the PC .The return instruction pops the return address from 
the stack into the PC .



Parameter Passing Using the Stack

The exchange of information between a calling program and a subroutine is referred to as 
parameter passing.
When calling a subroutine, a program may provide to the subroutine the parameters, ( the 
operands or their addresses) to be used in the computation.
Later, the subroutine returns other parameters, ( the results of the computation. ) to the 
calling program .
If many parameters are involved, there may not be enough general-purpose registers  
available for passing them to the subroutine.
Alternatively, parameters can be placed on the stack  ( stack can handle a large number of 
parameters)
 In the below example subroutine uses three registers , the contents of these registers are 
saved by pushing them on the stack using the move_multiple instruction .Before return, 
they are restored .
                                                


Comments

Popular posts from this blog

COMPUTER ORGANISATION & ARCHITECTURE TUTORIAL 1