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

Similar documents
Chapter 10 Memory Model for Program Execution. Problem

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

Review Topics. Final Exam Review Slides

Implementing Functions at the Machine Level

Textbook chapter 10. Abstract data structures are. In this section, we will talk about. The array The stack Arithmetic using a stack

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

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

System Software Assignment 1 Runtime Support for Procedures

Storage in Programs. largest. address. address

Midterm 2 Review Chapters 4-16 LC-3

Systems I. Machine-Level Programming V: Procedures

Part 7. Stacks. Stack. Stack. Examples of Stacks. Stack Operation: Push. Piles of Data. The Stack

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

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

Chapter 10 And, Finally... The Stack

Subroutines. int main() { int i, j; i = 5; j = celtokel(i); i = j; return 0;}

Run-time Environments - 2

Scope: Global and Local. Concept of Scope of Variable

Review Topics. Midterm Exam Review Slides

Computer Architecture and System Software Lecture 07: Assembly Language Programming

Review Topics. Midterm Exam Review Slides

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

CA Compiler Construction

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

MIPS Procedure Calls. Lecture 6 CS301

Procedure Call. Procedure Call CS 217. Involves following actions

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

Branch Addressing. Jump Addressing. Target Addressing Example. The University of Adelaide, School of Computer Science 28 September 2015

Control Instructions. Computer Organization Architectures for Embedded Computing. Thursday, 26 September Summary

Control Instructions

ARM Assembly Programming

Wednesday, October 15, 14. Functions

Subprograms, Subroutines, and Functions

Lecture #16: Introduction to Runtime Organization. Last modified: Fri Mar 19 00:17: CS164: Lecture #16 1

COMP 303 Computer Architecture Lecture 3. Comp 303 Computer Architecture

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?

ARM Assembly Programming

EE 361 University of Hawaii Fall

Run-time Environments

Module 27 Switch-case statements and Run-time storage management

Run-time Environments

MIPS Functions and Instruction Formats

Course Administration

CIT Week13 Lecture

Plan. Regression testing: Demo of how to use the regress.sh script.

An Overview to Compiler Design. 2008/2/14 \course\cpeg421-08s\topic-1a.ppt 1

Chapter 14 Functions

Objectives. ICT106 Fundamentals of Computer Systems Topic 8. Procedures, Calling and Exit conventions, Run-time Stack Ref: Irvine, Ch 5 & 8

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

Chapter 2. Computer Abstractions and Technology. Lesson 4: MIPS (cont )

Run-time Environment

MIPS Functions and the Runtime Stack

Concepts Introduced in Chapter 7

CSE Lecture In Class Example Handout

MIPS Programming. A basic rule is: try to be mechanical (that is, don't be "tricky") when you translate high-level code into assembler code.

Computer Architecture and System Software Lecture 06: Assembly Language Programming

Topic 7: Activation Records

ARM Assembly Programming II

CprE 288 Introduction to Embedded Systems ARM Assembly Programming: Translating C Control Statements and Function Calls

Winter Compiler Construction T11 Activation records + Introduction to x86 assembly. Today. Tips for PA4. Today:

Review of Activation Frames. FP of caller Y X Return value A B C

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

Run-time Environments. Lecture 13. Prof. Alex Aiken Original Slides (Modified by Prof. Vijay Ganesh) Lecture 13

Virtual Machine Tutorial

appendix a The LC-3 ISA A.1 Overview

x86 assembly CS449 Fall 2017

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

System Calls. Chapter 9 TRAP Routines and Subroutines

6.001 Recitation 23: Register Machines and Stack Frames

SPIM Procedure Calls

ECE232: Hardware Organization and Design

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

Computing Layers. Chapter 5 The LC-3

Code Generation. The Main Idea of Today s Lecture. We can emit stack-machine-style code for expressions via recursion. Lecture Outline.

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

We can emit stack-machine-style code for expressions via recursion

G Programming Languages - Fall 2012

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

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

Stack -- Memory which holds register contents. Will keep the EIP of the next address after the call

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

Memory Management and Run-Time Systems

Procedures and Stacks

ECE251: Tuesday September 12

12/4/18. Outline. Implementing Subprograms. Semantics of a subroutine call. Storage of Information. Semantics of a subroutine return

Data Structure Layout. In HERA/Assembly

ASSEMBLY III: PROCEDURES. Jo, Heeseung

Assembly III: Procedures. Jo, Heeseung

Run-Time Data Structures

CS61C : Machine Structures

Binding and Storage. COMP 524: Programming Language Concepts Björn B. Brandenburg. The University of North Carolina at Chapel Hill

Functions and Procedures

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

CS 536 Introduction to Programming Languages and Compilers Charles N. Fischer Lecture 11

Compiling Code, Procedures and Stacks

Stack Discipline Jan. 19, 2018

CSC 2400: Computing Systems. X86 Assembly: Function Calls

CSIS1120A. 10. Instruction Set & Addressing Mode. CSIS1120A 10. Instruction Set & Addressing Mode 1

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

THEORY OF COMPILATION

Transcription:

Problem Chapter 10 Memory Model for Program Execution Original slides by Chris Wilcox, Colorado State University How do we allocate memory during the execution of a program written in C?! Programs need memory for code and data such as instructions, global and local variables, etc.! Modern programming practices encourage many (reusable) functions, callable from anywhere.! Some memory can be statically allocated, since the size and type is known at compile time.! Some memory must be allocated dynamically, size and type is unknown at compile time. 2 Motivation Why is memory allocation important? Why not just use a memory manager?! Allocation affects the performance and memory usage of every C, C++, Java program.! Current systems do not have enough registers to store everything that is required.! Memory management is too slow and cumbersome to solve the problem.! Static allocation of memory resources is too inflexible and inefficient, as we will see.! What do we care about? Goals Fast program execution Efficient memory usage Avoid memory fragmentation Maintain data locality Allow recursive calls Support parallel execution Minimize resource allocation Memory should never be allocated for functions that are not executed. 3 4 1

Function Call! Consider the following code: // main program int a = 10; int b = 20 c = foo(a, b); int foo(int x, int y) { int z; z = x + y; return z; }! What needs to be stored? Code, parameters, locals, globals, return values Storage Requirements! Code must be stored in memory so that we can execute the function.! The return address must be stored so that control can be returned to the caller.! Parameters must be sent from the caller to the callee so that the function receives them.! Return values must be sent from the callee to the caller, that s how results are returned.! Local variables for the function must be stored somewhere, is one copy enough? 5 6 Possible Solution: Mixed Code and Data! Function implementation: foo JMP foo_code # skip over data foo_rv.blkw 1 # return value foo_ra.blkw 1 # return address foo_paramx.blkw 1 # x parameter foo_paramy.blkw 1 # y parameter foo_localz.blkw 1 # z local foo_begin STR R7, foo_rv # save return LDR R7, foo_ra # restore return RET! Can construct data section by appending foo_ Possible Solution: Mixed Code and Data! Calling sequence ST R1, foo_paramx # R1 has x ST R2, foo_paramx # R2 has y JSR foo # Function call LDR R3, foo_rv # R3 = return value! Code generation is relatively simple.! Few instructions are spent moving data. 7 8 2

Possible Solution: Mixed Code and Data! Advantages: Code and data are close together Conceptually easy to understand Minimizes register usage for variables Data persists through life of program! Disadvantages: Cannot handle recursion or parallel execution Code is vulnerable to self-modification Consumes resource for inactive functions Possible Solution: Separate Code and Data! Memory allocation: foo_rv.blkw 1 # foo return value foo_ra.blkw 1 # foo return address foo_paramx.blkw 1 # foo x parameter foo_paramy.blkw 1 # foo y parameter foo_localz.blkw 1 # foo z local bar_rv.blkw 1 # bar return value bar_ra.blkw 1 # bar return address bar_paramw.blkw 1 # bar w parameter! Code for foo() and bar() are somewhere else! Function code call is similar to mixed solution 9 10 Possible Solution: Separate Code and Data! Advantages: Code can be marked read only Conceptually easy to understand Early Fortran used this scheme Data persists through life of program! Disadvantages: Cannot handle recursion or parallel execution Consumes resource for inactive functions 11 Real Solution:! Instructions are stored in code segment! Global data is stored in data segment! Statically allocated memory uses stack! Dynamically allocated memory uses heap x0000 xffff Code Data Heap Stack Code segment is write protected Initialized and uninitialized globals Heap can be fragmented Stack size is usually limited Stack can grow either direction (usual convention is down) 12 3

! What is a stack? First In, Last Out (FILO) data structure PUSH adds data, POP removes data Overflow condition: push when stack full Underflow condition: pop when stack empty Stack grows and shrinks as data is added and removed Stack grows downward from the end of memory space Function calls allocate a stack frame Return cleans up by freeing the stack frame Corresponds nicely to nested function calls Stack Trace shows current execution (Java/Eclipse) Stack Trace! Example stack trace from gdb: main() calls A() calls B() calls C() calls D().! Breakpoint is set in function D(), note that main() is at the bottom, D() is at the top. (gdb) info stack #0 D (a=8, b=9) at stacktest.c:23 #1 0x00400531 in C (a=7, b=8) at stacktest.c:19 #2 0x0040050c in B (a=6, b=7) at stacktest.c:15 #3 0x004004e7 in A (a=5, b=6) at stacktest.c:11 #4 0x00400566 in main () at stacktest.c:29 13 14! Picture of stack during program execution, same call stack as previous slide: main() calls A(5,6) A(5,6) calls B(6,7) B(6,7) calls C(7,8) C(7,8) calls D(8,9) x0000 xffff D(8,9) C(7,8) B(6,7) A(5,6) main() Stack Requirements! Consider what has to happen in a function call: Caller must allocate space for the return value. Caller must pass parameters to the callee. Caller must save the return address. Caller must transfer control to the callee. Callee requires space for local variables. Callee must return control to the caller.! Parameters, return value, return address, and locals are stored on the stack.! The order above determines the responsibility and order of stack operations. 15 16 4

! Definition: A stack frame or activation record is the memory required for a function call: x0000 xffff Locals Return Address Parameters Return Value Stack frame below contains the function that called this function. Stack frame above contains the functions called from this function. Caller allocates return value, pushes parameters and return address. Callee allocates and frees local variables, stores the return value. Stack Pointers! Clearly we need a variable to store the stack pointer (SP), LC3 assembly uses R6.! Stack execution is ubiquitous, so hardware has a stack pointer, sometimes even instructions.! Problem: stack pointer is difficult to use to access data, since it moves around constantly.! Solution: allocate another variable called a frame pointer (FP), for stack frame, uses R5.! Where should frame pointer point? Convention sets it between caller and callee data. 17 18! Definition: A stack frame or activation record is the memory required for a function call: x0000 xffff Locals Return Address Parameters Return Value SP FP Locals are accessed by negative offsets from frame pointer. Parameters and return value are accessed by positive offsets. Most offsets are small, this explains LDR/STR implementation. Base register stores pointer, signed offset accesses both directions.! In the previous solutions, the compiler allocated parameters and locals in fixed memory locations.! Using an execution stack means parameters and locals are constantly moving around.! The frame pointer solves this problem by using fixed offsets instead of addresses.! The compiler can generate code using offsets, without knowing where the stack frame will reside.! Frame pointer needs to be saved and restored around function calls. How about the stack pointer? 19 20 5

Nested Calls! Definition: A stack frame or activation record is the memory required for a function call: D(8,9) C(7,8) B(6,7) A(5,6) main() FP(D) FP(C) FP(B) FP(A) Locals are accessed by negative offsets from frame pointer. Parameters and return value are accessed by positive offsets. Most offsets are small, this explains LDR/STR implementation. Base register stores pointer, signed offset accesses both directions.! Advantages: Code can be marked read only Conceptually easy to understand Supports recursion and parallel execution No resources for inactive functions Good data locality, no fragmenting Minimizes register usage! Disadvantages: More memory than static allocation 21 22! Assume POP and PUSH code as follows: MACRO PUSH(reg) ADD R6,R6,#-1 ; Decrement SP STR reg,r6,#0 ; Store value END MACRO POP(reg) LDR R0,R6,#0 ADD R6,R6,#1 END ; Load value ; Increment SP! Main program to illustrate stack convention:.orig x3000 MAIN LD R6,STACK ; init stack pointer LD R0,OPERAND0 ; load first operand PUSH R0 ; PUSH first operand LD R1,OPERAND1 ; load second operand PUSH R1 ; PUSH second operand JSR FUNCTION ; call function LDR R0,R6,#0 ; POP return value ADD R6,R6,#3 ; unwind stack ST R0,RESULT ; store result HALT 23 24 6

! Function code to illustrate stack convention: Second Operand SP First Operand Stack before JSR instruction FUNCTION ADD R6,R6,#-1 ; alloc return value PUSH R7 ; PUSH return address PUSH R5 ; PUSH frame pointer ADD R5,R6,#-1 ; FP = SP-1 ADD R6,R6,#-1 ; alloc local variable LDR R2,R5,#4 ; load first operand LDR R3,R5,#5 ; load second operand ADD R4,R3,R2 ; add operands STR R4,R5,#0 ; store local variable 25 26 FP[0] FP[1] FP[2] FP[3] FP[4] FP[5] Local Variable Frame Pointer Return Address Return Value Second Operand First Operand FP Stack before STR instruction! Function code to illustrate stack convention: FUNCTION ; stack exit code STR R4,R5,#3 ; store return value ADD R6,R5,#1 ; SP = FP+1 POP R5 ; POP frame pointer POP R7 ; POP return address RET ; return OPERAND0.FILL x1234 ; first operand OPERAND1.FILL x2345 ; second operand RESULT.BLKW 1 ; result STACK.FILL x4000 ; stack address 27 28 7

Stack Execution! Summary of memory model: We have discussed the stack model for execution of C programs, and along the way we have shown how a compiler might generate code for function calls.! Future programming assignment: Write a recursive function in C, then implement the same function in assembly code, managing memory using the stack model. 29 8