1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
2 "http://www.w3.org/TR/html4/strict.dtd">
5 <meta http-equiv="Content-Type" Content="text/html; charset=UTF-8" >
6 <title>Accurate Garbage Collection with LLVM</title>
7 <link rel="stylesheet" href="llvm.css" type="text/css">
8 <style type="text/css">
9 .rowhead { text-align: left; background: inherit; }
10 .indent { padding-left: 1em; }
11 .optl { color: #BFBFBF; }
16 <div class="doc_title">
17 Accurate Garbage Collection with LLVM
21 <li><a href="#introduction">Introduction</a>
23 <li><a href="#feature">GC features provided and algorithms
28 <li><a href="#usage">Using the collectors</a>
30 <li><a href="#shadow-stack">ShadowStack -
31 A highly portable collector</a></li>
32 <li><a href="#semispace">SemiSpace -
33 A simple copying collector runtime</a></li>
34 <li><a href="#ocaml">Ocaml -
35 An Objective Caml-compatible collector</a></li>
39 <li><a href="#core">Core support</a>
41 <li><a href="#gcattr">Specifying GC code generation:
42 <tt>gc "..."</tt></a></li>
43 <li><a href="#gcroot">Identifying GC roots on the stack:
44 <tt>llvm.gcroot</tt></a></li>
45 <li><a href="#barriers">Reading and writing references in the heap</a>
47 <li><a href="#gcwrite">Write barrier: <tt>llvm.gcwrite</tt></a></li>
48 <li><a href="#gcread">Read barrier: <tt>llvm.gcread</tt></a></li>
54 <li><a href="#runtime">Recommended runtime interface</a>
56 <li><a href="#initialize">Garbage collector startup and
57 initialization</a></li>
58 <li><a href="#allocate">Allocating memory from the GC</a></li>
59 <li><a href="#explicit">Explicit invocation of the garbage
61 <li><a href="#traceroots">Tracing GC pointers from the program
63 <li><a href="#staticroots">Tracing GC pointers from static roots</a></li>
67 <li><a href="#plugin">Implementing a collector plugin</a>
69 <li><a href="#collector-algos">Overview of available features</a></li>
70 <li><a href="#stack-map">Computing stack maps</a></li>
71 <li><a href="#init-roots">Initializing roots to null:
72 <tt>InitRoots</tt></a></li>
73 <li><a href="#custom">Custom lowering of intrinsics: <tt>CustomRoots</tt>,
74 <tt>CustomReadBarriers</tt>, and <tt>CustomWriteBarriers</tt></a></li>
75 <li><a href="#safe-points">Generating safe points:
76 <tt>NeededSafePoints</tt></a></li>
77 <li><a href="#assembly">Emitting assembly code:
78 <tt>GCMetadataPrinter</tt></a></li>
82 <li><a href="#runtime-impl">Implementing a collector runtime</a>
84 <li><a href="#gcdescriptors">Tracing GC pointers from heap
89 <li><a href="#references">References</a></li>
93 <div class="doc_author">
94 <p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a> and
98 <!-- *********************************************************************** -->
99 <div class="doc_section">
100 <a name="introduction">Introduction</a>
102 <!-- *********************************************************************** -->
104 <div class="doc_text">
106 <p>Garbage collection is a widely used technique that frees the programmer from
107 having to know the lifetimes of heap objects, making software easier to produce
108 and maintain. Many programming languages rely on garbage collection for
109 automatic memory management. There are two primary forms of garbage collection:
110 conservative and accurate.</p>
112 <p>Conservative garbage collection often does not require any special support
113 from either the language or the compiler: it can handle non-type-safe
114 programming languages (such as C/C++) and does not require any special
115 information from the compiler. The
116 <a href="http://www.hpl.hp.com/personal/Hans_Boehm/gc/">Boehm collector</a> is
117 an example of a state-of-the-art conservative collector.</p>
119 <p>Accurate garbage collection requires the ability to identify all pointers in
120 the program at run-time (which requires that the source-language be type-safe in
121 most cases). Identifying pointers at run-time requires compiler support to
122 locate all places that hold live pointer variables at run-time, including the
123 <a href="#gcroot">processor stack and registers</a>.</p>
125 <p>Conservative garbage collection is attractive because it does not require any
126 special compiler support, but it does have problems. In particular, because the
127 conservative garbage collector cannot <i>know</i> that a particular word in the
128 machine is a pointer, it cannot move live objects in the heap (preventing the
129 use of compacting and generational GC algorithms) and it can occasionally suffer
130 from memory leaks due to integer values that happen to point to objects in the
131 program. In addition, some aggressive compiler transformations can break
132 conservative garbage collectors (though these seem rare in practice).</p>
134 <p>Accurate garbage collectors do not suffer from any of these problems, but
135 they can suffer from degraded scalar optimization of the program. In particular,
136 because the runtime must be able to identify and update all pointers active in
137 the program, some optimizations are less effective. In practice, however, the
138 locality and performance benefits of using aggressive garbage allocation
139 techniques dominates any low-level losses.</p>
141 <p>This document describes the mechanisms and interfaces provided by LLVM to
142 support accurate garbage collection.</p>
146 <!-- ======================================================================= -->
147 <div class="doc_subsection">
148 <a name="feature">GC features provided and algorithms supported</a>
151 <div class="doc_text">
153 <p>LLVM's intermediate representation provides <a href="#intrinsics">garbage
154 collection intrinsics</a> that offer support for a broad class of
155 collector models. For instance, the intrinsics permit:</p>
158 <li>semi-space collectors</li>
159 <li>mark-sweep collectors</li>
160 <li>generational collectors</li>
161 <li>reference counting</li>
162 <li>incremental collectors</li>
163 <li>concurrent collectors</li>
164 <li>cooperative collectors</li>
167 <p>We hope that the primitive support built into the LLVM IR is sufficient to
168 support a broad class of garbage collected languages including Scheme, ML, Java,
169 C#, Perl, Python, Lua, Ruby, other scripting languages, and more.</p>
171 <p>However, LLVM does not itself implement a garbage collector. This is because
172 collectors are tightly coupled to object models, and LLVM is agnostic to object
173 models. Since LLVM is agnostic to object models, it would be inappropriate for
174 LLVM to dictate any particular collector. Instead, LLVM provides a framework for
175 garbage collector implementations in two manners:</p>
178 <li><b>At compile time</b> with <a href="#plugin">collector plugins</a> for
179 the compiler. Collector plugins have ready access to important garbage
180 collector algorithms. Leveraging these tools, it is straightforward to
181 emit type-accurate stack maps for your runtime in as little as ~100 lines of
184 <li><b>At runtime</b> with <a href="#runtime">suggested runtime
185 interfaces</a>, which allow front-end compilers to support a range of
186 collection runtimes.</li>
191 <!-- *********************************************************************** -->
192 <div class="doc_section">
193 <a name="usage">Using the collectors</a>
195 <!-- *********************************************************************** -->
197 <div class="doc_text">
199 <p>In general, using a collector implies:</p>
202 <li>Emitting compatible code, including initialization in the main
203 program if necessary.</li>
204 <li>Loading a compiler plugin if the collector is not statically linked with
205 your compiler. For <tt>llc</tt>, use the <tt>-load</tt> option.</li>
206 <li>Selecting the collection algorithm by applying the <tt>gc "..."</tt>
207 attribute to your garbage collected functions, or equivalently with
208 the <tt>setGC</tt> method.</li>
209 <li>Linking your final executable with the garbage collector runtime.</li>
212 <p>This table summarizes the available runtimes.</p>
217 <th><tt>gc</tt> attribute</th>
219 <th><tt>gcroot</tt></th>
220 <th><tt>gcread</tt></th>
221 <th><tt>gcwrite</tt></th>
223 <tr valign="baseline">
224 <td><a href="#semispace">SemiSpace</a></td>
225 <td><tt>gc "shadow-stack"</tt></td>
231 <tr valign="baseline">
232 <td><a href="#ocaml">Ocaml</a></td>
233 <td><tt>gc "ocaml"</tt></td>
234 <td><i>provided by ocamlopt</i></td>
241 <p>The sections for <a href="#intrinsics">Collection intrinsics</a> and
242 <a href="#runtime">Recommended runtime interface</a> detail the interfaces that
243 collectors may require user programs to utilize.</p>
247 <!-- ======================================================================= -->
248 <div class="doc_subsection">
249 <a name="shadow-stack">ShadowStack - A highly portable collector</a>
252 <div class="doc_code"><tt>
253 Collector *llvm::createShadowStackCollector();
256 <div class="doc_text">
258 <p>The ShadowStack backend is invoked with the <tt>gc "shadow-stack"</tt>
260 Unlike many collectors which rely on a cooperative code generator to generate
261 stack maps, this algorithm carefully maintains a linked list of stack root
262 descriptors [<a href="#henderson02">Henderson2002</a>]. This so-called "shadow
263 stack" mirrors the machine stack. Maintaining this data structure is slower
264 than using stack maps, but has a significant portability advantage because it
265 requires no special support from the target code generator.</p>
267 <p>The ShadowStack collector does not use read or write barriers, so the user
268 program may use <tt>load</tt> and <tt>store</tt> instead of <tt>llvm.gcread</tt>
269 and <tt>llvm.gcwrite</tt>.</p>
271 <p>ShadowStack is a code generator plugin only. It must be paired with a
272 compatible runtime.</p>
276 <!-- ======================================================================= -->
277 <div class="doc_subsection">
278 <a name="semispace">SemiSpace - A simple copying collector runtime</a>
281 <div class="doc_text">
283 <p>The SemiSpace runtime implements the <a href="runtime">suggested
284 runtime interface</a> and is compatible with the ShadowStack backend.</p>
286 <p>SemiSpace is a very simple copying collector. When it starts up, it
287 allocates two blocks of memory for the heap. It uses a simple bump-pointer
288 allocator to allocate memory from the first block until it runs out of space.
289 When it runs out of space, it traces through all of the roots of the program,
290 copying blocks to the other half of the memory space.</p>
292 <p>This runtime is highly experimental and has not been used in a real project.
293 Enhancements would be welcomed.</p>
297 <!-- ======================================================================= -->
298 <div class="doc_subsection">
299 <a name="ocaml">Ocaml - An Objective Caml-compatible collector</a>
302 <div class="doc_code"><tt>
303 Collector *llvm::createOcamlCollector();
306 <div class="doc_text">
308 <p>The ocaml backend is invoked with the <tt>gc "ocaml"</tt> function attribute.
310 <a href="http://caml.inria.fr/">Objective Caml</a> language runtime by emitting
311 a type-accurate stack map in the form of an ocaml 3.10.0-compatible frametable.
312 The linkage requirements are satisfied automatically by the <tt>ocamlopt</tt>
313 compiler when linking an executable.</p>
315 <p>The ocaml collector does not use read or write barriers, so the user program
316 may use <tt>load</tt> and <tt>store</tt> instead of <tt>llvm.gcread</tt> and
317 <tt>llvm.gcwrite</tt>.</p>
322 <!-- *********************************************************************** -->
323 <div class="doc_section">
324 <a name="core">Core support</a><a name="intrinsics"></a>
326 <!-- *********************************************************************** -->
328 <div class="doc_text">
330 <p>This section describes the garbage collection facilities provided by the
331 <a href="LangRef.html">LLVM intermediate representation</a>.</p>
333 <p>These facilities are limited to those strictly necessary for compilation.
334 They are not intended to be a complete interface to any garbage collector.
335 Notably, heap allocation is not among the supplied primitives. A user program
336 will also need to interface with the runtime, using either the
337 <a href="#runtime">suggested runtime interface</a> or another interface
338 specified by the runtime.</p>
342 <!-- ======================================================================= -->
343 <div class="doc_subsection">
344 <a name="gcattr">Specifying GC code generation: <tt>gc "..."</tt></a>
347 <div class="doc_code"><tt>
348 define <i>ty</i> @<i>name</i>(...) <u>gc "<i>collector</i>"</u> { ...
351 <div class="doc_text">
353 <p>The <tt>gc</tt> function attribute is used to specify the desired collector
354 algorithm to the compiler. It is equivalent to specifying the collector name
355 programmatically using the <tt>setGC</tt> method of <tt>Function</tt>.</p>
357 <p>Specifying the collector on a per-function basis allows LLVM to link together
358 programs that use different garbage collection algorithms.</p>
362 <!-- ======================================================================= -->
363 <div class="doc_subsection">
364 <a name="gcroot">Identifying GC roots on the stack: <tt>llvm.gcroot</tt></a>
367 <div class="doc_code"><tt>
368 void @llvm.gcroot(i8** %ptrloc, i8* %metadata)
371 <div class="doc_text">
373 <p>The <tt>llvm.gcroot</tt> intrinsic is used to inform LLVM of a pointer
374 variable on the stack. The first argument <b>must</b> be a value referring to an alloca instruction
375 or a bitcast of an alloca. The second contains a pointer to metadata that
376 should be associated with the pointer, and <b>must</b> be a constant or global
377 value address. If your target collector uses tags, use a null pointer for
380 <p>Consider the following fragment of Java code:</p>
384 Object X; // A null-initialized reference to an object
389 <p>This block (which may be located in the middle of a function or in a loop
390 nest), could be compiled to this LLVM code:</p>
394 ;; In the entry block for the function, allocate the
395 ;; stack space for X, which is an LLVM pointer.
398 ;; Tell LLVM that the stack space is a stack root.
399 ;; Java has type-tags on objects, so we pass null as metadata.
400 %tmp = bitcast %Object** %X to i8**
401 call void @llvm.gcroot(i8** %X, i8* null)
404 ;; "CodeBlock" is the block corresponding to the start
405 ;; of the scope above.
407 ;; Java null-initializes pointers.
408 store %Object* null, %Object** %X
412 ;; As the pointer goes out of scope, store a null value into
413 ;; it, to indicate that the value is no longer live.
414 store %Object* null, %Object** %X
420 <!-- ======================================================================= -->
421 <div class="doc_subsection">
422 <a name="barriers">Reading and writing references in the heap</a>
425 <div class="doc_text">
427 <p>Some collectors need to be informed when the mutator (the program that needs
428 garbage collection) either reads a pointer from or writes a pointer to a field
429 of a heap object. The code fragments inserted at these points are called
430 <em>read barriers</em> and <em>write barriers</em>, respectively. The amount of
431 code that needs to be executed is usually quite small and not on the critical
432 path of any computation, so the overall performance impact of the barrier is
435 <p>Barriers often require access to the <em>object pointer</em> rather than the
436 <em>derived pointer</em> (which is a pointer to the field within the
437 object). Accordingly, these intrinsics take both pointers as separate arguments
438 for completeness. In this snippet, <tt>%object</tt> is the object pointer, and
439 <tt>%derived</tt> is the derived pointer:</p>
443 %class.Array = type { %class.Object, i32, [0 x %class.Object*] }
446 ;; Load the object pointer from a gcroot.
447 %object = load %class.Array** %object_addr
449 ;; Compute the derived pointer.
450 %derived = getelementptr %object, i32 0, i32 2, i32 %n</pre></blockquote>
454 <!-- ======================================================================= -->
455 <div class="doc_subsubsection">
456 <a name="gcwrite">Write barrier: <tt>llvm.gcwrite</tt></a>
459 <div class="doc_code"><tt>
460 void @llvm.gcwrite(i8* %value, i8* %object, i8** %derived)
463 <div class="doc_text">
465 <p>For write barriers, LLVM provides the <tt>llvm.gcwrite</tt> intrinsic
466 function. It has exactly the same semantics as a non-volatile <tt>store</tt> to
467 the derived pointer (the third argument).</p>
469 <p>Many important algorithms require write barriers, including generational
470 and concurrent collectors. Additionally, write barriers could be used to
471 implement reference counting.</p>
473 <p>The use of this intrinsic is optional if the target collector does use
474 write barriers. If so, the collector will replace it with the corresponding
479 <!-- ======================================================================= -->
480 <div class="doc_subsubsection">
481 <a name="gcread">Read barrier: <tt>llvm.gcread</tt></a>
484 <div class="doc_code"><tt>
485 i8* @llvm.gcread(i8* %object, i8** %derived)<br>
488 <div class="doc_text">
490 <p>For read barriers, LLVM provides the <tt>llvm.gcread</tt> intrinsic function.
491 It has exactly the same semantics as a non-volatile <tt>load</tt> from the
492 derived pointer (the second argument).</p>
494 <p>Read barriers are needed by fewer algorithms than write barriers, and may
495 have a greater performance impact since pointer reads are more frequent than
498 <p>As with <tt>llvm.gcwrite</tt>, a target collector might not require the use
499 of this intrinsic.</p>
503 <!-- *********************************************************************** -->
504 <div class="doc_section">
505 <a name="runtime">Recommended runtime interface</a>
507 <!-- *********************************************************************** -->
509 <div class="doc_text">
511 <p>LLVM specifies the following recommended runtime interface to the garbage
512 collection at runtime. A program should use these interfaces to accomplish the
513 tasks not supported by the intrinsics.</p>
515 <p>Unlike the intrinsics, which are integral to LLVM's code generator, there is
516 nothing unique about these interfaces; a front-end compiler and runtime are free
517 to agree to a different specification.</p>
519 <p class="doc_warning">Note: This interface is a work in progress.</p>
523 <!-- ======================================================================= -->
524 <div class="doc_subsection">
525 <a name="initialize">Garbage collector startup and initialization</a>
528 <div class="doc_text">
530 <div class="doc_code"><tt>
531 void llvm_gc_initialize(unsigned InitialHeapSize);
535 The <tt>llvm_gc_initialize</tt> function should be called once before any other
536 garbage collection functions are called. This gives the garbage collector the
537 chance to initialize itself and allocate the heap. The initial heap size to
538 allocate should be specified as an argument.
543 <!-- ======================================================================= -->
544 <div class="doc_subsection">
545 <a name="allocate">Allocating memory from the GC</a>
548 <div class="doc_text">
550 <div class="doc_code"><tt>
551 void *llvm_gc_allocate(unsigned Size);
554 <p>The <tt>llvm_gc_allocate</tt> function is a global function defined by the
555 garbage collector implementation to allocate memory. It returns a
556 zeroed-out block of memory of the specified size, sufficiently aligned to store
561 <!-- ======================================================================= -->
562 <div class="doc_subsection">
563 <a name="explicit">Explicit invocation of the garbage collector</a>
566 <div class="doc_text">
568 <div class="doc_code"><tt>
569 void llvm_gc_collect();
573 The <tt>llvm_gc_collect</tt> function is exported by the garbage collector
574 implementations to provide a full collection, even when the heap is not
575 exhausted. This can be used by end-user code as a hint, and may be ignored by
576 the garbage collector.
581 <!-- ======================================================================= -->
582 <div class="doc_subsection">
583 <a name="traceroots">Tracing GC pointers from the program stack</a>
586 <div class="doc_text">
587 <div class="doc_code"><tt>
588 void llvm_cg_walk_gcroots(void (*FP)(void **Root, void *Meta));
592 The <tt>llvm_cg_walk_gcroots</tt> function is a function provided by the code
593 generator that iterates through all of the GC roots on the stack, calling the
594 specified function pointer with each record. For each GC root, the address of
595 the pointer and the meta-data (from the <a
596 href="#gcroot"><tt>llvm.gcroot</tt></a> intrinsic) are provided.
600 <!-- ======================================================================= -->
601 <div class="doc_subsection">
602 <a name="staticroots">Tracing GC pointers from static roots</a>
605 <div class="doc_text">
610 <!-- *********************************************************************** -->
611 <div class="doc_section">
612 <a name="plugin">Implementing a collector plugin</a>
614 <!-- *********************************************************************** -->
616 <div class="doc_text">
618 <p>User code specifies which GC code generation to use with the <tt>gc</tt>
619 function attribute or, equivalently, with the <tt>setGC</tt> method of
620 <tt>Function</tt>.</p>
622 <p>To implement a GC plugin, it is necessary to subclass
623 <tt>llvm::GCStrategy</tt>, which can be accomplished in a few lines of
624 boilerplate code. LLVM's infrastructure provides access to several important
625 algorithms. For an uncontroversial collector, all that remains may be to emit
626 the assembly code for the collector's unique stack map data structure, which
627 might be accomplished in as few as 100 LOC.</p>
629 <p>This is not the appropriate place to implement a garbage collected heap or a
630 garbage collector itself. That code should exist in the language's runtime
631 library. The compiler plugin is responsible for generating code which is
632 compatible with that runtime library.</p>
634 <p>To subclass <tt>llvm::GCStrategy</tt> and register it with the compiler:</p>
636 <blockquote><pre>// lib/MyGC/MyGC.cpp - Example LLVM GC plugin
638 #include "llvm/CodeGen/GCStrategy.h"
639 #include "llvm/CodeGen/GCMetadata.h"
640 #include "llvm/Support/Compiler.h"
642 using namespace llvm;
645 class VISIBILITY_HIDDEN MyGC : public GCStrategy {
650 GCRegistry::Add<MyGC>
651 X("mygc", "My bespoke garbage collector.");
654 <p>Using the LLVM makefiles (like the <a
655 href="http://llvm.org/viewvc/llvm-project/llvm/trunk/projects/sample/">sample
656 project</a>), this can be built into a plugin using a simple makefile:</p>
662 LIBRARYNAME = <var>MyGC</var>
665 include $(LEVEL)/Makefile.common</pre></blockquote>
667 <p>Once the plugin is compiled, code using it may be compiled using <tt>llc
668 -load=<var>MyGC.so</var></tt> (though <var>MyGC.so</var> may have some other
669 platform-specific extension):</p>
673 define void @f() gc "mygc" {
677 $ llvm-as < sample.ll | llc -load=MyGC.so</pre></blockquote>
679 <p>It is also possible to statically link the collector plugin into tools, such
680 as a language-specific compiler front-end.</p>
684 <!-- ======================================================================= -->
685 <div class="doc_subsection">
686 <a name="collector-algos">Overview of available features</a>
689 <div class="doc_text">
691 <p>The boilerplate collector above does nothing. More specifically:</p>
694 <li><tt>llvm.gcread</tt> calls are replaced with the corresponding
695 <tt>load</tt> instruction.</li>
696 <li><tt>llvm.gcwrite</tt> calls are replaced with the corresponding
697 <tt>store</tt> instruction.</li>
698 <li>No stack map is emitted, and no safe points are added.</li>
701 <p><tt>Collector</tt> provides a range of features through which a plugin
702 collector may do useful work. This matrix summarizes the supported (and planned)
703 features and correlates them with the collection techniques which typically
710 <th>shadow stack</th>
719 <th class="rowhead"><a href="#stack-map">stack map</a></th>
730 <th class="rowhead"><a href="#init-roots">initialize roots</a></th>
740 <tr class="doc_warning">
741 <th class="rowhead">derived pointers</th>
752 <th class="rowhead"><em><a href="#custom">custom lowering</a></em></th>
763 <th class="rowhead indent">gcroot</th>
774 <th class="rowhead indent">gcwrite</th>
785 <th class="rowhead indent">gcread</th>
796 <th class="rowhead"><em><a href="#safe-points">safe points</a></em></th>
807 <th class="rowhead indent">in calls</th>
818 <th class="rowhead indent">before calls</th>
828 <tr class="doc_warning">
829 <th class="rowhead indent">for loops</th>
840 <th class="rowhead indent">before escape</th>
850 <tr class="doc_warning">
851 <th class="rowhead">emit code at safe points</th>
862 <th class="rowhead"><em>output</em></th>
873 <th class="rowhead indent"><a href="#assembly">assembly</a></th>
883 <tr class="doc_warning">
884 <th class="rowhead indent">JIT</th>
888 <td class="optl">✘</td>
889 <td class="optl">✘</td>
890 <td class="optl">✘</td>
891 <td class="optl">✘</td>
892 <td class="optl">✘</td>
894 <tr class="doc_warning">
895 <th class="rowhead indent">obj</th>
899 <td class="optl">✘</td>
900 <td class="optl">✘</td>
901 <td class="optl">✘</td>
902 <td class="optl">✘</td>
903 <td class="optl">✘</td>
905 <tr class="doc_warning">
906 <th class="rowhead">live analysis</th>
910 <td class="optl">✘</td>
911 <td class="optl">✘</td>
912 <td class="optl">✘</td>
913 <td class="optl">✘</td>
914 <td class="optl">✘</td>
916 <tr class="doc_warning">
917 <th class="rowhead">register map</th>
921 <td class="optl">✘</td>
922 <td class="optl">✘</td>
923 <td class="optl">✘</td>
924 <td class="optl">✘</td>
925 <td class="optl">✘</td>
929 <div><span class="doc_warning">*</span> Derived pointers only pose a
930 hazard to copying collectors.</div>
931 <div><span class="optl">✘</span> in gray denotes a feature which
932 could be utilized if available.</div>
937 <p>To be clear, the collection techniques above are defined as:</p>
940 <dt>Shadow Stack</dt>
941 <dd>The mutator carefully maintains a linked list of stack root
943 <dt>Reference Counting</dt>
944 <dd>The mutator maintains a reference count for each object and frees an
945 object when its count falls to zero.</dd>
947 <dd>When the heap is exhausted, the collector marks reachable objects starting
948 from the roots, then deallocates unreachable objects in a sweep
951 <dd>As reachability analysis proceeds, the collector copies objects from one
952 heap area to another, compacting them in the process. Copying collectors
953 enable highly efficient "bump pointer" allocation and can improve locality
956 <dd>(Including generational collectors.) Incremental collectors generally have
957 all the properties of a copying collector (regardless of whether the
958 mature heap is compacting), but bring the added complexity of requiring
961 <dd>Denotes a multithreaded mutator; the collector must still stop the mutator
962 ("stop the world") before beginning reachability analysis. Stopping a
963 multithreaded mutator is a complicated problem. It generally requires
964 highly platform specific code in the runtime, and the production of
965 carefully designed machine code at safe points.</dd>
967 <dd>In this technique, the mutator and the collector run concurrently, with
968 the goal of eliminating pause times. In a <em>cooperative</em> collector,
969 the mutator further aids with collection should a pause occur, allowing
970 collection to take advantage of multiprocessor hosts. The "stop the world"
971 problem of threaded collectors is generally still present to a limited
972 extent. Sophisticated marking algorithms are necessary. Read barriers may
976 <p>As the matrix indicates, LLVM's garbage collection infrastructure is already
977 suitable for a wide variety of collectors, but does not currently extend to
978 multithreaded programs. This will be added in the future as there is
983 <!-- ======================================================================= -->
984 <div class="doc_subsection">
985 <a name="stack-map">Computing stack maps</a>
988 <div class="doc_text">
991 >for (iterator I = begin(), E = end(); I != E; ++I) {
992 GCFunctionInfo *FI = *I;
993 unsigned FrameSize = FI->getFrameSize();
994 size_t RootCount = FI->roots_size();
996 for (GCFunctionInfo::roots_iterator RI = FI->roots_begin(),
997 RE = FI->roots_end();
999 int RootNum = RI->Num;
1000 int RootStackOffset = RI->StackOffset;
1001 Constant *RootMetadata = RI->Metadata;
1003 }</pre></blockquote>
1005 <p>LLVM automatically computes a stack map. All a <tt>GCStrategy</tt> needs to do
1006 is access it using <tt>GCFunctionMetadata::roots_begin()</tt> and
1007 -<tt>end()</tt>. If the <tt>llvm.gcroot</tt> intrinsic is eliminated before code
1008 generation by a custom lowering pass, LLVM's stack map will be empty.</p>
1013 <!-- ======================================================================= -->
1014 <div class="doc_subsection">
1015 <a name="init-roots">Initializing roots to null: <tt>InitRoots</tt></a>
1018 <div class="doc_text">
1023 }</pre></blockquote>
1025 <p>When set, LLVM will automatically initialize each root to <tt>null</tt> upon
1026 entry to the function. This prevents the GC's sweep phase from visiting
1027 uninitialized pointers, which will almost certainly cause it to crash. This
1028 initialization occurs before custom lowering, so the two may be used
1031 <p>Since LLVM does not yet compute liveness information, there is no means of
1032 distinguishing an uninitialized stack root from an initialized one. Therefore,
1033 this feature should be used by all GC plugins. It is enabled by default.</p>
1038 <!-- ======================================================================= -->
1039 <div class="doc_subsection">
1040 <a name="custom">Custom lowering of intrinsics: <tt>CustomRoots</tt>,
1041 <tt>CustomReadBarriers</tt>, and <tt>CustomWriteBarriers</tt></a>
1044 <div class="doc_text">
1046 <p>For GCs which use barriers or unusual treatment of stack roots, these
1047 flags allow the collector to perform arbitrary transformations of the LLVM
1051 >class MyGC : public GCStrategy {
1055 CustomReadBarriers = true;
1056 CustomWriteBarriers = true;
1059 virtual bool initializeCustomLowering(Module &M);
1060 virtual bool performCustomLowering(Function &F);
1061 };</pre></blockquote>
1063 <p>If any of these flags are set, then LLVM suppresses its default lowering for
1064 the corresponding intrinsics and instead calls
1065 <tt>performCustomLowering</tt>.</p>
1067 <p>LLVM's default action for each intrinsic is as follows:</p>
1070 <li><tt>llvm.gcroot</tt>: Pass through to the code generator to generate a
1072 <li><tt>llvm.gcread</tt>: Substitute a <tt>load</tt> instruction.</li>
1073 <li><tt>llvm.gcwrite</tt>: Substitute a <tt>store</tt> instruction.</li>
1076 <p>If <tt>CustomReadBarriers</tt> or <tt>CustomWriteBarriers</tt> are specified,
1077 then <tt>performCustomLowering</tt> <strong>must</strong> eliminate the
1078 corresponding barriers.</p>
1080 <p><tt>performCustomLowering</tt> must comply with the same restrictions as <a
1081 href="WritingAnLLVMPass.html#runOnFunction"><tt
1082 >FunctionPass::runOnFunction</tt></a>.
1083 Likewise, <tt>initializeCustomLowering</tt> has the same semantics as <a
1084 href="WritingAnLLVMPass.html#doInitialization_mod"><tt
1085 >Pass::doInitialization(Module&)</tt></a>.</p>
1087 <p>The following can be used as a template:</p>
1090 >#include "llvm/Module.h"
1091 #include "llvm/IntrinsicInst.h"
1093 bool MyGC::initializeCustomLowering(Module &M) {
1097 bool MyGC::performCustomLowering(Function &F) {
1098 bool MadeChange = false;
1100 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1101 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; )
1102 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++))
1103 if (Function *F = CI->getCalledFunction())
1104 switch (F->getIntrinsicID()) {
1105 case Intrinsic::gcwrite:
1106 // Handle llvm.gcwrite.
1107 CI->eraseFromParent();
1110 case Intrinsic::gcread:
1111 // Handle llvm.gcread.
1112 CI->eraseFromParent();
1115 case Intrinsic::gcroot:
1116 // Handle llvm.gcroot.
1117 CI->eraseFromParent();
1123 }</pre></blockquote>
1128 <!-- ======================================================================= -->
1129 <div class="doc_subsection">
1130 <a name="safe-points">Generating safe points: <tt>NeededSafePoints</tt></a>
1133 <div class="doc_text">
1135 <p>LLVM can compute four kinds of safe points:</p>
1139 /// PointKind - The type of a collector-safe point.
1142 Loop, //< Instr is a loop (backwards branch).
1143 Return, //< Instr is a return instruction.
1144 PreCall, //< Instr is a call instruction.
1145 PostCall //< Instr is the return address of a call.
1147 }</pre></blockquote>
1149 <p>A collector can request any combination of the four by setting the
1150 <tt>NeededSafePoints</tt> mask:</p>
1154 NeededSafePoints = 1 << GC::Loop
1155 | 1 << GC::Return
1156 | 1 << GC::PreCall
1157 | 1 << GC::PostCall;
1158 }</pre></blockquote>
1160 <p>It can then use the following routines to access safe points.</p>
1163 >for (iterator I = begin(), E = end(); I != E; ++I) {
1164 GCFunctionInfo *MD = *I;
1165 size_t PointCount = MD->size();
1167 for (GCFunctionInfo::iterator PI = MD->begin(),
1168 PE = MD->end(); PI != PE; ++PI) {
1169 GC::PointKind PointKind = PI->Kind;
1170 unsigned PointNum = PI->Num;
1175 <p>Almost every collector requires <tt>PostCall</tt> safe points, since these
1176 correspond to the moments when the function is suspended during a call to a
1179 <p>Threaded programs generally require <tt>Loop</tt> safe points to guarantee
1180 that the application will reach a safe point within a bounded amount of time,
1181 even if it is executing a long-running loop which contains no function
1184 <p>Threaded collectors may also require <tt>Return</tt> and <tt>PreCall</tt>
1185 safe points to implement "stop the world" techniques using self-modifying code,
1186 where it is important that the program not exit the function without reaching a
1187 safe point (because only the topmost function has been patched).</p>
1192 <!-- ======================================================================= -->
1193 <div class="doc_subsection">
1194 <a name="assembly">Emitting assembly code: <tt>GCMetadataPrinter</tt></a>
1197 <div class="doc_text">
1199 <p>LLVM allows a GC to print arbitrary assembly code before and after the rest
1200 of a module's assembly code. At the end of the module, the GC can print stack
1201 maps built by the code generator. (At the beginning, this information is not
1204 <p>Since AsmWriter and CodeGen are separate components of LLVM, a separate
1205 abstract base class and registry is provided for printing assembly code, the
1206 <tt>GCMetadaPrinter</tt> and <tt>GCMetadaPrinterRegistry</tt>. The AsmWriter
1207 will look for such a subclass if the <tt>GCStrategy</tt> sets
1208 <tt>UsesMetadata</tt>:</p>
1212 UsesMetadata = true;
1213 }</pre></blockquote>
1215 <p>Note that LLVM does not currently have analogous APIs to support code
1216 generation in the JIT, nor using the object writers.</p>
1219 >// lib/MyGC/MyGCPrinter.cpp - Example LLVM GC printer
1221 #include "llvm/CodeGen/GCMetadataPrinter.h"
1222 #include "llvm/Support/Compiler.h"
1224 using namespace llvm;
1227 class VISIBILITY_HIDDEN MyGCPrinter : public GCMetadataPrinter {
1229 virtual void beginAssembly(std::ostream &OS, AsmPrinter &AP,
1230 const TargetAsmInfo &TAI);
1232 virtual void finishAssembly(std::ostream &OS, AsmPrinter &AP,
1233 const TargetAsmInfo &TAI);
1236 GCMetadataPrinterRegistry::Add<MyGCPrinter>
1237 X("mygc", "My bespoke garbage collector.");
1238 }</pre></blockquote>
1240 <p>The collector should use <tt>AsmPrinter</tt> and <tt>TargetAsmInfo</tt> to
1241 print portable assembly code to the <tt>std::ostream</tt>. The collector itself
1242 contains the stack map for the entire module, and may access the
1243 <tt>GCFunctionInfo</tt> using its own <tt>begin()</tt> and <tt>end()</tt>
1244 methods. Here's a realistic example:</p>
1247 >#include "llvm/CodeGen/AsmPrinter.h"
1248 #include "llvm/Function.h"
1249 #include "llvm/Target/TargetMachine.h"
1250 #include "llvm/Target/TargetData.h"
1251 #include "llvm/Target/TargetAsmInfo.h"
1253 void MyGCPrinter::beginAssembly(std::ostream &OS, AsmPrinter &AP,
1254 const TargetAsmInfo &TAI) {
1258 void MyGCPrinter::finishAssembly(std::ostream &OS, AsmPrinter &AP,
1259 const TargetAsmInfo &TAI) {
1260 // Set up for emitting addresses.
1261 const char *AddressDirective;
1262 int AddressAlignLog;
1263 if (AP.TM.getTargetData()->getPointerSize() == sizeof(int32_t)) {
1264 AddressDirective = TAI.getData32bitsDirective();
1265 AddressAlignLog = 2;
1267 AddressDirective = TAI.getData64bitsDirective();
1268 AddressAlignLog = 3;
1271 // Put this in the data section.
1272 AP.SwitchToDataSection(TAI.getDataSection());
1274 // For each function...
1275 for (iterator FI = begin(), FE = end(); FI != FE; ++FI) {
1276 GCFunctionInfo &MD = **FI;
1278 // Emit this data structure:
1281 // int32_t PointCount;
1283 // void *SafePointAddress;
1284 // int32_t LiveCount;
1285 // int32_t LiveOffsets[LiveCount];
1286 // } Points[PointCount];
1287 // } __gcmap_<FUNCTIONNAME>;
1289 // Align to address width.
1290 AP.EmitAlignment(AddressAlignLog);
1292 // Emit the symbol by which the stack map can be found.
1294 Symbol += TAI.getGlobalPrefix();
1295 Symbol += "__gcmap_";
1296 Symbol += MD.getFunction().getName();
1297 if (const char *GlobalDirective = TAI.getGlobalDirective())
1298 OS << GlobalDirective << Symbol << "\n";
1299 OS << TAI.getGlobalPrefix() << Symbol << ":\n";
1302 AP.EmitInt32(MD.size());
1303 AP.EOL("safe point count");
1305 // And each safe point...
1306 for (GCFunctionInfo::iterator PI = MD.begin(),
1307 PE = MD.end(); PI != PE; ++PI) {
1308 // Align to address width.
1309 AP.EmitAlignment(AddressAlignLog);
1311 // Emit the address of the safe point.
1312 OS << AddressDirective
1313 << TAI.getPrivateGlobalPrefix() << "label" << PI->Num;
1314 AP.EOL("safe point address");
1316 // Emit the stack frame size.
1317 AP.EmitInt32(MD.getFrameSize());
1318 AP.EOL("stack frame size");
1320 // Emit the number of live roots in the function.
1321 AP.EmitInt32(MD.live_size(PI));
1322 AP.EOL("live root count");
1324 // And for each live root...
1325 for (GCFunctionInfo::live_iterator LI = MD.live_begin(PI),
1326 LE = MD.live_end(PI);
1328 // Print its offset within the stack frame.
1329 AP.EmitInt32(LI->StackOffset);
1330 AP.EOL("stack offset");
1340 <!-- *********************************************************************** -->
1341 <div class="doc_section">
1342 <a name="runtime-impl">Implementing a collector runtime</a>
1344 <!-- *********************************************************************** -->
1346 <div class="doc_text">
1348 <p>Implementing a garbage collector for LLVM is fairly straightforward. The
1349 LLVM garbage collectors are provided in a form that makes them easy to link into
1350 the language-specific runtime that a language front-end would use. They require
1351 functionality from the language-specific runtime to get information about <a
1352 href="#gcdescriptors">where pointers are located in heap objects</a>.</p>
1354 <p>The implementation must include the
1355 <a href="#allocate"><tt>llvm_gc_allocate</tt></a> and
1356 <a href="#explicit"><tt>llvm_gc_collect</tt></a> functions. To do this, it will
1357 probably have to <a href="#traceroots">trace through the roots
1358 from the stack</a> and understand the <a href="#gcdescriptors">GC descriptors
1359 for heap objects</a>. Luckily, there are some <a href="#usage">example
1360 implementations</a> available.
1365 <!-- ======================================================================= -->
1366 <div class="doc_subsection">
1367 <a name="gcdescriptors">Tracing GC pointers from heap objects</a>
1370 <div class="doc_text">
1372 The three most common ways to keep track of where pointers live in heap objects
1373 are (listed in order of space overhead required):</p>
1376 <li>In languages with polymorphic objects, pointers from an object header are
1377 usually used to identify the GC pointers in the heap object. This is common for
1378 object-oriented languages like Self, Smalltalk, Java, or C#.</li>
1380 <li>If heap objects are not polymorphic, often the "shape" of the heap can be
1381 determined from the roots of the heap or from some other meta-data [<a
1382 href="#appel89">Appel89</a>, <a href="#goldberg91">Goldberg91</a>, <a
1383 href="#tolmach94">Tolmach94</a>]. In this case, the garbage collector can
1384 propagate the information around from meta data stored with the roots. This
1385 often eliminates the need to have a header on objects in the heap. This is
1386 common in the ML family.</li>
1388 <li>If all heap objects have pointers in the same locations, or pointers can be
1389 distinguished just by looking at them (e.g., the low order bit is clear), no
1390 book-keeping is needed at all. This is common for Lisp-like languages.</li>
1393 <p>The LLVM garbage collectors are capable of supporting all of these styles of
1394 language, including ones that mix various implementations. To do this, it
1395 allows the source-language to associate meta-data with the <a
1396 href="#gcroot">stack roots</a>, and the heap tracing routines can propagate the
1397 information. In addition, LLVM allows the front-end to extract GC information
1398 in any form from a specific object pointer (this supports situations #1 and #3).
1404 <!-- *********************************************************************** -->
1405 <div class="doc_section">
1406 <a name="references">References</a>
1408 <!-- *********************************************************************** -->
1410 <div class="doc_text">
1412 <p><a name="appel89">[Appel89]</a> Runtime Tags Aren't Necessary. Andrew
1413 W. Appel. Lisp and Symbolic Computation 19(7):703-705, July 1989.</p>
1415 <p><a name="goldberg91">[Goldberg91]</a> Tag-free garbage collection for
1416 strongly typed programming languages. Benjamin Goldberg. ACM SIGPLAN
1419 <p><a name="tolmach94">[Tolmach94]</a> Tag-free garbage collection using
1420 explicit type parameters. Andrew Tolmach. Proceedings of the 1994 ACM
1421 conference on LISP and functional programming.</p>
1423 <p><a name="henderson02">[Henderson2002]</a> <a
1424 href="http://citeseer.ist.psu.edu/henderson02accurate.html">
1425 Accurate Garbage Collection in an Uncooperative Environment</a>.
1426 Fergus Henderson. International Symposium on Memory Management 2002.</p>
1431 <!-- *********************************************************************** -->
1435 <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
1436 src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS"></a>
1437 <a href="http://validator.w3.org/check/referer"><img
1438 src="http://www.w3.org/Icons/valid-html401-blue" alt="Valid HTML 4.01"></a>
1440 <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
1441 <a href="http://llvm.org">LLVM Compiler Infrastructure</a><br>
1442 Last modified: $Date$