ch. 8 functions. comp sci 251 -- functions 2 functions high-level languages have functions (methods)...

54
Ch. 8 Functions

Upload: kira-fadley

Post on 14-Dec-2015

228 views

Category:

Documents


4 download

TRANSCRIPT

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

Ch. 8 Functions

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

Comp Sci 251 -- functions2

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

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

Comp Sci 251 -- functions3

High-level function example

void helloWorld(){

print("Hello, world");

}

void main(){

helloWorld();

. . .

}

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

Comp Sci 251 -- functions4

Mechanism for implementing functions

Steps in the invocation and execution of a function:

save return address call the function execute the function return

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

Comp Sci 251 -- functions5

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

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

Comp Sci 251 -- functions6

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

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

Comp Sci 251 -- functions7

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"

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

Comp Sci 251 -- functions8

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

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

Comp Sci 251 -- functions9

Assembly language functions

Return from functionJump Register instruction:

jr Rsrc

Jump to the address in the register

jr $ra jump to return address

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

Comp Sci 251 -- functions10

Code Review

See helloFunc.a in /shared/huen/251

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

Comp Sci 251 -- functions11

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

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

Comp Sci 251 -- functions12

Program memory model

Memory contains three important segments

Text segment: program instructions

Data segment: global variables & constants

Stack segment: arguments & local variables

0x00000000 Reserved

0x00400000 Text segment

0x10000000 Data segment

0x7FFFEFFC Stack segment

0x80000000

0xFFFFFFFFOperating

system

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

Comp Sci 251 -- functions13

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

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

Comp Sci 251 -- functions14

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

$spword

Low

High

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

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 -- functions15

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

Comp Sci 251 -- functions16

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

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

Comp Sci 251 -- functions17

.text .globl __start __start: # execution starts here

la $t0, test # This code sets up the stacklw $t1, num # Do not alter

loop: lw $t2, ($t0)subu $sp, $sp, 4 # push stack w/ integerssw $t2, ($sp) # from test arrayadd $t0, $t0, 4add $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.

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

Comp Sci 251 -- functions18

# 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, 4bgez $t2, done # encounter non-negativeaddi $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:

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

Comp Sci 251 -- functions19

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.

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

Comp Sci 251 -- functions20

Use of system stack

Stores temporary information Key support for functions

Pending function calls Saved register values Parameters Local variables

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

Comp Sci 251 -- functions21

Functions that call functions

f:jal g #call gjr $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?

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

Comp Sci 251 -- functions22

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

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

Comp Sci 251 -- functions23

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)

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

Comp Sci 251 -- functions24

MIPS function structure

Prologue: push items on stack

Body: do required computation

Epilogue: pop items off stack & return

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

Comp Sci 251 -- functions25

What items must be stacked?

$ra (if function is non-leaf)

Some registers…

But not others…

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

Comp Sci 251 -- functions26

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

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

Comp Sci 251 -- functions27

Return value

Some functions return a value

MIPS register convention:

use $v0

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

Comp Sci 251 -- functions28

Functions with parameters

Parameters are special local variables Initial values come from arguments

More MIPS register conventions

Arguments: $a0 -- $a3

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

Comp Sci 251 -- functions29

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

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

Comp Sci 251 -- functions30

Example: vowel count -2

Main program– a0 points to str– Calls vcount passing a0 – Print answer– Terminate the program

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

Comp Sci 251 -- functions31

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 codecount = 0;set s1 to point to first character in str and call the character cwhile (c != 0) {

count += vowelp( c ); // call another function vowelpmove s1 to point to next character and call it c

}Done: return count;

Long time ago in a galaxy far aways1

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

Comp Sci 251 -- functions32

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;

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

Comp Sci 251 -- functions33

Example: vowel count- 5

Integrate all together in vowel.a

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

Comp Sci 251 -- functions34

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?

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

Comp Sci 251 -- functions35

Local variables

Implement locals on the stack– Reserve space in prologue– Release it in epilogue

Savedregisters

LocalVariables

$sp

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

Comp Sci 251 -- functions36

Example: Translate to MIPS

int sum(){int x;int y;

x = read int;y = read int;return x + y;

}

Stack:

Savedregisters

y

$sp

x

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

Comp Sci 251 -- functions37

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)

Savedregisters

LocalVariables

$sp

$fp

}Stack frame

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

Comp Sci 251 -- functions38

Re-work example w/ $fp

# prologuesubu $sp, $sp, 12 #create framesw $fp, 8($sp) #save old $fpaddu $fp, $sp, 8 #set up $fp

# epiloguelw $fp, 0($fp) # restore $fpaddu $sp, $sp, 12 # remove framejr $ra

Exercise: re-work function body w/ $fpold $fp

$fp

$spx

y

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

Comp Sci 251 -- functions39

Functions with parameters

Parameters are special local variables Initial values come from arguments

More MIPS register conventions

Arguments: $a0 -- $a3

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

Comp Sci 251 -- functions40

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

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

Comp Sci 251 -- functions41

Example function w/ parameters

#prologuesubu $sp, $sp, 20sw $fp, 16($sp)addu $fp, $sp, 16sw $a0, -4($fp) # basesw $a1, -8($fp) # exp

#epiloguelw $fp, 0($fp)addu $sp, $sp, 20jr $ra

old $fp$fp

base

exp

result

i

Prev frameOld $sp

$sp

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

Comp Sci 251 -- functions42

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

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

Wait a minute!

What if your function has more than 4 parameters?

Comp Sci 251 -- functions43

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

Comp Sci 251 -- functions44

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

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

Comp Sci 251 -- functions45

// This program uses variables as function parameters.#include <iostream>using namespace std;

// Function prototypes. The function uses pass by valuevoid doubleNum(int );

Pass By Value

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

Comp Sci 251 -- functions46

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;}

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

Comp Sci 251 -- functions47

//**********************************************************// 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

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

Comp Sci 251 -- functions48

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 & );

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

Comp Sci 251 -- functions49

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;}

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

Comp Sci 251 -- functions50

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;}

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

Comp Sci 251 -- functions51

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, 1sw $t1, ($t0)#epilogue...

__start: la $a0, foo jal increment .datafoo: .word 5

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

Comp Sci 251 -- functions52

Example

Value_ref.a

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

Comp Sci 251 -- functions53

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

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

Comp Sci 251 -- functions54

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);

.textsum: # fill in code

jr $ra

__start: la $a0, bar li $a1, 1000 jal sum

.databar: .space 4000