1 / 54

Ch. 8 Functions

Ch. 8 Functions. Functions. High-level languages have functions (methods) For modularity – easier to change To eliminate duplication of code – code reuse allows different programmers to write different parts of the same program Assembly language programs have similar structure.

cardea
Download Presentation

Ch. 8 Functions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Ch. 8 Functions

  2. Functions • High-level languages have functions (methods) • For modularity – easier to change • To eliminate duplication of code – code reuse • allows different programmers to write different parts of the same program • Assembly language programs have similar structure Comp Sci 251 -- functions

  3. High-level function example void helloWorld(){ print("Hello, world"); } void main(){ helloWorld(); . . . } Comp Sci 251 -- functions

  4. Mechanism for implementing functions Steps in the invocation and execution of a function: • save return address • call the function • execute the function • return Comp Sci 251 -- functions

  5. Machine Language mechanism • What is the return address? • Address of the instruction following call • What is the function call? • jump or branch to first instruction in the function • What is a return? • jump or branch to return address Comp Sci 251 -- functions

  6. Functions in assembly language • Labels to name functions • Instructions to support function call & return • System stack to track pending calls • Programming conventions for parameter passing Comp Sci 251 -- functions

  7. .text # Prints the string # "Hello, world" helloWorld: la $a0, hello li $v0, 4 syscall jr $ra __start: jal helloWorld ... .data hello: .asciiz "Hello, world" MIPS function example Comp Sci 251 -- functions

  8. Assembly language functions • Function name Label on first instruction • Function call: Jump And Link instruction: jal label • Jump to label • Save return address in $ra Comp Sci 251 -- functions

  9. Assembly language functions • Return from function Jump Register instruction: jr Rsrc Jump to the address in the register jr $ra jump to return address Comp Sci 251 -- functions

  10. Code Review • See helloFunc.a in /shared/huen/251 Comp Sci 251 -- functions

  11. Complications: • What if function calls another function? • Must keep track of multiple return addresses • There is only one $ra i.e. $31 • What if a function modifies some registers? • Should it restore the original values before returning? • Solution: • have a way to save return addresses as they are generated • This data is generated dynamically; while the program is running. • These return addresses will need to be used (for returning) in the reverse order that they are saved. • use system stack Comp Sci 251 -- functions

  12. Program memory model Memory contains three important segments • Text segment: program instructions • Data segment: global variables & constants • Stack segment: arguments & local variables Comp Sci 251 -- functions

  13. System stack • Stack: Last-in-first-out (LIFO) data structure • Push: place a new item on the top • Pop: remove the top item • Implementation • Stack segment of memory holds stacked items • Each item is one word • $sp register points to top of stack • Stack grows toward low addresses $sp Stacked items Comp Sci 251 -- functions

  14. Push $t0 to top of stack: subu $sp, $sp, 4 sw $t0, ($sp) Pop top of stack to $t0: lw $t0, ($sp) addu $sp, $sp, 4 Stack operations Low word $sp High Comp Sci 251 -- functions

  15. Example: Problem - stack1.a • Problem: Count the number of negative integers on the stack by popping the stack until a non-negative integer is found, and print out the number of words popped. Comp Sci 251 -- functions

  16. Example: Solution stack1.a • Integers from an array are first pushed onto the stack • Then the integers are popped and checked in turn until a non-negative integer is encountered • Prints out the count • The program portion to be written should be independent of the data and the rest of the program given Comp Sci 251 -- functions

  17. .text .globl __start __start: # execution starts here la $t0, test # This code sets up the stack lw $t1, num # Do not alter loop: lw $t2, ($t0) subu $sp, $sp, 4 # push stack w/ integers sw $t2, ($sp) # from test array add $t0, $t0, 4 add $t1, $t1, -1 bnez $t1, loop # Stack is set up now.... # At this point, the stack looks somewhat like # the following but in hexadecimal of course: # $sp ->| -9| # | -4| # | -3| # |0xfffabfff| # |0xffffffd5| # | 2| # | etc. | # Put your answer between dashed lines. Comp Sci 251 -- functions

  18. # loop to pop the stack and count # Put your answer between dashed lines. #-------------- start cut ----------------------- li $t3, 0 # count = 0; next: lw $t2, ($sp) # pop the stack addu $sp, $sp, 4 bgez $t2, done # encounter non-negative addi $t3, $t3, 1 # count++ j next # At this point, the stack looks somewhat like # the following but in hexadecimal of course: # | -9| # | -4| # | -3| # |0xfffabfff| # |0xffffffd5| # $sp ->| 2| # | etc. | # done: Comp Sci 251 -- functions

  19. Example 2 stack2.a • The stack is set up with integers and the top of stack contains the number of integers • Required to find the sum of integers on the stack • The top of stack number should not be included. Comp Sci 251 -- functions

  20. Use of system stack • Stores temporary information • Key support for functions • Pending function calls • Saved register values • Parameters • Local variables Comp Sci 251 -- functions

  21. f: jal g #call g jr $ra #return g: jr $ra #return __start: jal f #call f Main calls f $ra = return addr. to main f calls g $ra = return addr. to f Problem: return addr. to main lost. Solution? Functions that call functions Comp Sci 251 -- functions

  22. f: # push $ra subu $sp, $sp, 4 sw $ra, ($sp) . . . jal g #call g . . . # pop $ra lw $ra, ($sp) addu $sp, $sp, 4 . . . jr $ra # f return g: . . . jr $ra # g return _start: jal f #call f Functions that call functions Comp Sci 251 -- functions

  23. Leaf vs. non-leaf functions • Leaf function: • Does not call other functions • No need to save & restore $ra • Non-leaf function: • Calls other functions • Must save & restore $ra (use the stack) Comp Sci 251 -- functions

  24. MIPS function structure • Prologue: push items on stack • Body: do required computation • Epilogue: pop items off stack & return Comp Sci 251 -- functions

  25. What items must be stacked? • $ra (if function is non-leaf) • Some registers… • But not others… Comp Sci 251 -- functions

  26. MIPS register conventions • Callee-saved registers $s0 -- $s7, $ra, $sp, $fp • All functions must guarantee: value upon return == value before call • Caller-saved registers: $t0--$t9 • Functions may freely modify these $t_ registers • Caller must save these registers $t_ if values will be re-used after the call Comp Sci 251 -- functions

  27. Return value • Some functions return a value • MIPS register convention: use $v0 Comp Sci 251 -- functions

  28. Functions with parameters • Parameters are special local variables • Initial values come from arguments • More MIPS register conventions Arguments: $a0 -- $a3 Comp Sci 251 -- functions

  29. Example: Vowel Count -1 • Count the number of vowels in a string str • Main program • Call vcount with the address of str • Print the return value • function vcount( address of String str) • Checks one char at a time for vowel • returns the number of vowels in str • function vowelp( char c) • Returns 1 if c is a vowel, 0 if not Comp Sci 251 -- functions

  30. Example: vowel count -2 • Main program • a0 points to str • Calls vcount passing a0 • Print answer • Terminate the program Comp Sci 251 -- functions

  31. Example: vowel count-3 • Function Vcount • Input: a0 holds address of str • Internal: s0 holds number of vowels, i.e. count • s1 points to a character in str • Output: v0 holds result • Pseudo code count = 0; set s1 to point to first character in str and call the character c while (c != 0) { count += vowelp( c ); // call another function vowelp move s1 to point to next character and call it c } Done: return count; Long time ago in a galaxy far away s1 Comp Sci 251 -- functions

  32. Example: vowel count-4 • Function int vowelp(char c) result = 0; if c == ‘a’ result = 1; if c == ‘e’ result = 1; if c == ‘i’ result = 1; if c == ‘o’ result = 1; if c == ‘u’ result = 1; return result; Comp Sci 251 -- functions

  33. Example: vowel count- 5 • Integrate all together in vowel.a Comp Sci 251 -- functions

  34. Local variables • Global variables (static allocation) • Accessible throughout entire program execution • Exist in data segment • Local variables (dynamic allocation) • Created upon function call • Deleted upon function return • Where? How to access them? Comp Sci 251 -- functions

  35. Local variables • Implement locals on the stack • Reserve space in prologue • Release it in epilogue Local Variables $sp Saved registers Comp Sci 251 -- functions

  36. int sum(){ int x; int y; x = read int; y = read int; return x + y; } Stack: Example: Translate to MIPS y x Saved registers $sp Comp Sci 251 -- functions

  37. Data on the stack associated w/ function call Saved registers Local variables Use register to point to fixed point in the stack frame $sp may change during function call Use $fp (frame pointer) to access locals $fp is callee-save (like $ra and s-registers) Stack frame $sp } $fp Local Variables Stack frame Saved registers Comp Sci 251 -- functions

  38. Re-work example w/ $fp # prologue subu $sp, $sp, 12 #create frame sw $fp, 8($sp) #save old $fp addu $fp, $sp, 8 #set up $fp # epilogue lw $fp, 0($fp) # restore $fp addu $sp, $sp, 12 # remove frame jr $ra • Exercise: re-work function body w/ $fp y x $sp old $fp $fp Comp Sci 251 -- functions

  39. Functions with parameters • Parameters are special local variables • Initial values come from arguments • More MIPS register conventions Arguments: $a0 -- $a3 Comp Sci 251 -- functions

  40. int power(int base, int exp){ int result = 1; int i; for(i = 0; i < exp; i++) result *= base; return result; } Sketch stack frame Write prologue & epilogue Write function body Example function w/ parameters i result exp base old $fp $fp Comp Sci 251 -- functions

  41. #prologue subu $sp, $sp, 20 sw $fp, 16($sp) addu $fp, $sp, 16 sw $a0, -4($fp) # base sw $a1, -8($fp) # exp #epilogue lw $fp, 0($fp) addu $sp, $sp, 20 jr $ra Example function w/ parameters $sp i result exp base old $fp $fp Prev frame Old $sp Comp Sci 251 -- functions

  42. int power(int base, int exp){ int result; if(exp == 0) result = 1; else result = base * power(base, exp – 1); return result; } Sketch stack frame Write prologue & epilogue Write function body Non-leaf function with parameters result exp base old $fp $ra $fp Comp Sci 251 -- functions

  43. Wait a minute! • What if your function has more than 4 parameters? Comp Sci 251 -- functions

  44. Call by value vs. call by reference • C++ has reference parameters • Java passes all objects by reference • Assembly language implementation? • Pass the address of the argument Comp Sci 251 -- functions

  45. Pass By Value // This program uses variables as function parameters. #include <iostream> using namespace std; // Function prototypes. The function uses pass by value void doubleNum(int ); Comp Sci 251 -- functions

  46. Pass By Value int main() { int value; // Get a number and store it in value. cout << "Enter a number: "; cin >> value; cout << "That value entered is " << value << endl; // Double the number stored in value. doubleNum(value); cout << "That value doubled is " << value << endl; return 0; } Comp Sci 251 -- functions

  47. Pass By Value //********************************************************** // Definition of doubleNum. // The parameter valueVar is a value variable. The value // in valueVar is doubled. //********************************************************** void doubleNum (int valueVar) { valueVar *= 2; // display valueVar in doubleNum cout << "In doubleNum, valueVar is " << valueVar << endl; } Comp Sci 251 -- functions

  48. Pass By Reference // This program uses reference variables as function // parameters. #include <iostream> using namespace std; // Function prototypes. Both functions use reference // variables // as parameters. void doubleNum( int & ); void getNum( int & ); Comp Sci 251 -- functions

  49. Pass By Reference int main() { int value; // Get a number and store it in value. getNum(value); // Display the resulting number. cout << "That value entered is " << value << endl; // Double the number stored in value. doubleNum(value); // Display the resulting number. cout << "That value doubled is " << value << endl; return 0; } Comp Sci 251 -- functions

  50. Pass By Reference // The parameter userNum is a reference variable. The user is // asked to enter a number, which is stored in userNum. void getNum(int &userNum) { cout << "Enter a number: "; cin >> userNum; } // The parameter refVar is a reference variable. The value // in refVar is doubled. void doubleNum (int &refVar) { refVar *= 2; } Comp Sci 251 -- functions

More Related