// Basic: b.sam // // int main() { // int x,y; // x := 10; // y := 20; // return x+y; // } PUSHIMM 0 // space for return value of program (result of main()) PUSHFBR // save current FBR (starts at 0) PUSHIMM 1 // need to push 1 for FBR POPFBR // set FBR to 1 JSR main // invoke main and push return address on the stack POPFBR // reinstall old FBR STOP // end program main: // label of first command is function name ADDSP 2 // allocate local variables PUSHIMM 10 // push 10 STOREOFF 2 // store x (why 2? see below) PUSHIMM 20 // push 20 STOREOFF 3 // store y (why 3? see below) <======= see diagram for SaM PUSHOFF 2 // retrieve x up to this point PUSHOFF 3 // retrieve y ADD // x+y STOREOFF -1 // store x+y to return ADDSP -2 // pop off local variables JUMPIND // return to caller Stack for "see diagram" portion: +----+ Must account for local var positions in stack! 7 | | <-- SP To store x, use STOREOFF 2: +----+ --> STOREOFF params + 1 ra slot + 1 saved FBR slot + FBR 6 | 20 | --> STOREOFF 0 + 1 + 1 + 1 +----+ --> "store V[top] in V[3]" 5 | 10 | +----+ 4 | y | +----+ 3 | x | +----+ 2 | 5 | return address new frame +----+ ^ 1 | 0 | <-- FBR (FBR is 1, which means it points to address 1) ___|___ +----+ | 0 | 0 | return value V +----+ old frame