Let me explain register machine subroutines and their calling conventions step by step.
- Basic Subroutine Structure
; A subroutine typically has:
- Entry point (label)
- Body of computation
- Return point (stored in a register, usually 'cont')
- Calling Convention Rules:
- The caller must save any registers it needs after the call
- The caller must set up the continuation (return point)
- The callee must preserve registers it uses (except for return values)
- The callee returns by jumping to the stored continuation
- For Tree-like Calls (where a subroutine calls multiple other subroutines):
subroutine-A
(save reg1) ; Save caller's registers
(save reg2)
(save cont) ; Save return point
(assign cont (label after-B)) ; Set up call to B
(goto (label subroutine-B))
after-B
(save result) ; Save B's result
(assign cont (label after-C)) ; Set up call to C
(goto (label subroutine-C))
after-C
(restore temp) ; Get B's result back
(restore cont) ; Restore original return point
(restore reg2) ; Restore caller's registers
(restore reg1)
(goto (reg cont)) ; Return to caller
- Key Principles:
- Stack discipline: push/pop must be balanced
- Register saving: save before modifying
- Continuation management: each subroutine needs its return point
- Results: agree on which register holds the return value
- Common Patterns:
; Tail call (no need to save continuation)
(assign cont (reg saved-cont))
(goto (label next-routine))
; Non-tail call
(save cont)
(assign cont (label after-call))
(goto (label subroutine))
after-call
(restore cont)
- Example with Multiple Nested Calls:
(define factorial-machine
(make-machine
'(n cont val temp)
ops
'(start
(assign cont (label fact-done))
fact-loop
(test (op =) (reg n) (const 1))
(branch (label base-case))
(save cont) ; Save return point
(save n) ; Save current n
(assign n (op -) (reg n) (const 1))
(assign cont (label after-fact))
(goto (label fact-loop))
after-fact
(restore n) ; Restore original n
(restore cont) ; Restore return point
(assign val (op *) (reg n) (reg val))
(goto (reg cont))
base-case
(assign val (const 1))
(goto (reg cont))
fact-done)))
- Tips for Complex Call Trees:
- Draw the call graph to visualize the structure
- Label each edge with required register saves
- Plan register allocation to minimize saves
- Consider using temporary registers for intermediate results
- Document register usage conventions
Would you like me to elaborate on any of these aspects or provide more specific examples for your use case?