Stack. Stack. Function Calls and Stack Allocation. Stack Popping Popping. Stack Pushing Pushing. Page 1

Similar documents
Function Calls and Stack Allocation

Function Calls and Stack Allocation

Systems I. Machine-Level Programming V: Procedures

CS558 Programming Languages

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

Stacks and Function Calls

(Extract from the slides by Terrance E. Boult

IA32 Stack. Lecture 5 Machine-Level Programming III: Procedures. IA32 Stack Popping. IA32 Stack Pushing. Topics. Pushing. Popping

IA32 Stack The course that gives CMU its Zip! Machine-Level Programming III: Procedures Sept. 17, IA32 Stack Popping. IA32 Stack Pushing

Giving credit where credit is due

Short Notes of CS201

Assembly III: Procedures. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

CS201 - Introduction to Programming Glossary By

Implementing Procedure Calls

MIPS Functions and the Runtime Stack

ASSEMBLY III: PROCEDURES. Jo, Heeseung

Assembly III: Procedures. Jo, Heeseung

Run-time Environments - 2

Implementing Subroutines. Outline [1]

Run Time Environment

CS213. Machine-Level Programming III: Procedures

Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst

Programming Studio #9 ECE 190

Topic 7: Activation Records

Programs in memory. The layout of memory is roughly:

Q1: /8 Q2: /30 Q3: /30 Q4: /32. Total: /100

Run-time Environment

Do-While Example. In C++ In assembly language. do { z--; while (a == b); z = b; loop: addi $s2, $s2, -1 beq $s0, $s1, loop or $s2, $s1, $zero

Data Transfer Instructions

Computer Programming

The course that gives CMU its Zip! Machine-Level Programming III: Procedures Sept. 17, 2002

Fundamentals of Programming

QUIZ. What are 3 differences between C and C++ const variables?

Course Administration

Scope: Global and Local. Concept of Scope of Variable

CSE Lecture In Class Example Handout

Informatica e Sistemi in Tempo Reale

Q1: /20 Q2: /30 Q3: /24 Q4: /26. Total: /100

University of Washington

X86 Assembly -Procedure II:1

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

Lectures 5-6: Introduction to C

In Java we have the keyword null, which is the value of an uninitialized reference type

Memory Usage 0x7fffffff. stack. dynamic data. static data 0x Code Reserved 0x x A software convention

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

Procedure Calls Main Procedure. MIPS Calling Convention. MIPS-specific info. Procedure Calls. MIPS-specific info who cares? Chapter 2.7 Appendix A.

Cpt S 122 Data Structures. Data Structures

Separate compilation. Topic 6: Runtime Environments p.1/21. CS 526 Topic 6: Runtime Environments The linkage convention

Today's Topics. CISC 458 Winter J.R. Cordy

Page 1. IA32 Stack CISC 360. Machine-Level Programming III: Procedures Sept. 22, IA32 Stack Popping Stack Bottom. IA32 Stack Pushing

CPSC 213. Introduction to Computer Systems. Procedures and the Stack. Unit 1e Feb 11, 13, 15, and 25. Winter Session 2018, Term 2

System Software Assignment 1 Runtime Support for Procedures

A Simplistic Program Translation Scheme

MPATE-GE 2618: C Programming for Music Technology. Unit 4.1

Stacks and Frames Demystified. CSCI 3753 Operating Systems Spring 2005 Prof. Rick Han

Lecture 7: Procedures and Program Execution Preview

Lectures 5. Announcements: Today: Oops in Strings/pointers (example from last time) Functions in MIPS

CIT Week13 Lecture

Project Compiler. CS031 TA Help Session November 28, 2011

Generating Programs and Linking. Professor Rick Han Department of Computer Science University of Colorado at Boulder

Functions in MIPS. Functions in MIPS 1

Calling Conventions. Hakim Weatherspoon CS 3410, Spring 2012 Computer Science Cornell University. See P&H 2.8 and 2.12

Implementing Subprograms

CPS311 Lecture: Procedures Last revised 9/9/13. Objectives:

ECE232: Hardware Organization and Design

Mechanisms in Procedures. CS429: Computer Organization and Architecture. x86-64 Stack. x86-64 Stack Pushing

Understand Execution of a Program

o Code, executable, and process o Main memory vs. virtual memory

Machine-level Programming (3)

An Experience Like No Other. Stack Discipline Aug. 30, 2006

Programming in C. main. Level 2. Level 2 Level 2. Level 3 Level 3

Assembly Programming (III)

Stack Discipline Jan. 19, 2018

Arguments and Return Values. EE 109 Unit 16 Stack Frames. Assembly & HLL s. Arguments and Return Values

Code Generation. Lecture 12

Compilers and computer architecture: A realistic compiler to MIPS

Interview Questions of C++

QUIZ. Source:

Region of memory managed with stack discipline Grows toward lower addresses. Register %esp contains lowest stack address = address of top element

Machine Programming 3: Procedures

The Procedure Abstraction Part I: Basics

Object Reference and Memory Allocation. Questions:

Scope, Functions, and Storage Management

Midterm Review. PIC 10B Spring 2018

MIPS R-format Instructions. Representing Instructions. Hexadecimal. R-format Example. MIPS I-format Example. MIPS I-format Instructions

Chapter 9 :: Subroutines and Control Abstraction

Assembly III: Procedures. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

COMP3221: Microprocessors and. and Embedded Systems. Overview. Variable Types and Memory Sections. Types of Variables in C

COMP 303 Computer Architecture Lecture 3. Comp 303 Computer Architecture

CSE2421 Systems1 Introduction to Low-Level Programming and Computer Organization

Sungkyunkwan University

ECE331: Hardware Organization and Design

CSC 1600 Memory Layout for Unix Processes"

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

6.096 Introduction to C++ January (IAP) 2009

CS201 Some Important Definitions

Computer Systems C S Cynthia Lee

Run-time Environments

Run-Time Environments

Run-time Environments

Transcription:

Function Calls and Allocation Region of memory managed with stack discipline Grows toward lower addresses pointer indicates lowest stack address Bottom Increasing Addresses Topics Pushing and Popping Role of in (Automatic) Allocation Parameter Passing Top Grows Down Pushing Pushing Bottom Popping Popping Bottom Add something at the top of the stack Increasing Addresses Throw away element at the top of the stack Increasing Addresses Grows Down Grows Down Top Top Page 1

Procedure Control Flow Use stack to support procedure call and return Allocated in Frames state for single procedure instantiation Local variables Arguments Other (e.g., for return) all state goes away when procedure returns Example Code Structure ( ) (); ( ) (); (); Procedure recursive (calls itself) ( ) (); Frames Contents Local variables Return information Temporary ace Management Space allocated when enter procedure Deallocated (freed) when return Operation ( ) (); proc Top Page 2

Operation ( ) (); (); Operation ( ) (); Operation ( ) (); Operation ( ) (); Page 3

Operation ( ) (); Operation ( ) (); Operation ( ) (); (); Operation ( ) Page 4

Operation ( ) (); (); Operation ( ) (); Function Parameters Example 1: swap_1 Function arguments are passed by value. What is pass by value? The called function is given a copy of the arguments. What does this imply? The called function can t alter a variable in the caller function, but its private copy. An example void swap_1(int a, int b) int temp; temp = a; a = b; b = temp; Q: Let x=3, y=4, after swap_1(x,y); x =? y=? A1: x=4; y=3; A2: x=3; y=4; Page 5

Process Memory Image Automatic variables are allocated memory on the stack. grows downwards Dynamic Memory Allocator requests memory from the heap. Heap grows upwards (automatic allocations) run-time heap (via new) Dynamic (Heap) Memory Allocator Recap Operator new is still a high-level request such as I d like an instance of class String Try to think about it low level You ask for n bytes (the sizeof that type/class) You get a pointer (memory address) to the allocated object This allocation is on the heap You need to free all memory blocks you allocated A delete for each correonding new data program code 0 Automatic Allocator Internals Automatic allocation of variables occurs on the stack We ll learn how automatic allocation works next Passing Arguments by Value Upon function call, the argument values are copied (byte-by by-byte) byte) onto stack Push args on stack for the function you are about to call Space for local variables is allocated on stack Local variables allocated automatically in new frame Disappear when frame pops off the stack Caller () Callee () Local Variables Copy Args for Local Variables Copy Args for Page 6

Pass Args by Value () int y1,y2; (y1,y2); Frame fp Pass Args by Value (Copy) () int y1,y2; (y1,y2); (int a, int b) int w1,w2; (); (); (int a, int b) int w1,w2; (a); (b); Pass Args by Value on Call (int a, int b) int w1,w2; (a); (b); (int i) (i); Pass Args by Value on Call (int i) (i); Page 7

Pass Args by Value on Call (int i) (i); Pop on Return (int i) (i); Pop on Return (int i) (i); Pop on Return (int a, int b) int w1,w2; (a); (b); Page 8

Pass Args by Value on Call (int a, int b) int w1,w2; (a); (b); (int i) (i); Pop on Return (int a, int b) int w1,w2; (a); (b); Pop on Return () int y1,y2; (y1,y2); Summary The Makes Function Calls Work Private storage for each instance of procedure call locals + arguments are allocated on stack Can be managed by stack discipline Procedures return in inverse order of calls That s how automatic allocation works Local vars allocated on new frame upon entering function call Vars (including arg copies) freed automatically upon return Do you see now why you cannot delete an automatically allocated object? Page 9

Summary (contd.) Do you see now why you cannot delete an automatically allocated object? (e.g. int i; int * pi = &i; delete pi is WRONG!) Because automatically allocated objects live temporarily on the stack. You cannot control lifetime. You can only free objects that you allocated with new (on the heap). The two allocators (dynamic & automatic) are different. Function Parameters Passing (contd) The only mechanism in C++ is to pass arguments by value (push/copy args on stack)!!! So how can we make swap work? A: The called function is passed a pointer (address) of a var. What does this imply? The called function can alter that variable var through its pointer This fakes a mechanism called pass args by reference present in other languages (e.g., Pascal). An example Example 2: swap_2 void swap_2(int *a, int *b) int temp; temp = *a; *a = *b; *b = temp; Q: Let x=3, y=4, after swap_2(&x,&y); x =? y=? A1: x=3; y=4; A2: x=4; y=3; Parameters Passing by Reference 1. The stack mechanism works unchanged 2. The pointer (arg( arg) ) is still copied (byte by byte) on stack as usual! 3. So the pointer itself is still passed by value 4. However, the callee can directly access that memory address thus can change the var through its pointer 5. If arg is large object (e.g., struct student_data) should pass its address (to avoid large copies) Page 10

A Simplistic Program Translation Scheme (seen up to now) Compilation and Linking Topics Separation of function code into.cc and.h Compiling Object files Linking different files m.cc Translator (compiler) p ASCII (text) source file g++ -o p m.cc Binary executable object file (memory image on disk) Problems: Efficiency: small change requires complete recompilation Modularity: hard to share common functions (e.g., cout, sort) Solution: Use separate files for different functionalities (code is modular ) Linker Example C Program A Better Scheme Using a Linker m.cc int e=7; sq.cc extern int e; m.cc sq.cc int main()... z = squared(y); cout << e; int squared(int y) return y*y; Translators m.o Translators sq.o Separately compiled object files return 0; Linker (ld) p Executable object file (contains code and data for all functions defined in m.cc and sq.cc) Page 11

Translating the Example Program g++ coordinates all steps in the translation and linking process. Invokes preprocessor, compiler, assembler (as), and linker (ld). Passes command line arguments to appropriate phases Example: create executable p from m.cc and sq.cc: Translating the Example Program g++ coordinates all steps in the translation and linking process. Invokes preprocessor, compiler, assembler (as), and linker (ld). Passes command line arguments to appropriate phases Example: create executable p from m.cc and sq.cc: g++ -c m.cc This creates m.o g++ -c sq.cc This creates sq.o g++ m.o sq.o o p Links m.o and sq.o g++ -c m.cc This creates m.o g++ -c sq.cc This creates sq.o g++ m.o sq.o o p Links m.o and sq.o Can do it like this too: g++ m.cc sq.cc o p But: If one file changes,all need to be recompiled,long compile time What Does a Linker Do? Merges object files Merges multiple (.o) object files into a single executable object file that can be loaded and executed. Resolves external references As part of the merging process, resolves external references. External reference: reference to a symbol defined in another object file. External references can be to either code or data» code: a(); /* reference to symbol a */» data: extern int x; /* reference to symbol x */ Why Linkers? Modularity Program can be written as a collection of smaller source files, rather than one monolithic mass. Can build libraries of common functions (more on this later) e.g., Math library, iostream library Efficiency Time: Change one source file, recompile that one!, and then relink. No need to recompile other source files» e.g., if Bahlul changes sort, then only his file will be recompiled to produce his.o, not our own Page 12

So what goes in.cc and in.h? int main() Listnode *head;... z = squared(y); head = free_list(head); return 0; main.cc squared.cc int squared(int y) return y*y; typedef struct list_node... Listnode; Example C++ Program int main() Listnode *head;//listnode??... z = squared(y); head = free_list(head); return 0; main.cc squared.cc int squared(int y) return y*y; typedef struct list_node... Listnode; //move to list.h list.cc Listnode *free_list(listnode *l)..//ex5 use no aux pointers //ex4&5 prize Visual C++ free list.cc Listnode *free_list(listnode *l).. //ex5 use no aux pointers Example Program #include squared.h int e=7; int main() Listnode *head;... z = squared(y); head = free_list(head); return 0; main.cc squared.h int squared(int y); squared.cc #include squared.h int squared(int y) return y*y; Example Program #include squared.h #include List.h int e=7; int main() Listnode *head;... z = squared(y); head = free_list(head); return 0; main.cc List.h typedef struct list_node... Listnode; Listnode *free_list(listnode *l); list.cc #include List.h Listnode *free_list(listnode *l).. //ex5 use no aux pointers Page 13

How It Works #include List.h #include squared.h int e=7; int main() Listnode *head;... z = squared(y); head = free_list(head); return 0; main.cc List.h typedef struct list_node... Listnode; Listnode *free_list(listnode *l); squared.h int squared(int y); Encapsulation Introduction Class implementation Interface User Preprocessor includes all text in List.h and squared.h in main.cc. We just separate declarations out for use by others and for the benefit of compiler/linker. Implementation details hidden from User Encapsulation Introduction Encapsulation Class1 implementation (by Bahlul) Class2 implementation (by Salam) Class implementation (e.g., Set.cc) Function call Interface User Interface int sort() Interface (Set.h) User Implementation details hidden from User Programmers collaborate (use each other s code thru func calls) Implementation details (in Set.cc) hidden from User Interface (in Set.h) is public - given to User Page 14

How to Encapsulate (first step)? Interface = ec (how to use) put in a header file We ll see more of this with classes (e.g., private/public) +/- of Encapsulation? + User code remains same if class implem changes - User code might run slower without apparent reason Class implementation Function bodies (.cc file) Interface (header file) User Class implementation (in Set.cc) #include Set.h int sort(..) //changed from //quick to bubble sort Interface in Set.h User code (inventory.cc) #include <iostream> #include Set.h int main () sort( ); Public function headers Public type definitions (e.g., class definition, struct definition, typedefs) Bottom Line: Code is read out over several.cc and.h files Changes to implementation are tranarent to user Only the file that changes needs to be recompiled Page 15