CSc 520 - Principles of Programming Languages
8 : Memory Management -- GC -- Mark and Sweep

Christian Collberg

Department of Computer Science

University of Arizona


Garbage Collection Issues


1 Finding the Object Graph

Finding the roots:
The dynamic objects in a program form a graph. Most GC algorithms need to traverse this graph. The roots of the graph can be in
  1. global variables
  2. registers
  3. local variables/formal parameters on the stack.
Hence, the compiler must communicate to the GC which registers/variables contain roots.

2 Finding the Object Graph...

Finding internal pointers:
Structured variables (arrays, records, objects) may contain internal pointers. These must be known to the GC so that it can traverse the graph. Hence, the compiler must communicate to the GC the type of each dynamic object and the internal structure of each type.
Finding the beginning of objects:
What happens if the only pointer to an object points somewhere in the middle of the object? We must either be able to find the beginning of the object, or make sure the compiler does not generate such code.

3 Finding the Object Graph...

garbage1

4 Pointer Maps

5 Pointer Maps...

6 Pointer Maps...


The Mark-and-Sweep Algorithm


7 Algorithm: Mark and Sweep

8 Algorithm: Mark and Sweep...

9 Algorithm: Mark and Sweep...

Marking Phase:
  1. Mark all objects unmarked.
  2. Find all roots, i.e. heap pointers in stack, regs & globals.
  3. Mark reachable blocks using a depth first search starting at the roots.
    1. DFS may run out of stack space!
    2. Use non-recursive (Deutsch-Schorr-Waite) DFS.
Scanning Phase:
same-size-cells
Scan heap and put un-marked (non-reachable) cells back on free-list.
different-size-cells
Compact the heap to prevent fragmentation.

10 Marking Phase

11 Marking Phase...

12 Marking: ``Look Ma, No Stack!''

garbage2

13 Marking: ``Look Ma, No Stack!''...




14 Marking: ``Look Ma, No Stack!''...

PointerReversal1

15 Marking: ``Look Ma, No Stack!''...

PointerReversal2

16 Where do the markbits go???

Template

17 Where do the markbits go...

18 Sweeping: Compaction

garbage3

  1. Calculate the forwarding address of each cell.
  2. Store the forwarding address of cell in .
  3. If points to cell , replace with .
  4. Move all cells to their forwarding addresses.


Cost of Garbage Collection


19 Cost of Garbage Collection

GCCost1


20 Cost of GC -- Mark-and-Sweep

GCCost1



21 Cost of GC -- Mark-and-Sweep...

GCCostHeqR



22 Readings and References



Christian Collberg 2008-02-06