lectures.alex.balgavy.eu

Lecture notes from university.
git clone git://git.alex.balgavy.eu/lectures.alex.balgavy.eu.git
Log | Files | Refs | Submodules

index.md (1593B)


      1 +++
      2 title = 'Subroutines & the stack'
      3 +++
      4 # Subroutines & the stack
      5 ## Subroutines
      6 
      7 allow a block of instructions to be called any number of times without having to rewrite it
      8 
      9 calling a subroutine:
     10 1. Store contents of PC in link register (contains return address)
     11 2. Branch to target address specified by call instruction
     12 3. Execute whatever code is there
     13 4. When return is called, branch to address in link register
     14 
     15 when nesting, the return address is pushed to the stack by the caller. on return the callee pops the saved return address from the stack into the link register.
     16 
     17 parameters can be passed by:
     18 
     19 - registers — convenient & efficient, but may not be enough registers
     20 - processor stack — can pass an arbitrary amount of parameters
     21 
     22 ## Stack
     23 a pile of stuff where the stuff can only be added to or taken from the top
     24 
     25 also called LIFO (last-in-first-out)
     26 
     27 push (add elements)
     28 1. subtract 4 from SP (32-bit)
     29 2. move value from register to address stored in SP
     30 
     31 pop (remove elements)
     32 1. move value from byte at address stored in SP to register
     33 2. add 4 to SP (32-bit)
     34 
     35 processor stack is used for storing data, e.g. parameters, registers
     36 
     37 stack pointer register (SP) holds address of top element in stack
     38 
     39 ‘grows downwards’ — from high to low addresses, decreasing size
     40 
     41 stack fame — ‘private workspace’ for a subroutine
     42 
     43 - allocated at start, deallocated at end of subroutine
     44 - can also be used for local memory variables
     45 - base/frame pointer points to base of current frame, can easily access parameters by using offset(%rbp)
     46 
     47 ![screenshot.png](screenshot-24.png)