Presentation is loading. Please wait.

Presentation is loading. Please wait.

Ch. 8 Functions. Comp Sci 251 -- functions 2 Functions High-level languages have functions (methods) – For modularity – easier to change – To eliminate.

Similar presentations


Presentation on theme: "Ch. 8 Functions. Comp Sci 251 -- functions 2 Functions High-level languages have functions (methods) – For modularity – easier to change – To eliminate."— Presentation transcript:

1 Ch. 8 Functions

2 Comp Sci 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

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

4 Comp Sci 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

5 Comp Sci 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

6 Comp Sci 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

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

8 Comp Sci 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

9 Comp Sci 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

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

11 Comp Sci 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

12 Comp Sci functions 12 Program memory model Memory contains three important segments Text segment: program instructions Data segment: global variables & constants Stack segment: arguments & local variables 0x Reserved 0x Text segment 0x Data segment 0x7FFFEFFC Stack segment 0x xFFFFFFFF Operating system

13 Comp Sci 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

14 Comp Sci functions 14 Stack operations 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 $sp word Low High

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 functions 15

16 Comp Sci 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

17 Comp Sci 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.

18 Comp Sci 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++ jnext # At this point, the stack looks somewhat like # the following but in hexadecimal of course: # | -9| # | -4| # | -3| # |0xfffabfff| # |0xffffffd5| # $sp ->| 2| # | etc. | # done:

19 Comp Sci 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.

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

21 Comp Sci functions 21 Functions that call functions 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?

22 Comp Sci functions 22 Functions that call functions 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

23 Comp Sci 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)

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

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

26 Comp Sci 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

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

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

29 Comp Sci 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

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

31 Comp Sci 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

32 Comp Sci 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;

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

34 Comp Sci 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?

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

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

37 Comp Sci functions 37 Stack frame 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) Saved registers Local Variables $sp $fp } Stack frame

38 Comp Sci 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 old $fp $fp $sp x y

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

40 Comp Sci functions 40 Example function w/ parameters 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 old $fp $fp base exp result i

41 Comp Sci functions 41 Example function w/ parameters #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 old $fp $fp base exp result i Prev frame Old $sp $sp

42 Comp Sci functions 42 Non-leaf function with parameters 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 old $fp $fp base exp result $ra

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

44 Comp Sci 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

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

46 Comp Sci 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; }

47 Comp Sci functions 47 //********************************************************** // 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; } Pass By Value

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

49 Comp Sci 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; }

50 Comp Sci 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; }

51 Comp Sci functions 51 Example // x is passed by ref. void increment(int &x){ x++; } int foo = 5; increment(foo); // foo contains 6 increment: #prologue... lw $t0, -4($fp) lw $t1, ($t0) addi $t1, $t1, 1 sw $t1, ($t0) #epilogue... __start: la $a0, foo jal increment.data foo:.word 5

52 Comp Sci functions 52 Example Value_ref.a

53 Comp Sci functions 53 Arrays are passed by reference void f(int[] a){...} int bar[1000]; f(bar);.text f:... jr $ra __start: la $a0, bar jal f.data bar:.space 4000

54 Comp Sci functions 54 Exercise: function to sum an array int sum(int[] a, int size){ int result = 0; int i; for(i=0; i< size; i++) result += a[i]; return result } int bar[1000]; cout << sum(bar, 1000);.text sum: # fill in code jr $ra __start: la $a0, bar li $a1, 1000 jal sum.data bar:.space 4000


Download ppt "Ch. 8 Functions. Comp Sci 251 -- functions 2 Functions High-level languages have functions (methods) – For modularity – easier to change – To eliminate."

Similar presentations


Ads by Google