Compiler Construction D7011E

Size: px
Start display at page:

Download "Compiler Construction D7011E"

Transcription

1 Compiler Construction D7011E Lecture 14: Memory Management Viktor Leijon Slides largely by Johan Nordlander with material generously provided by Mark P. Jones. 1

2 First: Run-time Systems 2

3 The Final Component: We have followed the workings of a compiler: From source input to code generation. We can use an assembler to turn the compiler s output into an object file. To produce an executable program, we must link the object file to the the compiler s run-time system. 3

4 Why use a Run-time System? Every programming language provides a different view of what the computer can do: Built-in types, and associated operations; I/O facilities; Concurrency and multiple threads; Dynamic memory allocation; Etc.. Different computers, and different operating systems, do not necessarily support all of these features directly, and will often use different interfaces, and even different semantics. 4

5 Examples from Java: Not all CPUs have built-in support for floating point division, or for standard mathematical functions like square root, sin, or log. Unix systems use file descriptors to identify files, and don t know anything about the File, OutputStream, etc. objects used in Java. Many operating systems include support for multiple threads of execution, but they don t all use the same interface. 5

6 Using a Run-time System: Compiled Program Run-time System Operating System / Hardware A run-time system bridges the gap between: The language designer s expectation of what facilities the underlying system will provide; and The set of features that are actually supported by the machine or its operating system. 6

7 Run-time Libraries: Conceptually, a run-time system has two parts: A set of conventions about the way that different kinds of value are represented, and about the data structures that are used; A library of code to implement the required features, or to wrap up operating system features according to the conventions of the run-time system. Compiled programs: Must follow the conventions of the run-time system; May include references to code in the run-time library. 7

8 Linking: A linking process is used to build executable programs by connecting compiled object files to the appropriate run-time system libraries. The goal is to fill each reference in an object file with the corresponding code from the library. Object Code Run-time Library Executable Program f a g a b c d e f g h f a g u m c n x i j k l m n u v w x y z Link u m c x n 8

9 Static Linking: Static linking produces executable code by inserting sections of run-time library code into each executable program. Thus portions of the run-time library may be duplicated many times over, which takes extra space on disk, and in memory (if multiple processes are executing). If there is a bug in a run-time library routine, then all compiled programs will need to be rebuilt. 9

10 Dynamic Linking: With dynamic linking, libraries are separate units that can be loaded into memory and connected to executable code as needed. It is enough to have just one copy of a dynamically linked library (DLL) on disk. A single copy in memory to be shared between multiple programs. In effect, DLLs behave like extensions of the operating system. But programs using DLLs won t run properly without suitable versions of their libraries. 10

11 Run-time System Pros: Portability: A run-time system isolates a program from the details of a particular operating environment, and so makes it easier to port code between different platforms. Reuse: A run-time system provides standardized libraries and abstractions that can be used in many different programs. Higher levels of abstraction: A run-time system can package up low-level features in a way that makes them easier to understand and use. 11

12 Run-time System Cons: Size: A comprehensive run-time system may be quite large, and so require a lot of effort to implement and port. Overhead: A run-time system can add overhead, increasing the size of executable programs. Coding Difficulties: The implementation of some features may conflict with the semantics of features in the underlying system, and so require an inefficient or indirect encoding. 12

13 A Question of Scale: For the MiniJava compiler, only three run-time system features are required: Initialization of a program; Output of an integer value; Allocation of a new object. In real compilers, the run-time system is often much larger than the compiler, and requires at least as much effort to implement, maintain, and document. 13

14 MiniJava Run-Time Support: Initialization: No special needs by naming our top-level assembly language routine main (and exporting it by.globl main), we can rely on the standard C/Unix program startup code. Printing integers: Simplest solution: just issue a call to the standard C library routine printf. First argument is a pointer to the constant string "%d\n", second argument is the integer to print. Allocating memory: Simplification: no memory recycling is necessary for the project. This means that memory allocation can most easily be done using the standard C library routine void* malloc(int) 14

15 Accessing the RTS Functions: From assembly language: No "import" or "external" declarations are needed. However, some platforms insist that printf and malloc are referred to as _printf and _malloc (you will quickly find out which is the case!). From LLVM: Include the following declarations: declare i32) declare (Note that we're giving printf a quite restrictive type here, but that's approximating in the safe direction.) 15

16 Declaring a String Literal: In assembly code: Add the following declaration: str:.asciz "%d\n" Just refer to the string address as str. In LLVM: Add the following global declaration (yes, odd = global [4 x i8] c"%d\0a\00" now has type [4 x i8]* must be type-cast to i8* before %str1 = getelementptr [4 x i32 0, i

17 Calculating Object Sizes: In assembly code: You have full control over the object sizes just give malloc the correct byte-count. In LLVM: Since the size of pointer types is not under direct control in LLVM, the proper way to obtain the size of a type %T is: %1 = getelementptr %T* null, i32 1 %sizet = ptrtoint %T* %1 to i32 Note: the malloc result is an i8*, must be cast to a %T*: %2 = call %sizet) %ptrt = bitcast i8* %2 to %T* 17

18 Declaring Method Tables: Assume we have a class T: class T {...; int m1(int x) {...}; int m2(int x, int y) {...}; } In assembly code:.section DATA, const T_vtab:.long m1.long m2 In LLVM (note the syntax for function pointers!): %T = type { %T_vt*,... } %T_vt = type { i32(%t*,i32)*, i32(%t*,i32,i32)* = global %T_vt { } 18

19 Dynamic Memory Allocation and Garbage Collection: 19

20 Dynamic Memory Allocation: Dynamic memory allocation is used when the amount of memory that will be needed to store a program s data cannot be predicted at compile-time. Examples of programs where this is useful include: compilers, web browsers, word processors, 20

21 Allocation in Run-time Systems: Some languages do not support dynamically allocated memory; instead, programmers must anticipate/guess the requirements at compiletime and pre-allocate storage accordingly. Many operating systems do not support (finegrained) dynamic memory allocation well but many languages require it. As a result, dynamic memory allocation is one of the most commonly supported features in modern run-time systems. 21

22 Explicit Allocation: Different languages provide different ways to allocate memory: bytes = (int*)malloc(120); ints = new int[30]; expr = new IntExpr(120); list = x:xs (cons x xs) 22

23 Allocating from a Heap: Where does dynamically allocated memory come from? When the run-time system is initialized, it requests a large block of memory from the operating system, which is known as the heap. The run-time system maintains a heap pointer that identifies the next free location. allocated not yet allocated Heap pointer To allocate n bytes, we return the current heap pointer setting, and advance the heap pointer by n. 23

24 Allocation is Only Half the Story: What happens when we run out of memory? Can we reclaim and recycle memory when we finish using it? 24

25 Memory Usage in a Compiler: Here is a (hypothetical) graph to illustrate how memory is used by a typical compiler: memory parsing static analysis output time NOT TO SCALE! When a program exits, any memory that it has used is returned to the operating system. We probably don t need to worry about reclaiming memory in programs that run only for a short time. 25

26 Memory Usage in a Browser: Each time you visit a new web page, the browser needs to allocate memory to store the text, images, and other items on that page. You might run a browser for a long time and visit many web pages. If the browser doesn t take steps to reclaim memory, then, eventually, your browser will not be able to load any new web pages. 26

27 Reclaiming Memory Explicitly: In some languages, programmers can tell the run-time system that they have finished with a piece of memory, and that it can be recycled. free(ptr); /* C */ destroy obj; /* C++ */ This can be risky; the programmer must ensure that: The specified memory was allocated dynamically; No part of the program will attempt to access that section of memory again. 27

28 Reclaiming Memory in a Browser: It is easy to manage memory in a browser: Keep data for the web pages that can be reached using the Back and Forward buttons. If memory gets tight, we can reclaim the storage used by some of the web pages: we can store the data on disk, or download it again if it is needed. In other words, it is easy to see where the calls to free or destroy should go. 28

29 Reclaiming Memory Automatically: In general, however: It is hard to know when memory can be reclaimed; If it is too early, the run-time system s structures will be corrupted, and the program could crash; If memory is reclaimed too late, then the program will have a space leak and use more memory than it needs. Incorrect attempts to reclaim memory are one of the biggest sources of bugs in C++ programs. Could a run-time system do better in deciding when memory can be reclaimed? 29

30 Garbage Collection: Garbage collection is the term used to describe automatic reclamation of computer storage. An object is garbage if it will not be used again in other words, if it is not live. Conceptually, garbage collection is a two phase process: Garbage detection: Distinguish live objects from those which are garbage. Garbage reclamation: Reclaim memory used by garbage so that the running program can reuse it. In practice, these phases may be interleaved. 30

31 How do we Detect Garbage? First Attempt: An object is garbage if there are no pointers to it. this leads us to the technique of reference counting. 31

32 Reference Counting: A run-time system can attach a reference count to each chunk of memory that is allocated. The reference count is the number of pointers to this object from elsewhere in the program. Every time we duplicate a pointer to an object, we increment the reference count. Every time we eliminate a pointer to an object, we decrement the reference count. When the reference count is zero, the object can be reclaimed. 32

33 Example: p q

34 Example: p q p = q;

35 Example: p q p q p = q;

36 Example: p q p q p = q; Now this object is garbage 33

37 Example: p q p q p = q; Now this object is garbage Reference counts take up one word of memory per object. A compiler can generate code to maintain the reference counts, but the overhead might be high. 33

38 The Problem With Cycles:

39 The Problem With Cycles: 1 1 The two values shown here are garbage; neither one can be reached from anywhere else in the program. But neither one has a zero reference count, so neither one will be reclaimed a memory leak! Thus additional steps must be taken to deal with cycles one further reason why reference counting is not popular in run-time systems. 34

40 How do we Detect Garbage? First Attempt: An object is garbage if there are no pointers to it. this leads us to the technique of reference counting. 35

41 How do we Detect Garbage? First Attempt: An object is garbage if there are no pointers to it. this leads us to the technique of reference counting. But an object can be garbage, even if there are pointers to it if those pointers are in other pieces of garbage. 35

42 How do we Detect Garbage? First Attempt: An object is garbage if there are no pointers to it. this leads us to the technique of reference counting. But an object can be garbage, even if there are pointers to it if those pointers are in other pieces of garbage. Second Attempt: An object is garbage if it is unreachable. This is still conservative, but usually works quite well. 35

43 Reachability: Suppose that we could interrupt a MiniJava computation at any stage. Which objects might be live at that point? We can identify a set of roots for live data: Any object that is pointed to from a global variable (i.e., a static field in a class, but we don t have those in MiniJava); Any object that is pointed to from an active frame on the stack. Any object that can be reached from one (or more) of the roots might be used in a future computation. 36

44 Understanding Reachability: p q root set 37

45 Understanding Reachability: p q root set 37

46 Understanding Reachability: p q root set 37

47 Understanding Reachability: p q root set 37

48 Understanding Reachability: p q root set 37

49 Understanding Reachability: p q root set All that remains unmarked is garbage! 37

50 Mark-Sweep Garbage Collection: This is almost exactly how a mark-sweep garbage collector works: The mark phase: Traverse the graph, starting at the roots, and mark every object that is reached; The sweep phase: Storage for any object that has not been marked can be reclaimed. The time to garbage collect is proportional to the size of the heap: we have to sweep the whole heap to find unmarked objects. 38

51 How do we Reclaim Memory? Once the marking phase is over, the heap will typically be broken into a mixture of marked and unmarked areas: We can reclaim memory by linking together the unused areas: free list 39

52 Allocating From a Free List: Now we must allocate memory from the free list too; we can t just advance a heap pointer. To allocate n bytes: Search for the first free chunk with n bytes in it; Allocate the required memory from that chunk; Return any unused portion to the free list. There are some techniques that we can use to make this more efficient. Exactly the same problems occur in systems with explicit memory reclamation (malloc() ) 40

53 Fragmentation: Another serious problem here is the risk of fragmentation, which happens when memory is broken into small pieces that are hard to reuse. For example, we can t allocate an object in a heap that looks like this: Although there is enough unused memory, in total, it isn t available in one contiguous block. Several compaction techniques have been developed to overcome this problem. 41

54 A Copying Collector: A copying collector works by copying all the reachable data to a safe place, and then discarding the original heap altogether! Copying collectors usually alternate between two heaps. At each garbage collection, reachable values in one heap ( from space ) are copied into new locations in the other ( to space ). 42

55 Pros and Cons: J A copying collector ensures that the heap is compacted at each garbage collection: J No fragmentation! J We can go back to allocating using a simple heap pointer. J The time to garbage collect is proportional to the amount memory that is reachable, which may be much less than the size of the heap. L We have to split available memory resources between two large heaps of equal size, even though we only use one at a time. 43

56 Some Details: We will look at a copying garbage collection algorithm in a little more detail. Let s assume that the runtime system maintains the following variables: fromspace the address of the active heap; tospace hp the address of the second heap; the heap pointer. Normally, hp points into fromspace. At the start of a garbage collection, we will reset it to point to the start of tospace. 44

57 Object Representations: We will also add some extra details to the representation of objects to support garbage collection: fields size forward scavenge methods The number of bytes in this object. Code to copy this object into tospace. Code to copy this object s fields to tospace. [Virtual methods listed here, as before] 45

58 Forwarding An Object: To copy an object from fromspace to tospace: Addr forward(addr obj) { } Addr dest = hp; for (i=0; i<obj.tag.size; i++) mem[hp++] = obj[i]; obj.tag = FORWARDED; obj.field1 = dest; return dest; The object s new address in tospace. Assume every object at least 8 bytes long. 46

59 The FORWARDED tag: Once an object has been forwarded, it should not be forwarded again. We deal with this by overwriting the tag of each forwarded object with the address FORWARDED, which points to a special virtual function table: not used forward Addr forwarded(addr obj) { return obj.field1; } The same address as the first time this object was forwarded 47

60 Scavenging An Object: Scavenging = forwarding the pointer-fields of an object: void scavenge(addr obj) { } obj.field1 = obj.field1.forward(); obj.field2 = obj.field2.forward(); Only pointers to objects should be scavenged, and not all fields contain such pointers. A compiler can generate an appropriate scavenge function for each class using the list of fields in that class. 48

61 Using tospace as a Queue: Initially, tospace is empty: Once the roots have been forwarded, it looks like this: tovisit hp Now we scavenge each object, left to right, using tospace as a queue: scavenged tovisit Waiting to be scavenged hp Unused space into which objects might be forwarded. 49

62 Putting it all Together: hp = tospace; for each root r { r = r.forward(); } tovisit = tospace; while (tovisit < hp) { tovisit.scavenge(); tovisit += tovisit.tag.size; } exchange tospace and fromspace; Make sure all the roots are forwarded Scavenge each forwarded object for pointers 50

63 Incremental Garbage Collection: The techniques that we have looked at so far put the main computation on hold while garbage collection is taking place. For an interactive program with a large heap size, this might cause a noticeable pause in execution. For real-time applications, a long pause at random is not acceptable. Much effort has been invested in the design of more sophisticated, incremental garbage collection algorithms that solve these problems by interleaving detection and reclamation. 51

64 Generational Garbage Collection: Experiments suggest most data is short-lived. Generational collectors exploit this by breaking the heap into several generations. old middle new The new generation is smaller and takes less time to garbage collect. Most objects die during the new collection. Those that survive are promoted to the middle generation, which needs less frequent collections. Objects that survive a middle collection are promoted to the old generation, which needs even less frequent collections. 52

65 The Cost of Garbage Collection: Appel has argued that garbage collection can sometimes be cheaper than stack allocation. Other estimates suggest that use of garbage collection can increase execution time by 10%. In any case: The cost depends on the quality of the garbage collector, and on the program that uses it. There are also overheads with schemes for explicitly reclaimed memory Perhaps the overheads of garbage collection are justified by the reduction in bugs? 53

66 Further Reading: There is a large literature on garbage collection; we have only scraped the surface here! There is some material in Appel s book. There is a book devoted to garbage collection by Richard Jones and Rafael Lins: But you could do a lot worse than start with Paul Wilson s long, but excellent survey at: ftp://ftp.cs.utexas.edu/pub/garbage/bigsurv.ps 54

Garbage Collection (1)

Garbage Collection (1) Garbage Collection (1) Advanced Operating Systems Lecture 7 This work is licensed under the Creative Commons Attribution-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nd/4.0/

More information

Garbage Collection. Akim D le, Etienne Renault, Roland Levillain. May 15, CCMP2 Garbage Collection May 15, / 35

Garbage Collection. Akim D le, Etienne Renault, Roland Levillain. May 15, CCMP2 Garbage Collection May 15, / 35 Garbage Collection Akim Demaille, Etienne Renault, Roland Levillain May 15, 2017 CCMP2 Garbage Collection May 15, 2017 1 / 35 Table of contents 1 Motivations and Definitions 2 Reference Counting Garbage

More information

Lecture Notes on Garbage Collection

Lecture Notes on Garbage Collection Lecture Notes on Garbage Collection 15-411: Compiler Design Frank Pfenning Lecture 21 November 4, 2014 These brief notes only contain a short overview, a few pointers to the literature with detailed descriptions,

More information

Runtime. The optimized program is ready to run What sorts of facilities are available at runtime

Runtime. The optimized program is ready to run What sorts of facilities are available at runtime Runtime The optimized program is ready to run What sorts of facilities are available at runtime Compiler Passes Analysis of input program (front-end) character stream Lexical Analysis token stream Syntactic

More information

Lecture 13: Garbage Collection

Lecture 13: Garbage Collection Lecture 13: Garbage Collection COS 320 Compiling Techniques Princeton University Spring 2016 Lennart Beringer/Mikkel Kringelbach 1 Garbage Collection Every modern programming language allows programmers

More information

Programming Language Implementation

Programming Language Implementation A Practical Introduction to Programming Language Implementation 2014: Week 10 Garbage Collection College of Information Science and Engineering Ritsumeikan University 1 review of last week s topics dynamic

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Memory Management and Garbage Collection CMSC 330 - Spring 2013 1 Memory Attributes! Memory to store data in programming languages has the following lifecycle

More information

Heap Management. Heap Allocation

Heap Management. Heap Allocation Heap Management Heap Allocation A very flexible storage allocation mechanism is heap allocation. Any number of data objects can be allocated and freed in a memory pool, called a heap. Heap allocation is

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Memory Management and Garbage Collection CMSC 330 Spring 2017 1 Memory Attributes Memory to store data in programming languages has the following lifecycle

More information

Acknowledgements These slides are based on Kathryn McKinley s slides on garbage collection as well as E Christopher Lewis s slides

Acknowledgements These slides are based on Kathryn McKinley s slides on garbage collection as well as E Christopher Lewis s slides Garbage Collection Last time Compiling Object-Oriented Languages Today Motivation behind garbage collection Garbage collection basics Garbage collection performance Specific example of using GC in C++

More information

Robust Memory Management Schemes

Robust Memory Management Schemes Robust Memory Management Schemes Prepared by : Fadi Sbahi & Ali Bsoul Supervised By: Dr. Lo ai Tawalbeh Jordan University of Science and Technology Robust Memory Management Schemes Introduction. Memory

More information

CS577 Modern Language Processors. Spring 2018 Lecture Garbage Collection

CS577 Modern Language Processors. Spring 2018 Lecture Garbage Collection CS577 Modern Language Processors Spring 2018 Lecture Garbage Collection 1 BASIC GARBAGE COLLECTION Garbage Collection (GC) is the automatic reclamation of heap records that will never again be accessed

More information

Memory Allocation. Static Allocation. Dynamic Allocation. Dynamic Storage Allocation. CS 414: Operating Systems Spring 2008

Memory Allocation. Static Allocation. Dynamic Allocation. Dynamic Storage Allocation. CS 414: Operating Systems Spring 2008 Dynamic Storage Allocation CS 44: Operating Systems Spring 2 Memory Allocation Static Allocation (fixed in size) Sometimes we create data structures that are fixed and don t need to grow or shrink. Dynamic

More information

Deallocation Mechanisms. User-controlled Deallocation. Automatic Garbage Collection

Deallocation Mechanisms. User-controlled Deallocation. Automatic Garbage Collection Deallocation Mechanisms User-controlled Deallocation Allocating heap space is fairly easy. But how do we deallocate heap memory no longer in use? Sometimes we may never need to deallocate! If heaps objects

More information

Garbage Collection. Hwansoo Han

Garbage Collection. Hwansoo Han Garbage Collection Hwansoo Han Heap Memory Garbage collection Automatically reclaim the space that the running program can never access again Performed by the runtime system Two parts of a garbage collector

More information

Structure of Programming Languages Lecture 10

Structure of Programming Languages Lecture 10 Structure of Programming Languages Lecture 10 CS 6636 4536 Spring 2017 CS 6636 4536 Lecture 10: Classes... 1/23 Spring 2017 1 / 23 Outline 1 1. Types Type Coercion and Conversion Type Classes, Generics,

More information

CMSC 330: Organization of Programming Languages. Memory Management and Garbage Collection

CMSC 330: Organization of Programming Languages. Memory Management and Garbage Collection CMSC 330: Organization of Programming Languages Memory Management and Garbage Collection CMSC330 Fall 2018 1 Memory Attributes Memory to store data in programming languages has the following lifecycle

More information

CS 345. Garbage Collection. Vitaly Shmatikov. slide 1

CS 345. Garbage Collection. Vitaly Shmatikov. slide 1 CS 345 Garbage Collection Vitaly Shmatikov slide 1 Major Areas of Memory Static area Fixed size, fixed content, allocated at compile time Run-time stack Variable size, variable content (activation records)

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 2 Thomas Wies New York University Review Last week Programming Languages Overview Syntax and Semantics Grammars and Regular Expressions High-level

More information

Lecture Notes on Garbage Collection

Lecture Notes on Garbage Collection Lecture Notes on Garbage Collection 15-411: Compiler Design André Platzer Lecture 20 1 Introduction In the previous lectures we have considered a programming language C0 with pointers and memory and array

More information

Automatic Garbage Collection

Automatic Garbage Collection Automatic Garbage Collection Announcements: PS6 due Monday 12/6 at 11:59PM Final exam on Thursday 12/16 o PS6 tournament and review session that week Garbage In OCaml programs (and in most other programming

More information

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

CS 536 Introduction to Programming Languages and Compilers Charles N. Fischer Lecture 11 CS 536 Introduction to Programming Languages and Compilers Charles N. Fischer Lecture 11 CS 536 Spring 2015 1 Handling Overloaded Declarations Two approaches are popular: 1. Create a single symbol table

More information

Compiler Construction

Compiler Construction Compiler Construction Thomas Noll Software Modeling and Verification Group RWTH Aachen University https://moves.rwth-aachen.de/teaching/ss-16/cc/ Recap: Static Data Structures Outline of Lecture 18 Recap:

More information

CS61C : Machine Structures

CS61C : Machine Structures inst.eecs.berkeley.edu/~cs61c/su06 CS61C : Machine Structures Lecture #6: Memory Management CS 61C L06 Memory Management (1) 2006-07-05 Andy Carle Memory Management (1/2) Variable declaration allocates

More information

Garbage Collection Techniques

Garbage Collection Techniques Garbage Collection Techniques Michael Jantz COSC 340: Software Engineering 1 Memory Management Memory Management Recognizing when allocated objects are no longer needed Deallocating (freeing) the memory

More information

Sustainable Memory Use Allocation & (Implicit) Deallocation (mostly in Java)

Sustainable Memory Use Allocation & (Implicit) Deallocation (mostly in Java) COMP 412 FALL 2017 Sustainable Memory Use Allocation & (Implicit) Deallocation (mostly in Java) Copyright 2017, Keith D. Cooper & Zoran Budimlić, all rights reserved. Students enrolled in Comp 412 at Rice

More information

Project. there are a couple of 3 person teams. a new drop with new type checking is coming. regroup or see me or forever hold your peace

Project. there are a couple of 3 person teams. a new drop with new type checking is coming. regroup or see me or forever hold your peace Project there are a couple of 3 person teams regroup or see me or forever hold your peace a new drop with new type checking is coming using it is optional 1 Compiler Architecture source code Now we jump

More information

Pointers II. Class 31

Pointers II. Class 31 Pointers II Class 31 Compile Time all of the variables we have seen so far have been declared at compile time they are written into the program code you can see by looking at the program how many variables

More information

Compiler Construction

Compiler Construction Compiler Construction Lecture 18: Code Generation V (Implementation of Dynamic Data Structures) Thomas Noll Lehrstuhl für Informatik 2 (Software Modeling and Verification) noll@cs.rwth-aachen.de http://moves.rwth-aachen.de/teaching/ss-14/cc14/

More information

Memory Management. Chapter Fourteen Modern Programming Languages, 2nd ed. 1

Memory Management. Chapter Fourteen Modern Programming Languages, 2nd ed. 1 Memory Management Chapter Fourteen Modern Programming Languages, 2nd ed. 1 Dynamic Memory Allocation Lots of things need memory at runtime: Activation records Objects Explicit allocations: new, malloc,

More information

Implementation Garbage Collection

Implementation Garbage Collection CITS 3242 Programming Paradigms Part IV: Advanced Topics Topic 19: Implementation Garbage Collection Most languages in the functional, logic, and object-oriented paradigms include some form of automatic

More information

HOT-Compilation: Garbage Collection

HOT-Compilation: Garbage Collection HOT-Compilation: Garbage Collection TA: Akiva Leffert aleffert@andrew.cmu.edu Out: Saturday, December 9th In: Tuesday, December 9th (Before midnight) Introduction It s time to take a step back and congratulate

More information

Garbage Collection Algorithms. Ganesh Bikshandi

Garbage Collection Algorithms. Ganesh Bikshandi Garbage Collection Algorithms Ganesh Bikshandi Announcement MP4 posted Term paper posted Introduction Garbage : discarded or useless material Collection : the act or process of collecting Garbage collection

More information

Garbage Collection. Steven R. Bagley

Garbage Collection. Steven R. Bagley Garbage Collection Steven R. Bagley Reference Counting Counts number of pointers to an Object deleted when the count hits zero Eager deleted as soon as it is finished with Problem: Circular references

More information

CS61, Fall 2012 Section 2 Notes

CS61, Fall 2012 Section 2 Notes CS61, Fall 2012 Section 2 Notes (Week of 9/24-9/28) 0. Get source code for section [optional] 1: Variable Duration 2: Memory Errors Common Errors with memory and pointers Valgrind + GDB Common Memory Errors

More information

Run-Time Environments/Garbage Collection

Run-Time Environments/Garbage Collection Run-Time Environments/Garbage Collection Department of Computer Science, Faculty of ICT January 5, 2014 Introduction Compilers need to be aware of the run-time environment in which their compiled programs

More information

Memory Management. Memory Management... Memory Management... Interface to Dynamic allocation

Memory Management. Memory Management... Memory Management... Interface to Dynamic allocation CSc 453 Compilers and Systems Software 24 : Garbage Collection Introduction Department of Computer Science University of Arizona collberg@gmail.com Copyright c 2009 Christian Collberg Dynamic Memory Management

More information

Memory Management. Didactic Module 14 Programming Languages - EEL670 1

Memory Management. Didactic Module 14 Programming Languages - EEL670 1 Memory Management Didactic Module 14 Programming Languages - EEL670 1 Dynamic Memory Allocation Lots of things need memory at runtime: Activation records Objects Explicit allocations: new, malloc, etc.

More information

Automatic Memory Management

Automatic Memory Management Automatic Memory Management Why Automatic Memory Management? Storage management is still a hard problem in modern programming Why Automatic Memory Management? Storage management is still a hard problem

More information

Heap Compression for Memory-Constrained Java

Heap Compression for Memory-Constrained Java Heap Compression for Memory-Constrained Java CSE Department, PSU G. Chen M. Kandemir N. Vijaykrishnan M. J. Irwin Sun Microsystems B. Mathiske M. Wolczko OOPSLA 03 October 26-30 2003 Overview PROBLEM:

More information

CS 4120 Lecture 37 Memory Management 28 November 2011 Lecturer: Andrew Myers

CS 4120 Lecture 37 Memory Management 28 November 2011 Lecturer: Andrew Myers CS 4120 Lecture 37 Memory Management 28 November 2011 Lecturer: Andrew Myers Heap allocation is a necessity for modern programming tasks, and so is automatic reclamation of heapallocated memory. However,

More information

Chapter 1 GETTING STARTED. SYS-ED/ Computer Education Techniques, Inc.

Chapter 1 GETTING STARTED. SYS-ED/ Computer Education Techniques, Inc. Chapter 1 GETTING STARTED SYS-ED/ Computer Education Techniques, Inc. Objectives You will learn: Java platform. Applets and applications. Java programming language: facilities and foundation. Memory management

More information

CA341 - Comparative Programming Languages

CA341 - Comparative Programming Languages CA341 - Comparative Programming Languages David Sinclair Dynamic Data Structures Generally we do not know how much data a program will have to process. There are 2 ways to handle this: Create a fixed data

More information

Managed runtimes & garbage collection. CSE 6341 Some slides by Kathryn McKinley

Managed runtimes & garbage collection. CSE 6341 Some slides by Kathryn McKinley Managed runtimes & garbage collection CSE 6341 Some slides by Kathryn McKinley 1 Managed runtimes Advantages? Disadvantages? 2 Managed runtimes Advantages? Reliability Security Portability Performance?

More information

Lecture Notes on Advanced Garbage Collection

Lecture Notes on Advanced Garbage Collection Lecture Notes on Advanced Garbage Collection 15-411: Compiler Design André Platzer Lecture 21 November 4, 2010 1 Introduction More information on garbage collection can be found in [App98, Ch 13.5-13.7]

More information

CPSC 213. Introduction to Computer Systems. Winter Session 2017, Term 2. Unit 1c Jan 24, 26, 29, 31, and Feb 2

CPSC 213. Introduction to Computer Systems. Winter Session 2017, Term 2. Unit 1c Jan 24, 26, 29, 31, and Feb 2 CPSC 213 Introduction to Computer Systems Winter Session 2017, Term 2 Unit 1c Jan 24, 26, 29, 31, and Feb 2 Instance Variables and Dynamic Allocation Overview Reading Companion: Reference 2.4.4-5 Textbook:

More information

A.Arpaci-Dusseau. Mapping from logical address space to physical address space. CS 537:Operating Systems lecture12.fm.2

A.Arpaci-Dusseau. Mapping from logical address space to physical address space. CS 537:Operating Systems lecture12.fm.2 UNIVERSITY of WISCONSIN-MADISON Computer Sciences Department CS 537 A. Arpaci-Dusseau Intro to Operating Systems Spring 2000 Dynamic Memory Allocation Questions answered in these notes When is a stack

More information

Managed runtimes & garbage collection

Managed runtimes & garbage collection Managed runtimes Advantages? Managed runtimes & garbage collection CSE 631 Some slides by Kathryn McKinley Disadvantages? 1 2 Managed runtimes Portability (& performance) Advantages? Reliability Security

More information

CS 241 Honors Memory

CS 241 Honors Memory CS 241 Honors Memory Ben Kurtovic Atul Sandur Bhuvan Venkatesh Brian Zhou Kevin Hong University of Illinois Urbana Champaign February 20, 2018 CS 241 Course Staff (UIUC) Memory February 20, 2018 1 / 35

More information

One-Slide Summary. Lecture Outine. Automatic Memory Management #1. Why Automatic Memory Management? Garbage Collection.

One-Slide Summary. Lecture Outine. Automatic Memory Management #1. Why Automatic Memory Management? Garbage Collection. Automatic Memory Management #1 One-Slide Summary An automatic memory management system deallocates objects when they are no longer used and reclaims their storage space. We must be conservative and only

More information

Review. Partitioning: Divide heap, use different strategies per heap Generational GC: Partition by age Most objects die young

Review. Partitioning: Divide heap, use different strategies per heap Generational GC: Partition by age Most objects die young Generational GC 1 Review Partitioning: Divide heap, use different strategies per heap Generational GC: Partition by age Most objects die young 2 Single-partition scanning Stack Heap Partition #1 Partition

More information

Lecture 15 Garbage Collection

Lecture 15 Garbage Collection Lecture 15 Garbage Collection I. Introduction to GC -- Reference Counting -- Basic Trace-Based GC II. Copying Collectors III. Break Up GC in Time (Incremental) IV. Break Up GC in Space (Partial) Readings:

More information

CS61C : Machine Structures

CS61C : Machine Structures inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture 4 Introduction to C (pt 2) 2014-09-08!!!Senior Lecturer SOE Dan Garcia!!!www.cs.berkeley.edu/~ddgarcia! C most popular! TIOBE programming

More information

The Dynamic Typing Interlude

The Dynamic Typing Interlude CHAPTER 6 The Dynamic Typing Interlude In the prior chapter, we began exploring Python s core object types in depth with a look at Python numbers. We ll resume our object type tour in the next chapter,

More information

CSCI 171 Chapter Outlines

CSCI 171 Chapter Outlines Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures

More information

CS61C : Machine Structures

CS61C : Machine Structures inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture 7 More Memory Management CS 61C L07 More Memory Management (1) 2004-09-15 Lecturer PSOE Dan Garcia www.cs.berkeley.edu/~ddgarcia Star Wars

More information

Exploiting the Behavior of Generational Garbage Collector

Exploiting the Behavior of Generational Garbage Collector Exploiting the Behavior of Generational Garbage Collector I. Introduction Zhe Xu, Jia Zhao Garbage collection is a form of automatic memory management. The garbage collector, attempts to reclaim garbage,

More information

Processes. Johan Montelius KTH

Processes. Johan Montelius KTH Processes Johan Montelius KTH 2017 1 / 47 A process What is a process?... a computation a program i.e. a sequence of operations a set of data structures a set of registers means to interact with other

More information

A process. the stack

A process. the stack A process Processes Johan Montelius What is a process?... a computation KTH 2017 a program i.e. a sequence of operations a set of data structures a set of registers means to interact with other processes

More information

Lecture 13: Complex Types and Garbage Collection

Lecture 13: Complex Types and Garbage Collection Lecture 13: Complex Types and Garbage Collection COMP 524 Programming Language Concepts Stephen Olivier March 17, 2009 Based on slides by A. Block, notes by N. Fisher, F. Hernandez-Campos, and D. Stotts

More information

Object-Oriented Programming for Scientific Computing

Object-Oriented Programming for Scientific Computing Object-Oriented Programming for Scientific Computing Dynamic Memory Management Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de 2. Mai 2017

More information

Compiler construction 2009

Compiler construction 2009 Compiler construction 2009 Lecture 6 Some project extensions. Pointers and heap allocation. Object-oriented languages. Module systems. Memory structure Javalette restrictions Only local variables and parameters

More information

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018 CS 31: Intro to Systems Pointers and Memory Kevin Webb Swarthmore College October 2, 2018 Overview How to reference the location of a variable in memory Where variables are placed in memory How to make

More information

High Performance Computing and Programming, Lecture 3

High Performance Computing and Programming, Lecture 3 High Performance Computing and Programming, Lecture 3 Memory usage and some other things Ali Dorostkar Division of Scientific Computing, Department of Information Technology, Uppsala University, Sweden

More information

Dynamic Storage Allocation

Dynamic Storage Allocation 6.172 Performance Engineering of Software Systems LECTURE 10 Dynamic Storage Allocation Charles E. Leiserson October 12, 2010 2010 Charles E. Leiserson 1 Stack Allocation Array and pointer A un Allocate

More information

Programming Languages Third Edition. Chapter 10 Control II Procedures and Environments

Programming Languages Third Edition. Chapter 10 Control II Procedures and Environments Programming Languages Third Edition Chapter 10 Control II Procedures and Environments Objectives Understand the nature of procedure definition and activation Understand procedure semantics Learn parameter-passing

More information

Lecture 8 Dynamic Memory Allocation

Lecture 8 Dynamic Memory Allocation Lecture 8 Dynamic Memory Allocation CS240 1 Memory Computer programs manipulate an abstraction of the computer s memory subsystem Memory: on the hardware side 3 @ http://computer.howstuffworks.com/computer-memory.htm/printable

More information

CS61C : Machine Structures

CS61C : Machine Structures inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture #5 Memory Management; Intro MIPS 2007-7-2 Scott Beamer, Instructor iphone Draws Crowds www.sfgate.com CS61C L5 Memory Management; Intro

More information

CS61C : Machine Structures

CS61C : Machine Structures inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture 7 C Memory Management 2007-02-06 Hello to Said S. from Columbus, OH CS61C L07 More Memory Management (1) Lecturer SOE Dan Garcia www.cs.berkeley.edu/~ddgarcia

More information

Memory management. Johan Montelius KTH

Memory management. Johan Montelius KTH Memory management Johan Montelius KTH 2017 1 / 22 C program # include int global = 42; int main ( int argc, char * argv []) { if( argc < 2) return -1; int n = atoi ( argv [1]); int on_stack

More information

Advanced Programming & C++ Language

Advanced Programming & C++ Language Advanced Programming & C++ Language ~6~ Introduction to Memory Management Ariel University 2018 Dr. Miri (Kopel) Ben-Nissan Stack & Heap 2 The memory a program uses is typically divided into four different

More information

Outline. Computer programming. Debugging. What is it. Debugging. Hints. Debugging

Outline. Computer programming. Debugging. What is it. Debugging. Hints. Debugging Outline Computer programming Debugging Hints Gathering evidence Common C errors "Education is a progressive discovery of our own ignorance." Will Durant T.U. Cluj-Napoca - Computer Programming - lecture

More information

QUIZ. What is wrong with this code that uses default arguments?

QUIZ. What is wrong with this code that uses default arguments? QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code

More information

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

Q1: /8 Q2: /30 Q3: /30 Q4: /32. Total: /100 ECE 2035(A) Programming for Hardware/Software Systems Fall 2013 Exam Three November 20 th 2013 Name: Q1: /8 Q2: /30 Q3: /30 Q4: /32 Total: /100 1/10 For functional call related questions, let s assume

More information

Memory Management. To do. q Basic memory management q Swapping q Kernel memory allocation q Next Time: Virtual memory

Memory Management. To do. q Basic memory management q Swapping q Kernel memory allocation q Next Time: Virtual memory Memory Management To do q Basic memory management q Swapping q Kernel memory allocation q Next Time: Virtual memory Memory management Ideal memory for a programmer large, fast, nonvolatile and cheap not

More information

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline CS 0 Lecture 8 Chapter 5 Louden Outline The symbol table Static scoping vs dynamic scoping Symbol table Dictionary associates names to attributes In general: hash tables, tree and lists (assignment ) can

More information

COSC Software Engineering. Lectures 14 and 15: The Heap and Dynamic Memory Allocation

COSC Software Engineering. Lectures 14 and 15: The Heap and Dynamic Memory Allocation COSC345 2013 Software Engineering Lectures 14 and 15: The Heap and Dynamic Memory Allocation Outline Revision The programmer s view of memory Simple array-based memory allocation C memory allocation routines

More information

Manual Allocation. CS 1622: Garbage Collection. Example 1. Memory Leaks. Example 3. Example 2 11/26/2012. Jonathan Misurda

Manual Allocation. CS 1622: Garbage Collection. Example 1. Memory Leaks. Example 3. Example 2 11/26/2012. Jonathan Misurda Manual llocation Dynamic memory allocation is an obvious necessity in a programming environment. S 1622: Garbage ollection Many programming languages expose some functions or keywords to manage runtime

More information

Lecture 4 September Required reading materials for this class

Lecture 4 September Required reading materials for this class EECS 261: Computer Security Fall 2007 Lecture 4 September 6 Lecturer: David Wagner Scribe: DK Moon 4.1 Required reading materials for this class Beyond Stack Smashing: Recent Advances in Exploiting Buffer

More information

Chapter 1 INTRODUCTION SYS-ED/ COMPUTER EDUCATION TECHNIQUES, INC.

Chapter 1 INTRODUCTION SYS-ED/ COMPUTER EDUCATION TECHNIQUES, INC. hapter 1 INTRODUTION SYS-ED/ OMPUTER EDUATION TEHNIQUES, IN. Objectives You will learn: Java features. Java and its associated components. Features of a Java application and applet. Java data types. Java

More information

Motivation for Dynamic Memory. Dynamic Memory Allocation. Stack Organization. Stack Discussion. Questions answered in this lecture:

Motivation for Dynamic Memory. Dynamic Memory Allocation. Stack Organization. Stack Discussion. Questions answered in this lecture: CS 537 Introduction to Operating Systems UNIVERSITY of WISCONSIN-MADISON Computer Sciences Department Dynamic Memory Allocation Questions answered in this lecture: When is a stack appropriate? When is

More information

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays C Arrays This handout was written by Nick Parlante and Julie Zelenski. As you recall, a C array is formed by laying out all the elements

More information

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2017 Lecture 7

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2017 Lecture 7 CS24: INTRODUCTION TO COMPUTING SYSTEMS Spring 2017 Lecture 7 LAST TIME Dynamic memory allocation and the heap: A run-time facility that satisfies multiple needs: Programs can use widely varying, possibly

More information

Garbage Collection (2) Advanced Operating Systems Lecture 9

Garbage Collection (2) Advanced Operating Systems Lecture 9 Garbage Collection (2) Advanced Operating Systems Lecture 9 Lecture Outline Garbage collection Generational algorithms Incremental algorithms Real-time garbage collection Practical factors 2 Object Lifetimes

More information

Name, Scope, and Binding. Outline [1]

Name, Scope, and Binding. Outline [1] Name, Scope, and Binding In Text: Chapter 3 Outline [1] Variable Binding Storage bindings and lifetime Type bindings Type Checking Scope Lifetime vs. Scope Referencing Environments N. Meng, S. Arthur 2

More information

Run-time Environments - 3

Run-time Environments - 3 Run-time Environments - 3 Y.N. Srikant Computer Science and Automation Indian Institute of Science Bangalore 560 012 NPTEL Course on Principles of Compiler Design Outline of the Lecture n What is run-time

More information

Memory Usage. Chapter 23

Memory Usage. Chapter 23 C23621721.fm Page 280 Wednesday, January 12, 2005 10:52 PM Chapter 23 Memory Usage The garbage collector is one of the most sophisticated pieces of the Microsoft.NET Framework architecture. Each time an

More information

CS61C : Machine Structures

CS61C : Machine Structures inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture 7 C Memory Management!!Lecturer SOE Dan Garcia!!!www.cs.berkeley.edu/~ddgarcia CS61C L07 More Memory Management (1)! 2010-02-03! Flexible

More information

Lecture Notes on Memory Management

Lecture Notes on Memory Management Lecture Notes on Memory Management 15-122: Principles of Imperative Computation Frank Pfenning Lecture 21 April 5, 2011 1 Introduction Unlike C0 and other modern languages like Java, C#, or ML, C requires

More information

Symbol Tables Symbol Table: In computer science, a symbol table is a data structure used by a language translator such as a compiler or interpreter, where each identifier in a program's source code is

More information

Ch. 11: References & the Copy-Constructor. - continued -

Ch. 11: References & the Copy-Constructor. - continued - Ch. 11: References & the Copy-Constructor - continued - const references When a reference is made const, it means that the object it refers cannot be changed through that reference - it may be changed

More information

CITS3211 FUNCTIONAL PROGRAMMING. 14. Graph reduction

CITS3211 FUNCTIONAL PROGRAMMING. 14. Graph reduction CITS3211 FUNCTIONAL PROGRAMMING 14. Graph reduction Summary: This lecture discusses graph reduction, which is the basis of the most common compilation technique for lazy functional languages. CITS3211

More information

Garbage Collection. Lecture Compilers SS Dr.-Ing. Ina Schaefer. Software Technology Group TU Kaiserslautern. Ina Schaefer Garbage Collection 1

Garbage Collection. Lecture Compilers SS Dr.-Ing. Ina Schaefer. Software Technology Group TU Kaiserslautern. Ina Schaefer Garbage Collection 1 Garbage Collection Lecture Compilers SS 2009 Dr.-Ing. Ina Schaefer Software Technology Group TU Kaiserslautern Ina Schaefer Garbage Collection 1 Content of Lecture 1. Introduction: Overview and Motivation

More information

Reference Counting. Reference counting: a way to know whether a record has other users

Reference Counting. Reference counting: a way to know whether a record has other users Garbage Collection Today: various garbage collection strategies; basic ideas: Allocate until we run out of space; then try to free stuff Invariant: only the PL implementation (runtime system) knows about

More information

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016 CS 31: Intro to Systems Pointers and Memory Martin Gagne Swarthmore College February 16, 2016 So we declared a pointer How do we make it point to something? 1. Assign it the address of an existing variable

More information

Run-time Environments -Part 3

Run-time Environments -Part 3 Run-time Environments -Part 3 Y.N. Srikant Computer Science and Automation Indian Institute of Science Bangalore 560 012 NPTEL Course on Compiler Design Outline of the Lecture Part 3 What is run-time support?

More information

Lecture 7 More Memory Management Slab Allocator. Slab Allocator

Lecture 7 More Memory Management Slab Allocator. Slab Allocator CS61C L07 More Memory Management (1) inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture 7 More Memory Management 2006-09-13 Lecturer SOE Dan Garcia www.cs.berkeley.edu/~ddgarcia Unbox problems

More information

Java Performance Tuning

Java Performance Tuning 443 North Clark St, Suite 350 Chicago, IL 60654 Phone: (312) 229-1727 Java Performance Tuning This white paper presents the basics of Java Performance Tuning and its preferred values for large deployments

More information

Dynamic Memory Management! Goals of this Lecture!

Dynamic Memory Management! Goals of this Lecture! Dynamic Memory Management!!! 1 Goals of this Lecture! Help you learn about:! Dynamic memory management techniques! Garbage collection by the run-time system (Java)! Manual deallocation by the programmer

More information