Section 1 TA: Roger Fong Meeting 8 Notes Reminder of a frame: +----+ SP ---> 7 | | temporaries: pushed and popped values for computations +----+ 6 | | local variable +----+ 5 | | local variable +----+ 4 | | return address +----+ 3 | | function parameter +----+ 2 | | function parameter +----+ FBR ---> 1 | | saved frame based register +----+ 0 | | rv: space for return variable +----+ Reminder of a FBR: - Register that always points to the bottom of the topmost frame on the stack - The location (cell) that the FBR points to contains the contents of the FBR before the topmost frame was constructed. Excersice to solidify functions in SAM === BALI CODE === % Main function main() int i, j, n; { i := 2; j := 8; n := pow(i, j); return n; } % function that performs exponentiation % assumes exp is a positive integer % returns num^exp pow(int num, int exp) int index, ans; { ans := 1; index := 0; while (index < exp) do { ans := ans * num; index := index + 1; } return ans; } === SAM CODE === PUSHIMM 0 // allocate space for rv PUSHFBR // save the current FBR value PUSHIMM 1 // the new FBR value POPFBR // store the new FBR value JSR main // after initialization, jump to main POPFBR // restore FBR STOP // STOP program // label for main function main: // note: no function parameters for main ADDSP 3 // allocate space for local vars PUSHIMM 2 STOREOFF 2 // set i to 2 PUSHIMM 8 STOREOFF 3 // set j to 8 // function call to pow PUSHIMM 0 // allocate space for rv PUSHFBR // save the current FBR value PUSHOFF 2 // push function param PUSHOFF 3 // push function param // compute new FBR ( SP - (# of Params+1)) PUSHSP // push SP value to top PUSHIMM 3 // push 1+number of params SUB // ( SP - (# of Params+1) ) POPFBR // pop the top value and store in FBR (FBR <- Vtop) JSR pow // make function call ADDSP -2 // remove param values POPFBR // restore FBR value STOREOFF 4 // set result to n PUSHOFF 4 // push off n value STOREOFF -1 // return n value ADDSP -3 // pop off local variables JUMPIND // return to caller // label for pow function pow: ADDSP 2 // allocate local vars PUSHIMM 1 STOREOFF 5 // set ans to 1 PUSHIMM 0 STOREOFF 4 // set index to 2 loopLabel: PUSHOFF 4 // push off index value PUSHOFF 2 // push off exp value LESS JUMPC trueCond // if index < exp, go to trueCond PUSHOFF 5 // push off ans value STOREOFF -1 // return ans value ADDSP -2 // deallocate local vars JUMPIND // return to caller trueCond: PUSHOFF 5 // push off ans value PUSHOFF 1 // push off num value TIMES // ans * num STOREOFF 5 // set ans to ans*num PUSHOFF 4 // push off index value PUSHIMM 1 ADD STOREOFF 4 // set index to index+1 JUMP loopLabel // jump back to while cond