Remove RLE from the headers, since the pass itself is gone now.
[oota-llvm.git] / docs / GarbageCollection.html
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
2                       "http://www.w3.org/TR/html4/strict.dtd">
3 <html>
4 <head>
5   <title>Accurate Garbage Collection with LLVM</title>
6   <link rel="stylesheet" href="llvm.css" type="text/css">
7 </head>
8 <body>
9
10 <div class="doc_title">
11   Accurate Garbage Collection with LLVM
12 </div>
13
14 <ol>
15   <li><a href="#introduction">Introduction</a>
16     <ul>
17     <li><a href="#feature">GC features provided and algorithms supported</a></li>
18     </ul>
19   </li>
20
21   <li><a href="#interfaces">Interfaces for user programs</a>
22     <ul>
23     <li><a href="#roots">Identifying GC roots on the stack: <tt>llvm.gcroot</tt></a></li>
24     <li><a href="#allocate">Allocating memory from the GC</a></li>
25     <li><a href="#barriers">Reading and writing references to the heap</a></li>
26     <li><a href="#explicit">Explicit invocation of the garbage collector</a></li>
27     </ul>
28   </li>
29
30   <li><a href="#gcimpl">Implementing a garbage collector</a>
31     <ul>
32     <li><a href="#llvm_gc_readwrite">Implementing <tt>llvm_gc_read</tt> and <tt>llvm_gc_write</tt></a></li>
33     <li><a href="#callbacks">Callback functions used to implement the garbage collector</a></li>
34     </ul>
35   </li>
36   <li><a href="#gcimpls">GC implementations available</a>
37     <ul>
38     <li><a href="#semispace">SemiSpace - A simple copying garbage collector</a></li>
39     </ul>
40   </li>
41
42 <!--
43   <li><a href="#codegen">Implementing GC support in a code generator</a></li>
44 -->
45 </ol>
46
47 <div class="doc_author">
48   <p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a></p>
49 </div>
50
51 <!-- *********************************************************************** -->
52 <div class="doc_section">
53   <a name="introduction">Introduction</a>
54 </div>
55 <!-- *********************************************************************** -->
56
57 <div class="doc_text">
58
59 <p>Garbage collection is a widely used technique that frees the programmer from
60 having to know the life-times of heap objects, making software easier to produce
61 and maintain.  Many programming languages rely on garbage collection for
62 automatic memory management.  There are two primary forms of garbage collection:
63 conservative and accurate.</p>
64
65 <p>Conservative garbage collection often does not require any special support
66 from either the language or the compiler: it can handle non-type-safe
67 programming languages (such as C/C++) and does not require any special
68 information from the compiler.  The
69 <a href="http://www.hpl.hp.com/personal/Hans_Boehm/gc/">Boehm collector</a> is
70 an example of a state-of-the-art conservative collector.</p>
71
72 <p>Accurate garbage collection requires the ability to identify all pointers in
73 the program at run-time (which requires that the source-language be type-safe in
74 most cases).  Identifying pointers at run-time requires compiler support to
75 locate all places that hold live pointer variables at run-time, including the
76 <a href="#roots">processor stack and registers</a>.</p>
77
78 <p>
79 Conservative garbage collection is attractive because it does not require any
80 special compiler support, but it does have problems.  In particular, because the
81 conservative garbage collector cannot <i>know</i> that a particular word in the
82 machine is a pointer, it cannot move live objects in the heap (preventing the
83 use of compacting and generational GC algorithms) and it can occasionally suffer
84 from memory leaks due to integer values that happen to point to objects in the
85 program.  In addition, some aggressive compiler transformations can break
86 conservative garbage collectors (though these seem rare in practice).
87 </p>
88
89 <p>
90 Accurate garbage collectors do not suffer from any of these problems, but they
91 can suffer from degraded scalar optimization of the program.  In particular,
92 because the runtime must be able to identify and update all pointers active in
93 the program, some optimizations are less effective.  In practice, however, the
94 locality and performance benefits of using aggressive garbage allocation
95 techniques dominates any low-level losses.
96 </p>
97
98 <p>
99 This document describes the mechanisms and interfaces provided by LLVM to
100 support accurate garbage collection.
101 </p>
102
103 </div>
104
105 <!-- ======================================================================= -->
106 <div class="doc_subsection">
107   <a name="feature">GC features provided and algorithms supported</a>
108 </div>
109
110 <div class="doc_text">
111
112 <p>
113 LLVM provides support for a broad class of garbage collection algorithms,
114 including compacting semi-space collectors, mark-sweep collectors, generational
115 collectors, and even reference counting implementations.  It includes support
116 for <a href="#barriers">read and write barriers</a>, and associating <a
117 href="#roots">meta-data with stack objects</a> (used for tagless garbage
118 collection).  All LLVM code generators support garbage collection, including the
119 C backend.
120 </p>
121
122 <p>
123 We hope that the primitive support built into LLVM is sufficient to support a
124 broad class of garbage collected languages, including Scheme, ML, scripting
125 languages, Java, C#, etc.  That said, the implemented garbage collectors may
126 need to be extended to support language-specific features such as finalization,
127 weak references, or other features.  As these needs are identified and
128 implemented, they should be added to this specification.
129 </p>
130
131 <p>
132 LLVM does not currently support garbage collection of multi-threaded programs or
133 GC-safe points other than function calls, but these will be added in the future
134 as there is interest.
135 </p>
136
137 </div>
138
139 <!-- *********************************************************************** -->
140 <div class="doc_section">
141   <a name="interfaces">Interfaces for user programs</a>
142 </div>
143 <!-- *********************************************************************** -->
144
145 <div class="doc_text">
146
147 <p>This section describes the interfaces provided by LLVM and by the garbage
148 collector run-time that should be used by user programs.  As such, this is the
149 interface that front-end authors should generate code for.
150 </p>
151
152 </div>
153
154 <!-- ======================================================================= -->
155 <div class="doc_subsection">
156   <a name="roots">Identifying GC roots on the stack: <tt>llvm.gcroot</tt></a>
157 </div>
158
159 <div class="doc_text">
160
161 <div class="doc_code"><tt>
162   void %llvm.gcroot(&lt;ty&gt;** %ptrloc, &lt;ty2&gt;* %metadata)
163 </tt></div>
164
165 <p>
166 The <tt>llvm.gcroot</tt> intrinsic is used to inform LLVM of a pointer variable
167 on the stack.  The first argument contains the address of the variable on the
168 stack, and the second contains a pointer to metadata that should be associated
169 with the pointer (which <b>must</b> be a constant or global value address).</p>
170
171 <p>
172 Consider the following fragment of Java code:
173 </p>
174
175 <pre>
176        {
177          Object X;   // A null-initialized reference to an object
178          ...
179        }
180 </pre>
181
182 <p>
183 This block (which may be located in the middle of a function or in a loop nest),
184 could be compiled to this LLVM code:
185 </p>
186
187 <pre>
188 Entry:
189    ;; In the entry block for the function, allocate the
190    ;; stack space for X, which is an LLVM pointer.
191    %X = alloca %Object*
192    ...
193
194    ;; Java null-initializes pointers.
195    store %Object* null, %Object** %X
196
197    ;; "CodeBlock" is the block corresponding to the start
198    ;;  of the scope above.
199 CodeBlock:
200    ;; Initialize the object, telling LLVM that it is now live.
201    ;; Java has type-tags on objects, so it doesn't need any
202    ;; metadata.
203    call void %llvm.gcroot(%Object** %X, sbyte* null)
204    ...
205
206    ;; As the pointer goes out of scope, store a null value into
207    ;; it, to indicate that the value is no longer live.
208    store %Object* null, %Object** %X
209    ...
210 </pre>
211
212 </div>
213
214 <!-- ======================================================================= -->
215 <div class="doc_subsection">
216   <a name="allocate">Allocating memory from the GC</a>
217 </div>
218
219 <div class="doc_text">
220
221 <div class="doc_code"><tt>
222   sbyte *%llvm_gc_allocate(unsigned %Size)
223 </tt></div>
224
225 <p>The <tt>llvm_gc_allocate</tt> function is a global function defined by the
226 garbage collector implementation to allocate memory.  It returns a
227 zeroed-out block of memory of the appropriate size.</p>
228
229 </div>
230
231 <!-- ======================================================================= -->
232 <div class="doc_subsection">
233   <a name="barriers">Reading and writing references to the heap</a>
234 </div>
235
236 <div class="doc_text">
237
238 <div class="doc_code"><tt>
239   sbyte *%llvm.gcread(sbyte *, sbyte **)<br>
240   void %llvm.gcwrite(sbyte*, sbyte*, sbyte**)
241 </tt></div>
242
243 <p>Several of the more interesting garbage collectors (e.g., generational
244 collectors) need to be informed when the mutator (the program that needs garbage
245 collection) reads or writes object references into the heap.  In the case of a
246 generational collector, it needs to keep track of which "old" generation objects
247 have references stored into them.  The amount of code that typically needs to be
248 executed is usually quite small (and not on the critical path of any 
249 computation), so the overall performance impact of the inserted code is 
250 tolerable.</p>
251
252 <p>To support garbage collectors that use read or write barriers, LLVM provides
253 the <tt>llvm.gcread</tt> and <tt>llvm.gcwrite</tt> intrinsics.  The first
254 intrinsic has exactly the same semantics as a non-volatile LLVM load and the
255 second has the same semantics as a non-volatile LLVM store, with the
256 additions that they also take a pointer to the start of the memory
257 object as an argument.  At code generation
258 time, these intrinsics are replaced with calls into the garbage collector
259 (<tt><a href="#llvm_gc_readwrite">llvm_gc_read</a></tt> and <tt><a
260 href="#llvm_gc_readwrite">llvm_gc_write</a></tt> respectively), which are then
261 inlined into the code.
262 </p>
263
264 <p>
265 If you are writing a front-end for a garbage collected language, every load or
266 store of a reference from or to the heap should use these intrinsics instead of
267 normal LLVM loads/stores.</p>
268
269 </div>
270
271 <!-- ======================================================================= -->
272 <div class="doc_subsection">
273   <a name="initialize">Garbage collector startup and initialization</a>
274 </div>
275
276 <div class="doc_text">
277
278 <div class="doc_code"><tt>
279   void %llvm_gc_initialize(unsigned %InitialHeapSize)
280 </tt></div>
281
282 <p>
283 The <tt>llvm_gc_initialize</tt> function should be called once before any other
284 garbage collection functions are called.  This gives the garbage collector the
285 chance to initialize itself and allocate the heap spaces.  The initial heap size
286 to allocate should be specified as an argument.
287 </p>
288
289 </div>
290
291 <!-- ======================================================================= -->
292 <div class="doc_subsection">
293   <a name="explicit">Explicit invocation of the garbage collector</a>
294 </div>
295
296 <div class="doc_text">
297
298 <div class="doc_code"><tt>
299   void %llvm_gc_collect()
300 </tt></div>
301
302 <p>
303 The <tt>llvm_gc_collect</tt> function is exported by the garbage collector
304 implementations to provide a full collection, even when the heap is not
305 exhausted.  This can be used by end-user code as a hint, and may be ignored by
306 the garbage collector.
307 </p>
308
309 </div>
310
311
312 <!-- *********************************************************************** -->
313 <div class="doc_section">
314   <a name="gcimpl">Implementing a garbage collector</a>
315 </div>
316 <!-- *********************************************************************** -->
317
318 <div class="doc_text">
319
320 <p>
321 Implementing a garbage collector for LLVM is fairly straight-forward.  The LLVM
322 garbage collectors are provided in a form that makes them easy to link into the
323 language-specific runtime that a language front-end would use.  They require
324 functionality from the language-specific runtime to get information about <a
325 href="#gcdescriptors">where pointers are located in heap objects</a>.
326 </p>
327
328 <p>The
329 implementation must include the <a
330 href="#allocate"><tt>llvm_gc_allocate</tt></a> and <a
331 href="#explicit"><tt>llvm_gc_collect</tt></a> functions, and it must implement
332 the <a href="#llvm_gc_readwrite">read/write barrier</a> functions as well.  To
333 do this, it will probably have to <a href="#traceroots">trace through the roots
334 from the stack</a> and understand the <a href="#gcdescriptors">GC descriptors
335 for heap objects</a>.  Luckily, there are some <a href="#gcimpls">example
336 implementations</a> available.
337 </p>
338 </div>
339
340
341 <!-- ======================================================================= -->
342 <div class="doc_subsection">
343   <a name="llvm_gc_readwrite">Implementing <tt>llvm_gc_read</tt> and <tt>llvm_gc_write</tt></a>
344 </div>
345
346 <div class="doc_text">
347   <div class="doc_code"><tt>
348     void *llvm_gc_read(void*, void **)<br>
349     void llvm_gc_write(void*, void *, void**)
350  </tt></div>
351
352 <p>
353 These functions <i>must</i> be implemented in every garbage collector, even if
354 they do not need read/write barriers.  In this case, just load or store the
355 pointer, then return.
356 </p>
357
358 <p>
359 If an actual read or write barrier is needed, it should be straight-forward to
360 implement it.
361 </p>
362
363 </div>
364
365 <!-- ======================================================================= -->
366 <div class="doc_subsection">
367   <a name="callbacks">Callback functions used to implement the garbage collector</a>
368 </div>
369
370 <div class="doc_text">
371 <p>
372 Garbage collector implementations make use of call-back functions that are
373 implemented by other parts of the LLVM system.
374 </p>
375 </div>
376
377 <!--_________________________________________________________________________-->
378 <div class="doc_subsubsection">
379   <a name="traceroots">Tracing GC pointers from the program stack</a>
380 </div>
381
382 <div class="doc_text">
383   <div class="doc_code"><tt>
384      void llvm_cg_walk_gcroots(void (*FP)(void **Root, void *Meta));
385   </tt></div>
386
387 <p>
388 The <tt>llvm_cg_walk_gcroots</tt> function is a function provided by the code
389 generator that iterates through all of the GC roots on the stack, calling the
390 specified function pointer with each record.  For each GC root, the address of
391 the pointer and the meta-data (from the <a
392 href="#roots"><tt>llvm.gcroot</tt></a> intrinsic) are provided.
393 </p>
394 </div>
395
396 <!--_________________________________________________________________________-->
397 <div class="doc_subsubsection">
398   <a name="staticroots">Tracing GC pointers from static roots</a>
399 </div>
400
401 <div class="doc_text">
402 TODO
403 </div>
404
405
406 <!--_________________________________________________________________________-->
407 <div class="doc_subsubsection">
408   <a name="gcdescriptors">Tracing GC pointers from heap objects</a>
409 </div>
410
411 <div class="doc_text">
412 <p>
413 The three most common ways to keep track of where pointers live in heap objects
414 are (listed in order of space overhead required):</p>
415
416 <ol>
417 <li>In languages with polymorphic objects, pointers from an object header are
418 usually used to identify the GC pointers in the heap object.  This is common for
419 object-oriented languages like Self, Smalltalk, Java, or C#.</li>
420
421 <li>If heap objects are not polymorphic, often the "shape" of the heap can be
422 determined from the roots of the heap or from some other meta-data [<a
423 href="#appel89">Appel89</a>, <a href="#goldberg91">Goldberg91</a>, <a
424 href="#tolmach94">Tolmach94</a>].  In this case, the garbage collector can
425 propagate the information around from meta data stored with the roots.  This
426 often eliminates the need to have a header on objects in the heap.  This is
427 common in the ML family.</li>
428
429 <li>If all heap objects have pointers in the same locations, or pointers can be
430 distinguished just by looking at them (e.g., the low order bit is clear), no
431 book-keeping is needed at all.  This is common for Lisp-like languages.</li>
432 </ol>
433
434 <p>The LLVM garbage collectors are capable of supporting all of these styles of
435 language, including ones that mix various implementations.  To do this, it
436 allows the source-language to associate meta-data with the <a
437 href="#roots">stack roots</a>, and the heap tracing routines can propagate the
438 information.  In addition, LLVM allows the front-end to extract GC information
439 from in any form from a specific object pointer (this supports situations #1 and
440 #3).
441 </p>
442
443 <p><b>Making this efficient</b></p>
444
445
446
447 </div>
448
449
450
451 <!-- *********************************************************************** -->
452 <div class="doc_section">
453   <a name="gcimpls">GC implementations available</a>
454 </div>
455 <!-- *********************************************************************** -->
456
457 <div class="doc_text">
458
459 <p>
460 To make this more concrete, the currently implemented LLVM garbage collectors
461 all live in the <tt>llvm/runtime/GC/*</tt> directories in the LLVM source-base.
462 If you are interested in implementing an algorithm, there are many interesting
463 possibilities (mark/sweep, a generational collector, a reference counting
464 collector, etc), or you could choose to improve one of the existing algorithms.
465 </p>
466
467 </div>
468
469 <!-- ======================================================================= -->
470 <div class="doc_subsection">
471   <a name="semispace">SemiSpace - A simple copying garbage collector</a>
472 </div>
473
474 <div class="doc_text">
475 <p>
476 SemiSpace is a very simple copying collector.  When it starts up, it allocates
477 two blocks of memory for the heap.  It uses a simple bump-pointer allocator to
478 allocate memory from the first block until it runs out of space.  When it runs
479 out of space, it traces through all of the roots of the program, copying blocks
480 to the other half of the memory space.
481 </p>
482
483 </div>
484
485 <!--_________________________________________________________________________-->
486 <div class="doc_subsubsection">
487   Possible Improvements
488 </div>
489
490 <div class="doc_text">
491
492 <p>
493 If a collection cycle happens and the heap is not compacted very much (say less
494 than 25% of the allocated memory was freed), the memory regions should be
495 doubled in size.</p>
496
497 </div>
498
499 <!-- *********************************************************************** -->
500 <div class="doc_section">
501   <a name="references">References</a>
502 </div>
503 <!-- *********************************************************************** -->
504
505 <div class="doc_text">
506
507 <p><a name="appel89">[Appel89]</a> Runtime Tags Aren't Necessary. Andrew
508 W. Appel. Lisp and Symbolic Computation 19(7):703-705, July 1989.</p>
509
510 <p><a name="goldberg91">[Goldberg91]</a> Tag-free garbage collection for
511 strongly typed programming languages.  Benjamin Goldberg. ACM SIGPLAN
512 PLDI'91.</p>
513
514 <p><a name="tolmach94">[Tolmach94]</a> Tag-free garbage collection using
515 explicit type parameters.  Andrew Tolmach.  Proceedings of the 1994 ACM
516 conference on LISP and functional programming.</p>
517
518 </div>
519
520 <!-- *********************************************************************** -->
521
522 <hr>
523 <address>
524   <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
525   src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"></a>
526   <a href="http://validator.w3.org/check/referer"><img
527   src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!"></a>
528
529   <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
530   <a href="http://llvm.org">LLVM Compiler Infrastructure</a><br>
531   Last modified: $Date$
532 </address>
533
534 </body>
535 </html>