0% found this document useful (0 votes)
11 views

Code Gen 1

The document discusses two options for code generation: 1) Generate final code directly from the abstract syntax tree. 2) Generate intermediate code ("IR code") from the AST, then generate final code from the IR in a separate phase. The preferred option is to generate IR code first in order to make the compiler easier to retarget, break code generation into smaller tasks, and allow for machine-independent optimizations.

Uploaded by

sajadul.cse
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Code Gen 1

The document discusses two options for code generation: 1) Generate final code directly from the abstract syntax tree. 2) Generate intermediate code ("IR code") from the AST, then generate final code from the IR in a separate phase. The preferred option is to generate IR code first in order to make the compiler easier to retarget, break code generation into smaller tasks, and allow for machine-independent optimizations.

Uploaded by

sajadul.cse
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

CS-322 Code Generation-Part 1

Intermediate Code Generation


Given: Results of parsing...
•!Abstract Syntax Tree
•!Embed generation directly in parser
Option 1:
Generate Final Code Directly
• SPARC Assembler, or goto L3
•!Machine Code ...
L3: goto L7
Option 2:
Generate Intermediate Code (“IR code”) t1 := x + y
... Then generate final code t2 := t1
“Final Code Generation Phase”
Why?

© Harry H. Porter, 2006 1


CS-322 Code Generation-Part 1

Intermediate Code Generation


Given: Results of parsing...
•!Abstract Syntax Tree
•!Embed generation directly in parser
Option 1:
Generate Final Code Directly
• SPARC Assembler, or goto L3
•!Machine Code ...
L3: goto L7
Option 2:
Generate Intermediate Code (“IR code”) t1 := x + y
... Then generate final code t2 := t1
“Final Code Generation Phase”
Why?
•!Retargetting the compiler
Got a new CPU architecture? Replace Final Code Generator
•!Break code generation task into two smaller tasks
•!Optimization
“Machine Independent” Optimizations

© Harry H. Porter, 2006 2


CS-322 Code Generation-Part 1

Approach #1
Syntax-Directed Translations

E0 ! E1 + E2 E0.place := NewTemp ()
E0.code := E1.code || E2.code ||
IR (E0.place, ‘:=’, E1.place, ‘+’, E2.place)

CFG Rule
“IR” - A routine to create IR instructions

Attributes (Synthesized, Inherited)

Approach #2
We have parsed the program and built an in-memory representation
(Abstract Syntax Tree)
We will create methods to walk this AST and emit code

© Harry H. Porter, 2006 3


CS-322 Code Generation-Part 1

Intermediate Representation (Variations)


Source Code
a = b * -c + b * -c;
Closer to SPARC code
Three-Address Code:
Each instruction has (up to) 3 operands.
t1 := -c neg c " t1
t2 := b * t1 mult b,t1 " t2
t3 := -c neg c " t3
t4 := b * t3 mult b,t3 " t4
t5 := t2 + t4 add t2,t4 " t5
a := t5 move t5 " a
Tree Representations: := Similar to the AST we already have.
(Temporaries are ignored, here)
a +

* *

b Unary- b Unary-

© Harry H. Porter, 2006


c c
4
CS-322 Code Generation-Part 1

Graphical Representations
Tree: := DAG: :=

a +
a +

* * *

b Unary- b Unary- b Unary-

c c c

© Harry H. Porter, 2006 5


CS-322 Code Generation-Part 1

Graphical Representations
Tree: := DAG: :=

a +
a +

* * *

b Unary- b Unary- b Unary-

c c c
0 id b -
Structures and Pointers
Minus 1 id c -
2 unary- 1 -
3 mult 0 2
4 id b -
An array of fixed-sized records 5 id c -
Q: How to build DAG’s (i.e., trees with 6 unary- 5 -
shared, common parts)? 7 mult 4 6
8 add 3 7
A: When you are about to allocate a
9 id a -
new node; look to see if you already
10 assign 9 8
have one with the same info.
© Harry H. Porter, 2006 6
CS-322 Code Generation-Part 1

Three-Address Instructions
Idea:
One operation
Three “addresses” (fields, args), at most
Two operands
One result
(Some instructions have only 0, 1, or 2 addresses)
Much closer to machine language
Notation used in Textbook
Examples:
t1 := -c neg c " t1
t2 := b * t1 mult b,t1 " t2
t3 := -c neg c " t3
t4 := b * t3 mult b,t3 " t4
t5 := t2 + t4 add t2,t4 " t5
a := t5 move t5 " a
•!Looks like source code, but...
•!NOTE: Lots of temp variables
Tend to create many
Will try to eliminate during optimization

© Harry H. Porter, 2006 7


CS-322 Code Generation-Part 1

Source:
a = (b * -c) + (b * -c);

Translation #1:
t1 := -c
t2 := b * t1
t3 := -c
t4 := b * t3
t5 := t2 + t4
a := t5
The shared sub-expression
Translation #2: is computed only once
t1 := -c
t2 := b * t1
t5 := t2 + t2
a := t5

© Harry H. Porter, 2006 8


CS-322 Code Generation-Part 1

Types of Three-Address Instructions


Binary Operations Notational Variations
x := y + z x := y + z (int)
x := y * z x := y + z (float)
...etc...
x := y +i z
Want different instructions for x := y +f z
•!Integer
x := iadd(y,z)
•!Floating-point x := fadd(y,z)
iadd y,z " x
fadd y,z " x
Unary Operations
x := -y Notational Variations
x := IntToReal(y)
x := -y (int)
x := -i y
Assignment / Move x := ineg(y)
x := y
ineg y " x

© Harry H. Porter, 2006 9


CS-322 Code Generation-Part 1

Jump / Goto / Unconditional Branch


goto Lab_58 Lab_43:
x := y + 3
Label
z := x * 2
Lab_43:
if z > w then goto Lab_43
A place holder
Strictly for labeling the target of a branch
Acts like a nop
Labels are simple strings Function “NewLabel()”
(Assembler/Linker will assign addresses) returns....
“Lab_1”
Conditional Jumps / Branches “Lab_2”
if x < y then goto Lab_57 “Lab_3”
...
Conditions: <, <=, >, >=, =, !=
Data Types: integer, floating
if x < y then... (int) gotoiLT
if x <= y then... (int) gotoiLE
...
if x < y then... (float) gotofLT
if x <= y then... (float) gotofLE
...

© Harry H. Porter, 2006 10


CS-322 Code Generation-Part 1

Procedure / Function Calls


param x ld ...,%o0
param y ld ...,%o1
call foo call foo
result x nop
Array Accessing st %o0,...
x := y[i]
x[i] := y
Address / Pointer Manipulation
x := &y Load address
x := *y Load indirect
*x := y Store indirect

You can design the exact instruction set in any way that facilitates compilation.
But you must be careful to be clear and precise about the IR instructions’ meanings.
More IR instructions " Easier to compile to.
...but more work during final code generation
Fewer IR instructions " < Reverse >

© Harry H. Porter, 2006 11


CS-322 Code Generation-Part 1

Representing 3-Address Statements


•!Quadruples (“Quads”)
• Triples t0 := x + y
•!Indirect Triples t1 := t0 * z
a := t1
Quadruples
Store each field directly

... In an array: ... In a linked list:


0 + t1 x y + t0 x y
1 * t2 t1 z
2 := a t2 -
3 * t1 t0 z

:= a t1 -

Less Space Easier to re-order

© Harry H. Porter, 2006 12


CS-322 Code Generation-Part 1

Triples
Don’t store the result directly.
Implicitly associate a temporary result with each triple.
t0 := x + y :=
t1 := t0 * z
a := t1 a *
Avoids creating the temporaries.
Saves storage. + z
Difficult to re-order instructions.
0 + x y
x y
1 * 0 z
2 := a 1
3

The following instruction is difficult


x[i] := y
It takes 2 triples.

© Harry H. Porter, 2006 13


CS-322 Code Generation-Part 1

Indirect Triples
Get around the re-ordering problem
... by introducing another data structure.

0: 100 100: + x y
1: 101 101: * 100 z
2: 102 102: := a 101
3: 103 103: := b w

Quadruples
Less indirection, simpler
Easier to manipulate, reorder
Triples
Indirect Triples
About same amount of space as quadruples
May save space when lots of shared sub-expressions
More complex

© Harry H. Porter, 2006 14


CS-322 Code Generation-Part 1

Indirect Triples
Get around the re-ordering problem
... by introducing another data structure.

0: 100 100: + x y
1: 101 101: * 100 z
2: 103 102: := a 101
3: 102 103: := b w

Quadruples
Less indirection, simpler
Easier to manipulate, reorder
Triples
Indirect Triples
About same amount of space as quadruples
May save space when lots of shared sub-expressions
More complex

© Harry H. Porter, 2006 15


CS-322 Code Generation-Part 1

Translating Expressions
Idea: Use Syntax-directed translations
For each expression, we’ll synthesize two attributes:
E.code
This is the code we will generate for expression E.
(It is a sequence of all the IR instructions in the translation.)
When executed (at runtime), these instructions will compute the
value of the expression and place the value into some variable.
E.place
The name of the variable (often a temporary variable)
into which this code will move the final result value when executed.
For each statement, we will synthesize one attribute:
S.code
The IR code for this source statement.

Call “NewTemp” to create a new temporary variable


t = NewTemp();
Call “IR” to create a new 3-address instruction
IR (t, “:=”, x, “+”, y) " “t := x + y”

© Harry H. Porter, 2006 16


CS-322 Code Generation-Part 1

Goal
Take a source statement and produce a sequence of IR quads:

Example:
x := y + z;
IR Quads:
t1 := y + z
x := t1

Example:
x := (y + z) * (u + v);
IR Quads:
t1 := y + z
t2 := u + v
t3 := t1 * t2
x := t3

© Harry H. Porter, 2006 17


CS-322 Code Generation-Part 1

Synthesized Code and Place Attributes


Consider S Example:
E0 ! E1 + E2 code=
x := y + z;

Work bottom-up.
ID E0
sval=“x” code=
Assume we already have place=
E1.place = “y”
E1.code = “ ”
E2.place = “z” E1 + E2
E2.code = “ ” code= code=
place= place=

Then, use the rules to compute


E0.place
E0.code ID ID
sval=“y” sval=“z”

© Harry H. Porter, 2006 18


CS-322 Code Generation-Part 1

E0 ! E1 + E2 E0.place := NewTemp ()
E0.code := E1.code || E2.code ||
IR (E0.place, ‘:=’, E1.place, ‘+’, E2.place)

Assume we already have


E1.place = “y”
E1.code = “ ”
E2.place = “z”
E2.code = “ ”

Then, use the rules to compute


E0.place = “t1”
E0.code = “t1 := y + z”

© Harry H. Porter, 2006 19


CS-322 Code Generation-Part 1

E0 ! E1 + E2 E0.place := NewTemp ()
E0.code := E1.code || E2.code ||
IR (E0.place, ‘:=’, E1.place, ‘+’, E2.place)

E0 ! E1 * E2 E0.place := NewTemp ()
E0.code := E1.code || E2.code ||
IR (E0.place, ‘:=’, E1.place, ‘*’, E2.place)

E0 ! ID E0.place := ID.svalue
E0.code := “ ”

E0 ! - E 1 E0.place := NewTemp ()
E0.code := E1.code || IR (E0.place, ‘:=’, ‘-’, E1.place)

E0 ! ( E 1 ) E0.place := E1.place
E0.code := E1.code

S ! ID := E ; S.code := E.code || IR (ID.svalue, ‘:=’, E.place)

© Harry H. Porter, 2006 20


CS-322 Code Generation-Part 1

Generating if E then S1 else S2 endIf


Code for <code for E>
“IF” Statement if E.place = 0 goto Label_Else
<code for S1>
goto Label_End
Label_Else:
<code for S2>
Label_End:

© Harry H. Porter, 2006 21


CS-322 Code Generation-Part 1

Generating if E then S1 else S2 endIf


Code for <code for E>
“IF” Statement if E.place = 0 goto Label_Else
<code for S1>
goto Label_End
Label_Else:
<code for S2>
Label_End:

S0 ! if E then S1 else S2 endIf


label_else = NewLabel ()
label_end = NewLabel ()
S0.code := E.code ||
IR ( ‘if’, E.place, ‘=0 goto ’, label_else) ||
S1.code ||
IR (‘goto’, label_end) ||
IR (label_else, ‘:’) ||
S2.code ||
IR (label_end, ‘:’)
© Harry H. Porter, 2006 22
CS-322 Code Generation-Part 1

Compile-Time vs. Run-Time

“Static” versus “Dynamic”


Source Text (“Syntactic”, “Lexical”)
procedure foo (...) is begin ... end;
Only 1 static (compile-time) copy of “foo”

Run-time Activations
At any moment at runtime, “foo” may have
•!Zero activations
• One activations
• Many activations (if “foo” is recursive)

© Harry H. Porter, 2006 23


CS-322 Code Generation-Part 1

Standard Terminology

“Routine”
“Procedure” - Returns no result
“Function” - Returns a result

Other Terminology

“Procedures” - may or may not return a result (PCAT)


“Void-Procedure”
“Non-void Procedure”

“Functions” - may or may not return a result (C)


“Void-Function”
“Non-void Function”

© Harry H. Porter, 2006 24


CS-322 Code Generation-Part 1

Terminology
Static
A routine is called a a place in the program
e.g., “quicksort” is called on lines 16, 17, and 23
“formal parameters” Like variables
“actual arguments” Expressions (which yield a value when executed)

Runtime
When a routine is called, it is a new “activation” (or “invocation”)
The routine is “invoked”.
The “lifetime of an activation”
From the moment of invocation to the moment of return

The “Caller”
The “Callee” (the “called” routine)

Static:
“quicksort” calls “partition” on line 12.
Dynamic:
This activation of quicksort calls quicksort with arguments 4 and 7.

© Harry H. Porter, 2006 25


CS-322 Code Generation-Part 1

Nested Activations
At runtime...
Assume p calls f
Then: f must return before p returns
Assumptions:
•!Single thread of control
• No errors / exceptions
• No suspended closures
•!No gotos.

Call and Return are like nested parentheses


(( (() (()()) ()) ( () ) ) () () )

Add print statements to routines


procedure foo ()
print (“foo entered”);
...
print (“foo returns”);
return;

© Harry H. Porter, 2006 26


CS-322 Code Generation-Part 1

Recursion
Recursive routines
foo entered
foo entered “Calling Graph”
foo entered for a program
...
foo returns quicksort
foo returns
foo returns calls
foo
Mutually recursive routines (“Indirectly recursive”)
calls
foo entered calls
bar entered
goo entered bar
goo calls
foo entered calls
...
foo returns myFunct
goo returns
bar returns
foo returns

© Harry H. Porter, 2006 27


CS-322 Code Generation-Part 1
The Quicksort Program
program is
var a: array of integer := ...;
procedure readArray () is
var i: integer := 0;
begin
for i := 1 to 9 do read ( a[i] ); end;
end;
procedure partition (y, z: integer): integer is
var i,j,x,v: integer := 0;
begin ... end;
procedure quicksort (m, n: integer) is
var i: integer := 0;
begin
if n>m then
i := partition (m, n);
quicksort (m, i-1); This code is in
quicksort (i+1, n);
end; examples/sort.pcat
end;
begin
a[0] := -9999;
a[10] := 9999;
readArray ();
quicksort (1,9);
end;
© Harry H. Porter, 2006 28
CS-322 Code Generation-Part 1

The Activation Tree


Shows the entire calling history of a run of the program
main Actual args can be shown

readarray qs(1,9)

partition(1,9) qs(1,3) qs(5,9)

Time
partition(1,3) qs(1,0) qs(2,3)

partition(5,9) qs(5,5) qs(7,9)

partition(2,3) qs(2,1) qs(3,3)

partition(7,9) qs(7,7) qs(9,9)


At any one instant...
A path from the root to a node
shows the current “activation stack”

© Harry H. Porter, 2006 29


CS-322 Code Generation-Part 1

The Activation Tree


Shows the entire calling history of a run of the program
main Actual args can be shown

readarray qs(1,9)

partition(1,9) qs(1,3) qs(5,9)

Time
partition(1,3) qs(1,0) qs(2,3)

partition(5,9) qs(5,5) qs(7,9)

partition(2,3) qs(2,1) qs(3,3)

partition(7,9) qs(7,7) qs(9,9)


At any one instant...
A path from the root to a node
shows the current “activation stack”

© Harry H. Porter, 2006 30


CS-322 Code Generation-Part 1 Also called:
Control Stack
Activation Stack Runtime Stack
Frame Stack

main main main main main


••• •••
readArray qs(1,9) qs(1,9) qs(1,9)

qs(1,3) qs(1,3) qs(1,3)

qs(2,3) qs(2,3) qs(2,3)

partition(2,3) qs(2,1)

Time

TOP
part(2,3) qs(2,1)
••• qs(2,3) qs(2,3) qs(2,3) •••
frames qs(1,3) qs(1,3) qs(1,3)
readArray qs(1,9) qs(1,9) qs(1,9)
main main main main main
© Harry H. Porter, 2006 31
CS-322 Code Generation-Part 1

Each live routine has an activation record (a “frame”) on the stack

Enter a new routine?


•!PUSH a frame onto the stack

Return from a routine?


•!POP the top frame

Want to access the local variables of the current routine?


• Find them in the frame on the TOP of the stack.

© Harry H. Porter, 2006 32


CS-322 Code Generation-Part 1

Declarations
There may be several declarations for some variable name,
procedure foo (...) is
var i: integer := ...;
procedure bar (...) is
var i: integer := ...;
begin ... end;
begin ... end;
“Scope Rules”
The scope of a declaration
The part of the program (static) where we can use the declared name.
“Local” VarDecl
“Non-Local”
Symbol Table
Match variable uses to declarations
var x: ...
... Variable
... x ...
myDef

© Harry H. Porter, 2006 33


CS-322 Code Generation-Part 1

Binding of Names

“environment” “state”
name storage value

Done Statically
Done Dynamically

L-Values
R-Values

Assignments change state.


Declarations change the environment.

Some languages allow the environment


to be changed dynamically!

© Harry H. Porter, 2006 34


CS-322 Code Generation-Part 1

Memory
.text segment
will be read-only
code (includkng library routines) misc.
fixed (constant) data
.asciz strings .text

.data segment .data


read/write
used to hold (global) data heap
“display registers” HeapTop

.bss segment unused


read/write
all bytes initialized to zero StackTop
(we won’t use)
stack

© Harry H. Porter, 2006 35


CS-322 Code Generation-Part 1

Dangling References
“A pointer to storage that has been freed / deallocated”

p := new (...) main () {


... int *p;
delete p; p = foo();
... ... p ...
...p... }
Consequences? int * foo () {
int i = 123;
•!Clobber random memory locations return &i;
Weird program behavior }
•!Read / write the wrong data
Normal program behavior, but incorrect results
• Caught by the runtime system
Catastrophic crash (core dump)
Graceful failure w/ message
•!No affect; program functions correctly
Is the program still wrong?

© Harry H. Porter, 2006 36


CS-322 Code Generation-Part 1

Dangling References

Problem:
The programmer explicitly frees / deallocates data
...but the programmer frees data “too soon”.

Solution:
Don’t let programmer free data!

Problem:
The program uses more memory than necessary.

Solution:
The runtime system identifies objects that
cannot possibly be used again by the program
“Garbage” objects
The runtime system reclaims this space
The “Garbage Collector”

© Harry H. Porter, 2006 37


CS-322 Code Generation-Part 1

The Heap
Simplest Organization
Allocate space at the end (top) of the heap
Abort when “StackTop < HeapTop”
Never free / release space

Explicit Freeing of Space


malloc / calloc / free in “C”
Object creation / deletion in “C++”
Keep a list of free chunks of memory (“free list”)
e.g., Linked list of memory areas
“Free” adds memory to this list
To allocate memory...
First check the free list
If possible, use the free list
Otherwise, grow the heap
NEVER MOVE ALLOCATED CHUNKS OF MEMORY
Program relies on pointers remaining valid. (“C”, “C++”)

© Harry H. Porter, 2006 38


CS-322 Code Generation-Part 1

Automatic Garbage Collection


Java, Smalltalk, Haskell, Lisp, ...
Memory Management Subsystem (“Heap Manager”)
Program periodically asks for memory (allocates objects)
Memory manager returns (a pointer to) a new chunk of space
Space running low?
Memory manager identifies objects that are no longer in use
“garbage”
Object is reachable? Not garbage
Object is unreachable? Garbage
Reclaims space used by garbage objects
Fragmentation?
Move objects around (“compaction”)
To make large chunks of memory available
Memory manager must re-adjust pointers when objects are moved.
Memory manager must be able to identify all pointers at runtime.
Tight coupling with the language implementation
The program doesn’t know objects have been moved!!!

© Harry H. Porter, 2006 39


CS-322 Code Generation-Part 1

Garbage
Memory is organized into “objects” which point to each other.
Objects are allocated at random during program execution.
Some objects are “reachable” from the program variables.
All other objects are considered to be garbage.

w:
x:
y:
z:

Stack a:
Frames b:
i:
j:

••
• The Heap of Objects

© Harry H. Porter, 2006 40


CS-322 Code Generation-Part 1

Garbage
Memory is organized into “objects” which point to each other.
Objects are allocated at random during program execution.
Some objects are “reachable” from the program variables.
All other objects are considered to be garbage.

w:
x:
y:
z:

Stack a:
Frames b:
i:
j:

••
• The Heap of Objects

© Harry H. Porter, 2006 41


CS-322 Code Generation-Part 1

Garbage
Memory is organized into “objects” which point to each other.
Objects are allocated at random during program execution.
Some objects are “reachable” from the program variables.
All other objects are considered to be garbage.

w:
x:
y:
z:

Stack a:
Frames b:
i:
j:

••
• The Heap of Objects

© Harry H. Porter, 2006 42


CS-322 Code Generation-Part 1

Fragmentation The Heap


Variable-sized chunks of memory are allocated.
Some chunks are freed (in more-or-less random order).
The resulting free space become “fragmented”.
Need to allocate more space?
Adequate space is available
... but it is not contiguous!

© Harry H. Porter, 2006 43


CS-322 Code Generation-Part 1

Fragmentation The Heap


Variable-sized chunks of memory are allocated.
Some chunks are freed (in more-or-less random order).
The resulting free space become “fragmented”.
Need to allocate more space?
Adequate space is available
... but it is not contiguous!

Several objects are freed.

© Harry H. Porter, 2006 44


CS-322 Code Generation-Part 1

Fragmentation The Heap


Variable-sized chunks of memory are allocated.
Some chunks are freed (in more-or-less random order).
The resulting free space become “fragmented”.
Need to allocate more space?
Adequate space is available
... but it is not contiguous!

Want to allocate this object:

© Harry H. Porter, 2006 45


CS-322 Code Generation-Part 1

Fragmentation The Heap


Variable-sized chunks of memory are allocated.
Some chunks are freed (in more-or-less random order).
The resulting free space become “fragmented”.
Need to allocate more space?
Adequate space is available
... but it is not contiguous!

© Harry H. Porter, 2006 46


CS-322 Code Generation-Part 1

Fragmentation The Heap


Variable-sized chunks of memory are allocated.
Some chunks are freed (in more-or-less random order).
The resulting free space become “fragmented”.
Need to allocate more space?
Adequate space is available
... but it is not contiguous!

Want to allocate this object:

© Harry H. Porter, 2006 47


CS-322 Code Generation-Part 1

Fragmentation The Heap


Variable-sized chunks of memory are allocated.
Some chunks are freed (in more-or-less random order).
The resulting free space become “fragmented”.
Need to allocate more space?
Adequate space is available
... but it is not contiguous!

Want to allocate this object:

“Compact” Memory!

© Harry H. Porter, 2006 48


CS-322 Code Generation-Part 1

Fragmentation The Heap The Heap


Variable-sized chunks of memory are allocated.
Some chunks are freed (in more-or-less random order).
The resulting free space become “fragmented”.
Need to allocate more space?
Adequate space is available
... but it is not contiguous!

Want to allocate this object:

“Compact” Memory!

© Harry H. Porter, 2006 49


CS-322 Code Generation-Part 1

Fragmentation The Heap


Variable-sized chunks of memory are allocated.
Some chunks are freed (in more-or-less random order).
The resulting free space become “fragmented”.
Need to allocate more space?
Adequate space is available
... but it is not contiguous!

Want to allocate this object:

“Compact” Memory!

© Harry H. Porter, 2006 50


CS-322 Code Generation-Part 1

Fragmentation The Heap


Variable-sized chunks of memory are allocated.
Some chunks are freed (in more-or-less random order).
The resulting free space become “fragmented”.
Need to allocate more space?
Adequate space is available
... but it is not contiguous!

© Harry H. Porter, 2006 51


CS-322 Code Generation-Part 1

Pointer Problems
The program frees memory “too soon”.
Dangling references
Program crashes
Program accesses/overwrites other data
Incorrect / weird behavior

The program fails to free unused memory.


The program frees memory “too late”.
The program slowly eats up memory.
Finally, the program runs out of memory.
“memory exhausted” error
A Debugging Nightmare
Happens with long running programs
Difficult to replicate the bug
Where exactly is the “error”
Errors of omissions are hard to localize!

© Harry H. Porter, 2006 52


CS-322 Code Generation-Part 1

Pointer Problems
Automatic Garbage Collection
Dangling references no longer possible.
Freeing memory...
The Garbage Collector is conservative.
May fail to collect some garbage.
What if this object is
never used again?
(Ought to collect it!)
w:
x:
y:
z:

Stack of
Frames

••
• The Heap of Objects

© Harry H. Porter, 2006 53


CS-322 Code Generation-Part 1

Pointer Problems
Automatic Garbage Collection
Dangling references no longer possible.
Freeing memory... Set this field to NULL,
The Garbage Collector is conservative. so the collector will
May fail to collect some garbage. identifiy the object
as garbage

w:
x: NULL
y:
z:

Stack of
Frames

••
• The Heap of Objects

© Harry H. Porter, 2006 54

You might also like