Short-comings of registers
 

Caveat:   registers are shared among all functions (subroutines):

  • Each subroutine need to use some CPU register to perform computations

This has consequences on the value inside a register before and after a function call instruction

A common source of error caused by sharing registers
 

An important effect when you call a function shown with an example:

 f1:                                           
                                              
       ...                                
       ...                                
       mov r0,#1     // Before function call to f2
       ...
       bl f2                              
       ...           // After function call to f2 
       ...                                 
       add r1, r1, r0                       
                                  
   

Question:   will the instruction add r1, r1, r0 always add 1 to register R1 ???

A common source of error caused by sharing registers
 

An important error explained with an example:

 f1:                                           
                       +---->  f2:  push {lr}
       ...             |            ...   
       ...             |            ...   
       mov r0,#1       |            mov r0, #9 
       ...             |            ...
       bl f2 ----------+            ...   
       ...   <--------------+       ...   
       ...                  |       ...    
       add r1, r1, r0       +------ pop {pc}
                                  
   

Answer:   NO !!! --- After the function call bl f2, the register r0 can be overwritten !!!

A common source of error caused by sharing registers
 

Recall:   an important rule in assembler programming:

  • CPU registers are shared by all subroutines

  • The value in any register used by a subroutine f1 can be changed after executing a subroutine call instruction (bl ...) !!!

       f1:                         
          ...                                
          mov r0,#1     // Before "bl f2", r0 = 1
          ...                       
          bl f2                      
          ... <-- All registers are suspect !! 
          ...
      

    I.e.: all registers are suspect after a bl instruction !!!

Consequence for non-leaf functions
 

  • A non-leaf function cannot store its parameters and local variables in registers

    Because:

      • A non-leaf function contains a bl instruction

      • and therefore, a non-leaf function may lose all the values in its parameters and local variables after executing the bl instruction

        (Because the called function will overwrite them....)