Problem Solving in C. Stepwise Refinement. ...but can stop refining at a higher level of abstraction. Same basic constructs. as covered in Chapter 6

Similar documents
Chapter 14 Functions

Scope: Global and Local. Concept of Scope of Variable

Chapter 14 Functions. Function. Example of High-Level Structure. Functions in C

Introduction to C Part 1 HLL s and the Basic Syntax. (Ch11 & 12)

COSC121: Computer Systems: Runtime Stack

Midterm 2 Review Chapters 4-16 LC-3

Chapter 11 Introduction to Programming in C

Chapter 11 Introduction to Programming in C

Chapter 11 Introduction to Programming in C

Functions in C. Memory Allocation in C. C to LC3 Code generation. Next.. Complete and submit C to LC3 code generation. How to handle function calls?

Chapter 11 Introduction to Programming in C

Chapter 11 Introduction to Programming in C

Chapter 11 Introduction to Programming in C

Chapter 11 Introduction to Programming in C

Lecture 5: C programming

Chapter 13 Control Structures

Chapter 13 Control Structures

Smaller, simpler, subcomponent of program Provides abstraction

2/6/2018. Let s Act Like Compilers! ECE 220: Computer Systems & Programming. Decompose Finding Absolute Value

Chapter 13. Control Structures

Implementing Functions at the Machine Level

Chapter 12 Variables and Operators

Introduction to Computer Engineering. CS/ECE 252, Fall 2016 Prof. Guri Sohi Computer Sciences Department University of Wisconsin Madison

ECE 190 Midterm Exam 3 Spring 2011

Chapter 9 TRAP Routines and Subroutines

TRAPs and Subroutines. University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell

Chapter 9 TRAP Routines and Subroutines

컴퓨터개념및실습. 기말고사 review

CSC 8400: Computer Systems. Using the Stack for Function Calls

CSC 2400: Computer Systems. Using the Stack for Function Calls

Chapter 12 Variables and Operators

Chapter 17 Recursion

CSC 2400: Computer Systems. Using the Stack for Function Calls

System Calls. Chapter 9 TRAP Routines and Subroutines

Chapter 6 Programming the LC-3

CSC 2400: Computing Systems. X86 Assembly: Function Calls"

CS 135: Computer Architecture I

CSC 2400: Computing Systems. X86 Assembly: Function Calls

University of Illinois at Urbana-Champaign First Midterm Exam, ECE 220 Honors Section

Functions in C. Lecture Topics. Lecture materials. Homework. Machine problem. Announcements. ECE 190 Lecture 16 March 9, 2011

Scope, Functions, and Storage Management

LC-3 Instruction Set Architecture

Chapter 17 Recursion

CS558 Programming Languages

Chapter 9 TRAP Routines and Subroutines

Wednesday, October 15, 14. Functions

LC-3 Instruction Set Architecture. Textbook Chapter 5

ECE220: Computer Systems and Programming Spring 2018 Honors Section due: Saturday 14 April at 11:59:59 p.m. Code Generation for an LC-3 Compiler

Chapter 12 Variables and Operators

Chapter 7 Assembly Language

Chapter 7 Assembly Language. ACKNOWLEDGEMENT: This lecture uses slides prepared by Gregory T. Byrd, North Carolina State University

Chapter 16 Pointers and Arrays

Assembly Language. University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell

Copyright The McGraw-Hill Companies, Inc. Persion required for reproduction or display. What is Recursion?

CS240: Programming in C

Introduction to C/C++ Programming

CS558 Programming Languages Winter 2018 Lecture 4a. Andrew Tolmach Portland State University

Stacks and Function Calls

Subroutines & Traps. Announcements. New due date for assignment 2 5pm Wednesday, 5May

1/30/2018. Conventions Provide Implicit Information. ECE 220: Computer Systems & Programming. Arithmetic with Trees is Unambiguous

Parsing Scheme (+ (* 2 3) 1) * 1

Chapter 10 And, Finally... The Stack. ACKNOWLEDGEMENT: This lecture uses slides prepared by Gregory T. Byrd, North Carolina State University

Function Calls COS 217. Reading: Chapter 4 of Programming From the Ground Up (available online from the course Web site)

Introduction to Computer Engineering. CS/ECE 252, Spring 2017 Rahul Nayar Computer Sciences Department University of Wisconsin Madison

What is Recursion? Chapter 17 Recursion. Executing RunningSum. High-Level Example: Binary Search

Stack Frames. September 2, Indiana University. Geoffrey Brown, Bryce Himebaugh 2015 September 2, / 15

LC-3 Subroutines and Traps. (Textbook Chapter 9)"

Functions Introduction. c h a p r e r

EC 413 Computer Organization

appendix a The LC-3 ISA A.1 Overview

Chapter 16 Pointers and Arrays

Computer Systems Lecture 9

Xuan Guo. Lecture XIX: Subroutines (2) CSC 3210 Computer Organization and Programming Georgia State University. March 31, 2015.

Project 3 Due October 21, 2015, 11:59:59pm

Assembly Language: Function Calls

CIT Week13 Lecture

Computing Layers. Chapter 7 Assembly Language

That is, we branch to JUMP_HERE, do whatever we need to do, and then branch to JUMP_BACK, which is where we started.

11/10/2016. Review the Problem to Be Solved. ECE 120: Introduction to Computing. What Shall We Keep in the Registers? Where Are the Pieces in Memory?

Copyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Pointers and Arrays

Function Calls. 1 Administrivia. Tom Kelliher, CS 240. Feb. 13, Announcements. Collect homework. Assignment. Read

Run-Time Data Structures

CS 2461: Computer Architecture I

ECE495k Final Sample Soln.

CMPE-013/L. Introduction to C Programming

Functions. printf( %f cubed is %f,x,cube(x)); return 0; } return parameter type double cube(double var) { return (var*var*var);

Question 4.2 2: (Solution, p 5) Suppose that the HYMN CPU begins with the following in memory. addr data (translation) LOAD 11110

Instruction Set Architecture

Princeton University Computer Science 217: Introduction to Programming Systems. Assembly Language: Function Calls

Functions in C C Programming and Software Tools. N.C. State Department of Computer Science

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 12, FALL 2012

n Address of a variable in memory n Allows us to indirectly access variables ! Array n A list of values arranged sequentially in memory

! What do we care about? n Fast program execution. n Efficient memory usage. n Avoid memory fragmentation. n Maintain data locality

Copyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Review Topics

Function Calls. Tom Kelliher, CS 220. Oct. 24, SPIM programs due Wednesday. Refer to homework handout for what to turn in, and how.

M2 Instruction Set Architecture

COMP 202 Recursion. CONTENTS: Recursion. COMP Recursion 1

Chapter 10 Memory Model for Program Execution. Problem

CS356: Discussion #6 Assembly Procedures and Arrays. Marco Paolieri

CSCI565 Compiler Design

Transcription:

Problem Solving in C Stepwise Refinement as covered in Chapter 6...but can stop refining at a higher level of abstraction. Same basic constructs Sequential -- C statements Conditional -- if-else, switch Iterative -- while, for, do-while 11-1

Problem 1: Calculating Pi Calculate π using its series expansion. User inputs number of terms. π= 4 4 3 4 5 4 7 1 n 1 4 2n 1 Start Initialize Get Input Evaluate Series Output Results Stop 11-2

Pi: 1st refinement Start Initialize Get Input Initialize iteration count count<terms F for loop T Evaluate Series Evaluate next term Output Results count = count+1 Stop 11-3

Pi: 2nd refinement Initialize iteration count T count is odd F count<terms F T Evaluate next term count = count+1 subtract term add term add term if-else 11-4

But, (Chaiken says) it's better to decide exactly what the variables (like count and terms) will mean! count : variable that tracks which term we will calculate and add to the sum. The first term (4) will correspond to count==0. The second term (-4/3) will correspond to count==1, etc. So, yes, for even count (0, 2, 4) we add a positive term; for odd count (1, 3, 5) we subtract a positive term. terms: Number of terms to add up; input from user. So: if count < terms, we add another term; if count==terms we stop before adding another term. 11-5

Pi: Code for Evaluate Terms for (count=0; count < numofterms; count++) { if (count % 2) { /* odd term -- subtract */ pi -= 4.0 / (2 * count + 1); } else { /* even term -- add */ pi += 4.0 / (2 * count + 1); } Note: Code in text is slightly different, but this code corresponds to equation. 11-6

Pi: Complete Code #include <stdio.h> main() { double pi = 0.0; int numofterms, count; printf("number of terms (must be 1 or larger) : "); scanf("%d", &numofterms); } for (count=0; count < numofterms; count++) { if (count % 2) { pi -= 4.0 / (2 * count + 1); /* odd term -- subtract */ } else { pi += 4.0 / (2 * count + 1); /* even term -- add */ } printf("the approximate value of pi is %f\n", pi); 11-7

C: A High-Level Language Gives symbolic names to values don t need to know which register or memory location Provides abstraction of underlying hardware operations do not depend on instruction set example: can write a = b * c, even though LC-3 doesn t have a multiply instruction Provides expressiveness use meaningful symbols that convey meaning simple expressions for common control patterns (if-then-else) Enhances code readability Safeguards against bugs can enforce rules or conditions at compile-time or run-time 11-8

Compiling a C Program Entire mechanism is usually called the compiler Preprocessor macro substitution conditional compilation source-level transformations output is still C Compiler generates object file machine instructions Linker combine object files (including libraries) into executable image Library Object Files Source Code Analysis Target Code Synthesis C Source and Header Files C Preprocessor Compiler Linker Executable Image Symbol Table 11-9

Compiler Source Code Analysis front end parses programs to identify its pieces variables, expressions, statements, functions, etc. depends on language (not on target machine) Code Generation back end generates machine code from analyzed source may optimize machine code to make it run more efficiently very dependent on target machine Symbol Table map between symbolic names and items like assembler, but more kinds of information 11-10

Functions in C Declaration (also called prototype) int Factorial(int n); type of return value name of function types of all arguments Function call -- used in expression a = x + Factorial(f + g); 1. evaluate arguments 2, execute function 3. use return value in expression 11-11

Function Definition State type, name, types of arguments must match function declaration give name to each argument (doesn't have to match declaration) int Factorial(int n) { int i; int result = 1; } for (i = 1; i <= n; i++) result *= i; return result; gives control back to calling function and returns value 11-12

Why Declaration? Since function definition also includes return and argument types, why is declaration needed? Use might be seen before definition. Compiler needs to know return and arg types and number of arguments. Definition might be in a different file, written by a different programmer. include a "header" file with function declarations only compile separately, link together to make executable 11-13

Example double ValueInDollars(double amount, double rate); main() {... dollars = ValueInDollars(francs, DOLLARS_PER_FRANC); printf("%f francs equals %f dollars.\n", francs, dollars);... } declaration function call (invocation) definition double ValueInDollars(double amount, double rate) { return amount * rate; } 11-14

Implementing Functions: Overview Activation record information about each function, including arguments and local variables stored on run-time stack Calling function push new activation record copy values into arguments call function get result from stack Called function execute code put result in activation record pop activation record from stack return 11-15

Run-Time Stack Recall that local variables are stored on the run-time stack in an activation record Frame pointer (R5) points to the beginning of a region of activation record that stores local variables for the current function When a new function is called, its activation record is pushed on the stack; when it returns, its activation record is popped off of the stack. 11-16

Run-Time Stack Memory Memory Memory Watt R6 R5 main R6 R5 main main R6 R5 Before call During call After call 11-17

Activation Record int NoName(int a, int b) { int w, x, y;.. }. return y; Name Type Offset Scope R5 bookkeeping y x w dynamic link return address return value a b locals args a b w x y int int int int int 4 5 0-1 -2 NoName NoName NoName NoName NoName 11-18

Arg VALUES are COPIED to Fun PARAMETERS main() { printf( x%x, Factorial(3)); }.ORIG x3000 Brnzp main Three.FILL #3 main LD R0, Three ;R0: LC3 Fun Arg Reg JSR Factorial JSR PrintHex HALT 11-19

Arg VALUES are COPIED to Fun PARAMETERS int Factorial(int n) { if( n == 0 ) return 1; else return( Factorial( n 1 )*n ); } HALT Factorial ADD R6,R6,#-2 ;Make stack frame STR R7,R6,#0 ;0(R6) saves R7 STR R0,R6,#1 ; Mem[R6+1] IS the Fun PARAMETER Variable! BRnp FactRec ;smart! AND R0,R0,#0 ADD R0,R0,#1 Brnzp FactRet 11-20

Arg VALUES are COPIED to Fun PARAMETERS int Factorial(int n) {... return( Factorial( n 1 )*n );} }; Mem[R6+1] IS the Fun PARAMETER Variable! BRnp FactRec ;smart!...... Brnzp FactRet FactRec ADD R0,R0,#-1 ;calc n-1, smart! JSR Factorial ;ARG is n-1. ; now, R0 holds (n-1)! (FACT!) LDR R1,R6,#1 ;copy n into R1 JSR Multiply ;please write for LC3 FactRet LDR R7,R6,#0 ; and forget abt n. ADD R6,R6,#2 ; pop stack RET 11-21

Arg VALUES are COPIED to Fun PARAMETERS main() { char PATTERN[31], SUBJECT[31]; Brnzp Main PATTERN.BLKW #31 SUBJECT.BLKW #31 PATA.FILL PATTERN SUBA.FILL SUBJECT /* Inputting is OMITTED */ if(fun( PATTERN, SUBJECT )) printf( Yes ); Main LD R0,PATA LD R1,SUBA JSR FUN Brz NoMatch 11-22

Arg VALUES are COPIED to Fun PARAMETERS int FUN(char *pat, char *sub) { if( *pat == '\0' && *sub == '\0' )... FUN ADD R6,R6,#-3 ;alloc. stack frame STR R7,R6,#0 ;save ret. address STR R0,R6,#1 ;1(R6) used for pat PARA STR R1,R6,#2 ;2(R6) used for sub PARA LDR R0,R6,#1 ;Load pat value:a POINTER LDR R0,R0,#0 ;Load value IT POINTS TO BRnp IfIsFalse ;C doesn't bother LDR R0,R6,#2 ;Load sub (pointer!) LDR R0,R0,#0 ;Load (char) it points to BRnp IfIsFalse ;Generate a 1 in R0 BRnzp FunEpilogue 11-23

Function Definition State type, name, types of arguments must match function declaration give name to each argument (doesn't have to match declaration) int Factorial(int n) { int i; int result = 1; } for (i = 1; i <= n; i++) result *= i; return result; gives control back to calling function and returns value 11-24

Activation Record Bookkeeping Return value space for value returned by function allocated even if function does not return a value Return address save pointer to next instruction in calling function convenient location to store R7 in case another function (JSR) is called Dynamic link caller s frame pointer used to pop this activation record from stack 11-25

Example Function Call int Volta(int q, int r) { int k; int m;... return k; } int Watt(int a) { int w;... w = Volta(w,10);... return w; } 11-26

Calling the Function w = Volta(w, 10); ; push second arg AND R0, R0, #0 ADD R0, R0, #10 ADD R6, R6, #-1 STR R0, R6, #0 ; push first argument LDR R0, R5, #0 ADD R6, R6, #-1 STR R0, R6, #0 ; call subroutine JSR Volta new R6 R6 R5 xfd00 25 10 25 q r w dyn link ret addr ret val a Note: Caller needs to know number and type of arguments, doesn't know about local variables. 11-27

Starting the Callee Function ; leave space for return value ADD R6, R6, #-1 ; push return address ADD R6, R6, #-1 STR R7, R6, #0 ; push dyn link (caller s frame ptr) ADD R6, R6, #-1 STR R5, R6, #0 ; set new frame pointer ADD R5, R6, #-1 ; allocate space for locals ADD R6, R6, #-2 new R6 new R5 R6 R5 xfd00 xfcfb x3100 25 10 25 m k dyn link ret addr ret val q r w dyn link ret addr ret val a 11-28

Ending the Callee Function return k; ; copy k into return value LDR R0, R5, #0 STR R0, R5, #3 ; pop local variables ADD R6, R5, #1 ; pop dynamic link (into R5) LDR R5, R6, #0 ADD R6, R6, #1 ; pop return addr (into R7) LDR R7, R6, #0 ADD R6, R6, #1 ; return control to caller RET R6 R5 new R6 new R5 xfd00-43 217 xfcfb x3100 217 25 10 25 m k dyn link ret addr ret val q r w dyn link ret addr ret val a 11-29

Resuming the Caller Function w = Volta(w,10); JSR Volta R6 ; load return value (top of stack) LDR R0, R6, #0 new R6 ; perform assignment R5 STR R0, R5, #0 ; pop return value ADD R6, R6, #1 ; pop arguments ADD R6, R6, #2 xfd00 217 25 10 217 ret val q r w dyn link ret addr ret val a 11-30

Summary of LC-3 Function Call Implementation 1. Caller pushes arguments (last to first). 2. Caller invokes subroutine (JSR). 3. Callee allocates return value, pushes R7 and R5. 4. Callee allocates space for local variables. 5. Callee executes function code. 6. Callee stores result into return value slot. 7. Callee pops local vars, pops R5, pops R7. 8. Callee returns (JMP R7). 9. Caller loads return value and pops arguments. 10. Caller resumes computation 11-31

A Simple C Program #include <stdio.h> #define STOP 0 /* Function: main */ /* Description: counts down from user input to STOP */ main() { /* variable declarations */ int counter; /* an integer to hold count values */ int startpoint; /* starting point for countdown */ /* prompt user for input */ printf("enter a positive number: "); scanf("%d", &startpoint); /* read into startpoint */ /* count down and print count */ for (counter=startpoint; counter >= STOP; counter--) printf("%d\n", counter); } 11-32

Compiling and Linking Various compilers available cc, gcc includes preprocessor, compiler, and linker Lots and lots of options! level of optimization, debugging preprocessor, linker options intermediate files -- object (.o), assembler (.s), preprocessor (.i), etc. 11-33

Symbol Table Like assembler, compiler needs to know information associated with identifiers in assembler, all identifiers were labels and information is address Compiler keeps more information Name (identifier) Type Location in memory Scope Name Type Offset Scope amount hours minutes rate seconds time int int int int int int 0-3 -4-1 -5-2 main main main main main main 11-34

Symbol Table Like assembler, compiler needs to know information associated with identifiers in assembler, all identifiers were labels and information is address In C: LOCAL lifetime versus GLOBAL (static) lifetime. LOCAL lifetime variables live in the activation records which live int the STACK. Symbol table tracks their OFFSET from frame pointer, so offset from the stack pointer can be known. { int A; char *B;... ADD R6,R6,#-[the appropriate number] GLOBAL (static) lifetime variables live in non-stack memory forever Symbol table tracks their absolute memory address In C, declare OUTSIDE a fun. body to make a global livetimer. int DEBUG = 0; DEBUG.FILL #0 int InitMeLater; InitMeLater.BLKW #1 11-35

Example: Code Generation ; main ; initialize variables AND R0, R0, #0 ADD R0, R0, #5 ; inlocal = 5 STR R0, R5, #0 ; (offset = 0) AND R0, R0, #0 ADD R0, R0, #3 ; inglobal = 3 STR R0, R4, #0 ; (offset = 0) 11-36

Example (continued) ; first statement: ; outlocala = inlocal++ & ~inglobal; LDR R0, R5, #0 ; get inlocal ADD R1, R0, #1 ; increment STR R1, R5, #0 ; store LDR R1, R4, #0 ; get inglobal NOT R1, R1 ; ~inglobal AND R2, R0, R1 ; inlocal & ~inglobal STR R2, R5, #-1 ; store in outlocala ; (offset = -1) 11-37

Example (continued) ; next statement: ; outlocalb = (inlocal + inglobal) ; - (inlocal - inglobal); LDR R0, R5, #0 ; inlocal LDR R1, R4, #0 ; inglobal ADD R0, R0, R1 ; R0 is sum LDR R2, R5, #0 ; inlocal LDR R3, R5, #0 ; inglobal NOT R3, R3 ADD R3, R3, #1 ADD R2, R2, R3 ; R2 is difference NOT R2, R2 ; negate ADD R2, R2, #1 ADD R0, R0, R2 ; R0 = R0 - R2 STR R0, R5, #-2 ; outlocalb (offset = -2) 11-38