Subroutines Flashcards
What are Subroutines used for and what are the two types?
Subroutines allow you to repeat a calculation using varying argument values
Open (inline)
Closed
How does Open (inline) work?
Code is inserted inline wherever the subroutine is invoked (usually using a macro preprocessor)
Arguments are passed in/out using registers
It is efficient since overhead branching and returning is avoided
Suitable for fairly shorter routines
How does Closed work?
Machine code for the routine appears only cone in RAM which leads to more compact machine code than with open routines
When invoked, jumps to the first instruction of the routine (PC is loaded with the address of the first instruction)
When finished, control returns to the next instruction in the calling code (PC is loaded with the return address)
Arguments are placed in registers on the stack
Slower than open routines because of the call/return overhead
What should Subroutines NOT do?
They should not change the state of the machine for the calling code
When invoked, they should save any registers it uses on the stack
What are arguments to subroutines considered to be?
Local Variables - the subroutines may change their value
Check Notes for examples of Open and Closed
.
How may a subroutine be invoked?
Using a branch and link instruction (bl)
Form: bl subroutine_label
Stores the return address into the link register: x30
Return address is PC + 4, which points to the instruction immediately following bl
Transfer control to the address specified by the label
Loads the PC register with the address of the subroutine’s first instruction
In calling code, the _______ of a variable is passed to the subroutine
What does it imply?
address
Implies that the variable must be in RAM, not in a register (since registers don’t have addresses)
The called subroutine ____________ the address, to manipulate the variable being pointed to
How is it done?
dereferences
Done with an ldr or str instruction
Example code for Pointer args in Notes
.
What does a function return for x0 and w0?
long ints in x0
ints, short ints, and chars in w0
Example in Notes
In C, a function may return a struct by value. The struct is usually too big to return in x0 or w0. Which other mechanism is used instead?
The calling code provides memory on the stack to store the returned result
The address of this memory is put into x8 prior to the function call
The called subroutine writes to memory at this address using a pointer to it
Example in notes
x8 is the _____________ register
indirect result location
What are leaf subroutines?
They do not call other subroutines
Is a frame record pushed on the stack?
No, since the routine does not do a bl, LR won’t change and since the routine does not call a subroutine, FP won’t change. Thus, eliminate the usual stp/ldp instructions