blob: 7765bd7d04cf5e7504e44a7a7cfd4a2f1af139d4 [file] [log] [blame]
Sean Silva691f4702012-12-09 15:52:47 +00001=====================================
2Accurate Garbage Collection with LLVM
3=====================================
4
5.. contents::
6 :local:
7
8.. sectionauthor:: Chris Lattner <sabre@nondot.org> and
9 Gordon Henriksen
10
11Introduction
12============
13
14Garbage collection is a widely used technique that frees the programmer from
15having to know the lifetimes of heap objects, making software easier to produce
16and maintain. Many programming languages rely on garbage collection for
17automatic memory management. There are two primary forms of garbage collection:
18conservative and accurate.
19
20Conservative garbage collection often does not require any special support from
21either the language or the compiler: it can handle non-type-safe programming
22languages (such as C/C++) and does not require any special information from the
23compiler. The `Boehm collector
24<http://www.hpl.hp.com/personal/Hans_Boehm/gc/>`__ is an example of a
25state-of-the-art conservative collector.
26
27Accurate garbage collection requires the ability to identify all pointers in the
28program at run-time (which requires that the source-language be type-safe in
29most cases). Identifying pointers at run-time requires compiler support to
30locate all places that hold live pointer variables at run-time, including the
31:ref:`processor stack and registers <gcroot>`.
32
33Conservative garbage collection is attractive because it does not require any
34special compiler support, but it does have problems. In particular, because the
35conservative garbage collector cannot *know* that a particular word in the
36machine is a pointer, it cannot move live objects in the heap (preventing the
37use of compacting and generational GC algorithms) and it can occasionally suffer
38from memory leaks due to integer values that happen to point to objects in the
39program. In addition, some aggressive compiler transformations can break
40conservative garbage collectors (though these seem rare in practice).
41
42Accurate garbage collectors do not suffer from any of these problems, but they
43can suffer from degraded scalar optimization of the program. In particular,
44because the runtime must be able to identify and update all pointers active in
45the program, some optimizations are less effective. In practice, however, the
46locality and performance benefits of using aggressive garbage collection
47techniques dominates any low-level losses.
48
49This document describes the mechanisms and interfaces provided by LLVM to
50support accurate garbage collection.
51
Sean Silva691f4702012-12-09 15:52:47 +000052Goals and non-goals
53-------------------
54
55LLVM's intermediate representation provides :ref:`garbage collection intrinsics
56<gc_intrinsics>` that offer support for a broad class of collector models. For
57instance, the intrinsics permit:
58
59* semi-space collectors
60
61* mark-sweep collectors
62
63* generational collectors
64
65* reference counting
66
67* incremental collectors
68
69* concurrent collectors
70
71* cooperative collectors
72
73We hope that the primitive support built into the LLVM IR is sufficient to
74support a broad class of garbage collected languages including Scheme, ML, Java,
75C#, Perl, Python, Lua, Ruby, other scripting languages, and more.
76
77However, LLVM does not itself provide a garbage collector --- this should be
78part of your language's runtime library. LLVM provides a framework for compile
79time :ref:`code generation plugins <plugin>`. The role of these plugins is to
80generate code and data structures which conforms to the *binary interface*
81specified by the *runtime library*. This is similar to the relationship between
82LLVM and DWARF debugging info, for example. The difference primarily lies in
83the lack of an established standard in the domain of garbage collection --- thus
84the plugins.
85
86The aspects of the binary interface with which LLVM's GC support is
87concerned are:
88
89* Creation of GC-safe points within code where collection is allowed to execute
90 safely.
91
92* Computation of the stack map. For each safe point in the code, object
93 references within the stack frame must be identified so that the collector may
94 traverse and perhaps update them.
95
96* Write barriers when storing object references to the heap. These are commonly
97 used to optimize incremental scans in generational collectors.
98
99* Emission of read barriers when loading object references. These are useful
100 for interoperating with concurrent collectors.
101
102There are additional areas that LLVM does not directly address:
103
104* Registration of global roots with the runtime.
105
106* Registration of stack map entries with the runtime.
107
108* The functions used by the program to allocate memory, trigger a collection,
109 etc.
110
111* Computation or compilation of type maps, or registration of them with the
112 runtime. These are used to crawl the heap for object references.
113
114In general, LLVM's support for GC does not include features which can be
115adequately addressed with other features of the IR and does not specify a
116particular binary interface. On the plus side, this means that you should be
117able to integrate LLVM with an existing runtime. On the other hand, it leaves a
118lot of work for the developer of a novel language. However, it's easy to get
119started quickly and scale up to a more sophisticated implementation as your
120compiler matures.
121
Sean Silva691f4702012-12-09 15:52:47 +0000122Getting started
123===============
124
125Using a GC with LLVM implies many things, for example:
126
127* Write a runtime library or find an existing one which implements a GC heap.
128
129 #. Implement a memory allocator.
130
131 #. Design a binary interface for the stack map, used to identify references
132 within a stack frame on the machine stack.\*
133
134 #. Implement a stack crawler to discover functions on the call stack.\*
135
136 #. Implement a registry for global roots.
137
138 #. Design a binary interface for type maps, used to identify references
139 within heap objects.
140
141 #. Implement a collection routine bringing together all of the above.
142
143* Emit compatible code from your compiler.
144
145 * Initialization in the main function.
146
147 * Use the ``gc "..."`` attribute to enable GC code generation (or
148 ``F.setGC("...")``).
149
150 * Use ``@llvm.gcroot`` to mark stack roots.
151
152 * Use ``@llvm.gcread`` and/or ``@llvm.gcwrite`` to manipulate GC references,
153 if necessary.
154
155 * Allocate memory using the GC allocation routine provided by the runtime
156 library.
157
158 * Generate type maps according to your runtime's binary interface.
159
160* Write a compiler plugin to interface LLVM with the runtime library.\*
161
162 * Lower ``@llvm.gcread`` and ``@llvm.gcwrite`` to appropriate code
163 sequences.\*
164
165 * Compile LLVM's stack map to the binary form expected by the runtime.
166
167* Load the plugin into the compiler. Use ``llc -load`` or link the plugin
168 statically with your language's compiler.\*
169
170* Link program executables with the runtime.
171
172To help with several of these tasks (those indicated with a \*), LLVM includes a
173highly portable, built-in ShadowStack code generator. It is compiled into
174``llc`` and works even with the interpreter and C backends.
175
Sean Silva691f4702012-12-09 15:52:47 +0000176In your compiler
177----------------
178
179To turn the shadow stack on for your functions, first call:
180
181.. code-block:: c++
182
183 F.setGC("shadow-stack");
184
185for each function your compiler emits. Since the shadow stack is built into
186LLVM, you do not need to load a plugin.
187
188Your compiler must also use ``@llvm.gcroot`` as documented. Don't forget to
189create a root for each intermediate value that is generated when evaluating an
190expression. In ``h(f(), g())``, the result of ``f()`` could easily be collected
191if evaluating ``g()`` triggers a collection.
192
193There's no need to use ``@llvm.gcread`` and ``@llvm.gcwrite`` over plain
194``load`` and ``store`` for now. You will need them when switching to a more
195advanced GC.
196
Sean Silva691f4702012-12-09 15:52:47 +0000197In your runtime
198---------------
199
200The shadow stack doesn't imply a memory allocation algorithm. A semispace
201collector or building atop ``malloc`` are great places to start, and can be
202implemented with very little code.
203
204When it comes time to collect, however, your runtime needs to traverse the stack
205roots, and for this it needs to integrate with the shadow stack. Luckily, doing
206so is very simple. (This code is heavily commented to help you understand the
207data structure, but there are only 20 lines of meaningful code.)
208
209.. code-block:: c++
210
211 /// @brief The map for a single function's stack frame. One of these is
212 /// compiled as constant data into the executable for each function.
213 ///
214 /// Storage of metadata values is elided if the %metadata parameter to
215 /// @llvm.gcroot is null.
216 struct FrameMap {
217 int32_t NumRoots; //< Number of roots in stack frame.
218 int32_t NumMeta; //< Number of metadata entries. May be < NumRoots.
219 const void *Meta[0]; //< Metadata for each root.
220 };
221
222 /// @brief A link in the dynamic shadow stack. One of these is embedded in
223 /// the stack frame of each function on the call stack.
224 struct StackEntry {
225 StackEntry *Next; //< Link to next stack entry (the caller's).
226 const FrameMap *Map; //< Pointer to constant FrameMap.
227 void *Roots[0]; //< Stack roots (in-place array).
228 };
229
230 /// @brief The head of the singly-linked list of StackEntries. Functions push
231 /// and pop onto this in their prologue and epilogue.
232 ///
233 /// Since there is only a global list, this technique is not threadsafe.
234 StackEntry *llvm_gc_root_chain;
235
236 /// @brief Calls Visitor(root, meta) for each GC root on the stack.
237 /// root and meta are exactly the values passed to
238 /// @llvm.gcroot.
239 ///
240 /// Visitor could be a function to recursively mark live objects. Or it
241 /// might copy them to another heap or generation.
242 ///
243 /// @param Visitor A function to invoke for every GC root on the stack.
244 void visitGCRoots(void (*Visitor)(void **Root, const void *Meta)) {
245 for (StackEntry *R = llvm_gc_root_chain; R; R = R->Next) {
246 unsigned i = 0;
247
248 // For roots [0, NumMeta), the metadata pointer is in the FrameMap.
249 for (unsigned e = R->Map->NumMeta; i != e; ++i)
250 Visitor(&R->Roots[i], R->Map->Meta[i]);
251
252 // For roots [NumMeta, NumRoots), the metadata pointer is null.
253 for (unsigned e = R->Map->NumRoots; i != e; ++i)
254 Visitor(&R->Roots[i], NULL);
255 }
256 }
257
Sean Silva691f4702012-12-09 15:52:47 +0000258About the shadow stack
259----------------------
260
261Unlike many GC algorithms which rely on a cooperative code generator to compile
262stack maps, this algorithm carefully maintains a linked list of stack roots
263[:ref:`Henderson2002 <henderson02>`]. This so-called "shadow stack" mirrors the
264machine stack. Maintaining this data structure is slower than using a stack map
265compiled into the executable as constant data, but has a significant portability
266advantage because it requires no special support from the target code generator,
267and does not require tricky platform-specific code to crawl the machine stack.
268
269The tradeoff for this simplicity and portability is:
270
271* High overhead per function call.
272
273* Not thread-safe.
274
275Still, it's an easy way to get started. After your compiler and runtime are up
Dmitri Gribenko8f691212012-12-11 23:35:23 +0000276and running, writing a :ref:`plugin <plugin>` will allow you to take advantage
277of :ref:`more advanced GC features <collector-algos>` of LLVM in order to
278improve performance.
Sean Silva691f4702012-12-09 15:52:47 +0000279
280.. _gc_intrinsics:
281
282IR features
283===========
284
285This section describes the garbage collection facilities provided by the
286:doc:`LLVM intermediate representation <LangRef>`. The exact behavior of these
287IR features is specified by the binary interface implemented by a :ref:`code
288generation plugin <plugin>`, not by this document.
289
290These facilities are limited to those strictly necessary; they are not intended
291to be a complete interface to any garbage collector. A program will need to
292interface with the GC library using the facilities provided by that program.
293
Sean Silva691f4702012-12-09 15:52:47 +0000294Specifying GC code generation: ``gc "..."``
295-------------------------------------------
296
297.. code-block:: llvm
298
299 define ty @name(...) gc "name" { ...
300
301The ``gc`` function attribute is used to specify the desired GC style to the
302compiler. Its programmatic equivalent is the ``setGC`` method of ``Function``.
303
304Setting ``gc "name"`` on a function triggers a search for a matching code
305generation plugin "*name*"; it is that plugin which defines the exact nature of
306the code generated to support GC. If none is found, the compiler will raise an
307error.
308
309Specifying the GC style on a per-function basis allows LLVM to link together
310programs that use different garbage collection algorithms (or none at all).
311
312.. _gcroot:
313
314Identifying GC roots on the stack: ``llvm.gcroot``
315--------------------------------------------------
316
317.. code-block:: llvm
318
319 void @llvm.gcroot(i8** %ptrloc, i8* %metadata)
320
321The ``llvm.gcroot`` intrinsic is used to inform LLVM that a stack variable
322references an object on the heap and is to be tracked for garbage collection.
323The exact impact on generated code is specified by a :ref:`compiler plugin
324<plugin>`. All calls to ``llvm.gcroot`` **must** reside inside the first basic
325block.
326
327A compiler which uses mem2reg to raise imperative code using ``alloca`` into SSA
328form need only add a call to ``@llvm.gcroot`` for those variables which a
329pointers into the GC heap.
330
331It is also important to mark intermediate values with ``llvm.gcroot``. For
332example, consider ``h(f(), g())``. Beware leaking the result of ``f()`` in the
333case that ``g()`` triggers a collection. Note, that stack variables must be
334initialized and marked with ``llvm.gcroot`` in function's prologue.
335
336The first argument **must** be a value referring to an alloca instruction or a
337bitcast of an alloca. The second contains a pointer to metadata that should be
338associated with the pointer, and **must** be a constant or global value
339address. If your target collector uses tags, use a null pointer for metadata.
340
341The ``%metadata`` argument can be used to avoid requiring heap objects to have
342'isa' pointers or tag bits. [Appel89_, Goldberg91_, Tolmach94_] If specified,
343its value will be tracked along with the location of the pointer in the stack
344frame.
345
346Consider the following fragment of Java code:
347
348.. code-block:: java
349
350 {
351 Object X; // A null-initialized reference to an object
352 ...
353 }
354
355This block (which may be located in the middle of a function or in a loop nest),
356could be compiled to this LLVM code:
357
358.. code-block:: llvm
359
360 Entry:
361 ;; In the entry block for the function, allocate the
362 ;; stack space for X, which is an LLVM pointer.
363 %X = alloca %Object*
364
365 ;; Tell LLVM that the stack space is a stack root.
366 ;; Java has type-tags on objects, so we pass null as metadata.
367 %tmp = bitcast %Object** %X to i8**
368 call void @llvm.gcroot(i8** %tmp, i8* null)
369 ...
370
371 ;; "CodeBlock" is the block corresponding to the start
372 ;; of the scope above.
373 CodeBlock:
374 ;; Java null-initializes pointers.
375 store %Object* null, %Object** %X
376
377 ...
378
379 ;; As the pointer goes out of scope, store a null value into
380 ;; it, to indicate that the value is no longer live.
381 store %Object* null, %Object** %X
382 ...
383
Sean Silva691f4702012-12-09 15:52:47 +0000384Reading and writing references in the heap
385------------------------------------------
386
387Some collectors need to be informed when the mutator (the program that needs
388garbage collection) either reads a pointer from or writes a pointer to a field
389of a heap object. The code fragments inserted at these points are called *read
390barriers* and *write barriers*, respectively. The amount of code that needs to
391be executed is usually quite small and not on the critical path of any
392computation, so the overall performance impact of the barrier is tolerable.
393
394Barriers often require access to the *object pointer* rather than the *derived
395pointer* (which is a pointer to the field within the object). Accordingly,
396these intrinsics take both pointers as separate arguments for completeness. In
397this snippet, ``%object`` is the object pointer, and ``%derived`` is the derived
398pointer:
399
400.. code-block:: llvm
401
402 ;; An array type.
403 %class.Array = type { %class.Object, i32, [0 x %class.Object*] }
404 ...
405
406 ;; Load the object pointer from a gcroot.
407 %object = load %class.Array** %object_addr
408
409 ;; Compute the derived pointer.
410 %derived = getelementptr %object, i32 0, i32 2, i32 %n
411
412LLVM does not enforce this relationship between the object and derived pointer
Dmitri Gribenko8f691212012-12-11 23:35:23 +0000413(although a :ref:`plugin <plugin>` might). However, it would be an unusual
414collector that violated it.
Sean Silva691f4702012-12-09 15:52:47 +0000415
416The use of these intrinsics is naturally optional if the target GC does require
417the corresponding barrier. Such a GC plugin will replace the intrinsic calls
418with the corresponding ``load`` or ``store`` instruction if they are used.
419
Sean Silva691f4702012-12-09 15:52:47 +0000420Write barrier: ``llvm.gcwrite``
421^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
422
423.. code-block:: llvm
424
425 void @llvm.gcwrite(i8* %value, i8* %object, i8** %derived)
426
427For write barriers, LLVM provides the ``llvm.gcwrite`` intrinsic function. It
428has exactly the same semantics as a non-volatile ``store`` to the derived
429pointer (the third argument). The exact code generated is specified by a
Dmitri Gribenko8f691212012-12-11 23:35:23 +0000430compiler :ref:`plugin <plugin>`.
Sean Silva691f4702012-12-09 15:52:47 +0000431
432Many important algorithms require write barriers, including generational and
433concurrent collectors. Additionally, write barriers could be used to implement
434reference counting.
435
Sean Silva691f4702012-12-09 15:52:47 +0000436Read barrier: ``llvm.gcread``
437^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
438
439.. code-block:: llvm
440
441 i8* @llvm.gcread(i8* %object, i8** %derived)
442
443For read barriers, LLVM provides the ``llvm.gcread`` intrinsic function. It has
444exactly the same semantics as a non-volatile ``load`` from the derived pointer
Dmitri Gribenko8f691212012-12-11 23:35:23 +0000445(the second argument). The exact code generated is specified by a
446:ref:`compiler plugin <plugin>`.
Sean Silva691f4702012-12-09 15:52:47 +0000447
448Read barriers are needed by fewer algorithms than write barriers, and may have a
449greater performance impact since pointer reads are more frequent than writes.
450
451.. _plugin:
452
453Implementing a collector plugin
454===============================
455
456User code specifies which GC code generation to use with the ``gc`` function
457attribute or, equivalently, with the ``setGC`` method of ``Function``.
458
459To implement a GC plugin, it is necessary to subclass ``llvm::GCStrategy``,
460which can be accomplished in a few lines of boilerplate code. LLVM's
461infrastructure provides access to several important algorithms. For an
462uncontroversial collector, all that remains may be to compile LLVM's computed
463stack map to assembly code (using the binary representation expected by the
464runtime library). This can be accomplished in about 100 lines of code.
465
466This is not the appropriate place to implement a garbage collected heap or a
467garbage collector itself. That code should exist in the language's runtime
468library. The compiler plugin is responsible for generating code which conforms
469to the binary interface defined by library, most essentially the :ref:`stack map
470<stack-map>`.
471
472To subclass ``llvm::GCStrategy`` and register it with the compiler:
473
474.. code-block:: c++
475
476 // lib/MyGC/MyGC.cpp - Example LLVM GC plugin
477
478 #include "llvm/CodeGen/GCStrategy.h"
479 #include "llvm/CodeGen/GCMetadata.h"
480 #include "llvm/Support/Compiler.h"
481
482 using namespace llvm;
483
484 namespace {
485 class LLVM_LIBRARY_VISIBILITY MyGC : public GCStrategy {
486 public:
487 MyGC() {}
488 };
489
490 GCRegistry::Add<MyGC>
491 X("mygc", "My bespoke garbage collector.");
492 }
493
494This boilerplate collector does nothing. More specifically:
495
496* ``llvm.gcread`` calls are replaced with the corresponding ``load``
497 instruction.
498
499* ``llvm.gcwrite`` calls are replaced with the corresponding ``store``
500 instruction.
501
502* No safe points are added to the code.
503
504* The stack map is not compiled into the executable.
505
506Using the LLVM makefiles (like the `sample project
507<http://llvm.org/viewvc/llvm-project/llvm/trunk/projects/sample/>`__), this code
508can be compiled as a plugin using a simple makefile:
509
510.. code-block:: make
511
512 # lib/MyGC/Makefile
513
514 LEVEL := ../..
515 LIBRARYNAME = MyGC
516 LOADABLE_MODULE = 1
517
518 include $(LEVEL)/Makefile.common
519
520Once the plugin is compiled, code using it may be compiled using ``llc
521-load=MyGC.so`` (though MyGC.so may have some other platform-specific
522extension):
523
524::
525
526 $ cat sample.ll
527 define void @f() gc "mygc" {
528 entry:
529 ret void
530 }
531 $ llvm-as < sample.ll | llc -load=MyGC.so
532
533It is also possible to statically link the collector plugin into tools, such as
534a language-specific compiler front-end.
535
536.. _collector-algos:
537
538Overview of available features
539------------------------------
540
541``GCStrategy`` provides a range of features through which a plugin may do useful
542work. Some of these are callbacks, some are algorithms that can be enabled,
543disabled, or customized. This matrix summarizes the supported (and planned)
544features and correlates them with the collection techniques which typically
545require them.
546
547.. |v| unicode:: 0x2714
548 :trim:
549
550.. |x| unicode:: 0x2718
551 :trim:
552
553+------------+------+--------+----------+-------+---------+-------------+----------+------------+
554| Algorithm | Done | Shadow | refcount | mark- | copying | incremental | threaded | concurrent |
555| | | stack | | sweep | | | | |
556+============+======+========+==========+=======+=========+=============+==========+============+
557| stack map | |v| | | | |x| | |x| | |x| | |x| | |x| |
558+------------+------+--------+----------+-------+---------+-------------+----------+------------+
559| initialize | |v| | |x| | |x| | |x| | |x| | |x| | |x| | |x| |
560| roots | | | | | | | | |
561+------------+------+--------+----------+-------+---------+-------------+----------+------------+
562| derived | NO | | | | | | **N**\* | **N**\* |
563| pointers | | | | | | | | |
564+------------+------+--------+----------+-------+---------+-------------+----------+------------+
565| **custom | |v| | | | | | | | |
566| lowering** | | | | | | | | |
567+------------+------+--------+----------+-------+---------+-------------+----------+------------+
568| *gcroot* | |v| | |x| | |x| | | | | | |
569+------------+------+--------+----------+-------+---------+-------------+----------+------------+
570| *gcwrite* | |v| | | |x| | | | |x| | | |x| |
571+------------+------+--------+----------+-------+---------+-------------+----------+------------+
572| *gcread* | |v| | | | | | | | |x| |
573+------------+------+--------+----------+-------+---------+-------------+----------+------------+
574| **safe | | | | | | | | |
575| points** | | | | | | | | |
576+------------+------+--------+----------+-------+---------+-------------+----------+------------+
577| *in | |v| | | | |x| | |x| | |x| | |x| | |x| |
578| calls* | | | | | | | | |
579+------------+------+--------+----------+-------+---------+-------------+----------+------------+
580| *before | |v| | | | | | | |x| | |x| |
581| calls* | | | | | | | | |
582+------------+------+--------+----------+-------+---------+-------------+----------+------------+
583| *for | NO | | | | | | **N** | **N** |
584| loops* | | | | | | | | |
585+------------+------+--------+----------+-------+---------+-------------+----------+------------+
586| *before | |v| | | | | | | |x| | |x| |
587| escape* | | | | | | | | |
588+------------+------+--------+----------+-------+---------+-------------+----------+------------+
589| emit code | NO | | | | | | **N** | **N** |
590| at safe | | | | | | | | |
591| points | | | | | | | | |
592+------------+------+--------+----------+-------+---------+-------------+----------+------------+
593| **output** | | | | | | | | |
594+------------+------+--------+----------+-------+---------+-------------+----------+------------+
595| *assembly* | |v| | | | |x| | |x| | |x| | |x| | |x| |
596+------------+------+--------+----------+-------+---------+-------------+----------+------------+
597| *JIT* | NO | | | **?** | **?** | **?** | **?** | **?** |
598+------------+------+--------+----------+-------+---------+-------------+----------+------------+
599| *obj* | NO | | | **?** | **?** | **?** | **?** | **?** |
600+------------+------+--------+----------+-------+---------+-------------+----------+------------+
601| live | NO | | | **?** | **?** | **?** | **?** | **?** |
602| analysis | | | | | | | | |
603+------------+------+--------+----------+-------+---------+-------------+----------+------------+
604| register | NO | | | **?** | **?** | **?** | **?** | **?** |
605| map | | | | | | | | |
606+------------+------+--------+----------+-------+---------+-------------+----------+------------+
607| \* Derived pointers only pose a hasard to copying collections. |
608+------------+------+--------+----------+-------+---------+-------------+----------+------------+
609| **?** denotes a feature which could be utilized if available. |
610+------------+------+--------+----------+-------+---------+-------------+----------+------------+
611
612To be clear, the collection techniques above are defined as:
613
614Shadow Stack
615 The mutator carefully maintains a linked list of stack roots.
616
617Reference Counting
618 The mutator maintains a reference count for each object and frees an object
619 when its count falls to zero.
620
621Mark-Sweep
622 When the heap is exhausted, the collector marks reachable objects starting
623 from the roots, then deallocates unreachable objects in a sweep phase.
624
625Copying
626 As reachability analysis proceeds, the collector copies objects from one heap
627 area to another, compacting them in the process. Copying collectors enable
628 highly efficient "bump pointer" allocation and can improve locality of
629 reference.
630
631Incremental
632 (Including generational collectors.) Incremental collectors generally have all
633 the properties of a copying collector (regardless of whether the mature heap
634 is compacting), but bring the added complexity of requiring write barriers.
635
636Threaded
637 Denotes a multithreaded mutator; the collector must still stop the mutator
638 ("stop the world") before beginning reachability analysis. Stopping a
639 multithreaded mutator is a complicated problem. It generally requires highly
640 platform specific code in the runtime, and the production of carefully
641 designed machine code at safe points.
642
643Concurrent
644 In this technique, the mutator and the collector run concurrently, with the
645 goal of eliminating pause times. In a *cooperative* collector, the mutator
646 further aids with collection should a pause occur, allowing collection to take
647 advantage of multiprocessor hosts. The "stop the world" problem of threaded
648 collectors is generally still present to a limited extent. Sophisticated
649 marking algorithms are necessary. Read barriers may be necessary.
650
651As the matrix indicates, LLVM's garbage collection infrastructure is already
652suitable for a wide variety of collectors, but does not currently extend to
653multithreaded programs. This will be added in the future as there is
654interest.
655
656.. _stack-map:
657
658Computing stack maps
659--------------------
660
661LLVM automatically computes a stack map. One of the most important features
662of a ``GCStrategy`` is to compile this information into the executable in
663the binary representation expected by the runtime library.
664
665The stack map consists of the location and identity of each GC root in the
666each function in the module. For each root:
667
668* ``RootNum``: The index of the root.
669
670* ``StackOffset``: The offset of the object relative to the frame pointer.
671
672* ``RootMetadata``: The value passed as the ``%metadata`` parameter to the
673 ``@llvm.gcroot`` intrinsic.
674
675Also, for the function as a whole:
676
677* ``getFrameSize()``: The overall size of the function's initial stack frame,
678 not accounting for any dynamic allocation.
679
680* ``roots_size()``: The count of roots in the function.
681
682To access the stack map, use ``GCFunctionMetadata::roots_begin()`` and
683-``end()`` from the :ref:`GCMetadataPrinter <assembly>`:
684
685.. code-block:: c++
686
687 for (iterator I = begin(), E = end(); I != E; ++I) {
688 GCFunctionInfo *FI = *I;
689 unsigned FrameSize = FI->getFrameSize();
690 size_t RootCount = FI->roots_size();
691
692 for (GCFunctionInfo::roots_iterator RI = FI->roots_begin(),
693 RE = FI->roots_end();
694 RI != RE; ++RI) {
695 int RootNum = RI->Num;
696 int RootStackOffset = RI->StackOffset;
697 Constant *RootMetadata = RI->Metadata;
698 }
699 }
700
701If the ``llvm.gcroot`` intrinsic is eliminated before code generation by a
702custom lowering pass, LLVM will compute an empty stack map. This may be useful
703for collector plugins which implement reference counting or a shadow stack.
704
705.. _init-roots:
706
707Initializing roots to null: ``InitRoots``
708-----------------------------------------
709
710.. code-block:: c++
711
712 MyGC::MyGC() {
713 InitRoots = true;
714 }
715
716When set, LLVM will automatically initialize each root to ``null`` upon entry to
717the function. This prevents the GC's sweep phase from visiting uninitialized
718pointers, which will almost certainly cause it to crash. This initialization
719occurs before custom lowering, so the two may be used together.
720
721Since LLVM does not yet compute liveness information, there is no means of
722distinguishing an uninitialized stack root from an initialized one. Therefore,
723this feature should be used by all GC plugins. It is enabled by default.
724
Sean Silva691f4702012-12-09 15:52:47 +0000725Custom lowering of intrinsics: ``CustomRoots``, ``CustomReadBarriers``, and ``CustomWriteBarriers``
726---------------------------------------------------------------------------------------------------
727
728For GCs which use barriers or unusual treatment of stack roots, these flags
729allow the collector to perform arbitrary transformations of the LLVM IR:
730
731.. code-block:: c++
732
733 class MyGC : public GCStrategy {
734 public:
735 MyGC() {
736 CustomRoots = true;
737 CustomReadBarriers = true;
738 CustomWriteBarriers = true;
739 }
740
741 virtual bool initializeCustomLowering(Module &M);
742 virtual bool performCustomLowering(Function &F);
743 };
744
745If any of these flags are set, then LLVM suppresses its default lowering for the
746corresponding intrinsics and instead calls ``performCustomLowering``.
747
748LLVM's default action for each intrinsic is as follows:
749
750* ``llvm.gcroot``: Leave it alone. The code generator must see it or the stack
751 map will not be computed.
752
753* ``llvm.gcread``: Substitute a ``load`` instruction.
754
755* ``llvm.gcwrite``: Substitute a ``store`` instruction.
756
757If ``CustomReadBarriers`` or ``CustomWriteBarriers`` are specified, then
758``performCustomLowering`` **must** eliminate the corresponding barriers.
759
760``performCustomLowering`` must comply with the same restrictions as
Dmitri Gribenkob64f0202012-12-12 17:02:44 +0000761:ref:`FunctionPass::runOnFunction <writing-an-llvm-pass-runOnFunction>`
Sean Silva691f4702012-12-09 15:52:47 +0000762Likewise, ``initializeCustomLowering`` has the same semantics as
Dmitri Gribenkob64f0202012-12-12 17:02:44 +0000763:ref:`Pass::doInitialization(Module&)
764<writing-an-llvm-pass-doInitialization-mod>`
Sean Silva691f4702012-12-09 15:52:47 +0000765
766The following can be used as a template:
767
768.. code-block:: c++
769
770 #include "llvm/Module.h"
771 #include "llvm/IntrinsicInst.h"
772
773 bool MyGC::initializeCustomLowering(Module &M) {
774 return false;
775 }
776
777 bool MyGC::performCustomLowering(Function &F) {
778 bool MadeChange = false;
779
780 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
781 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; )
782 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++))
783 if (Function *F = CI->getCalledFunction())
784 switch (F->getIntrinsicID()) {
785 case Intrinsic::gcwrite:
786 // Handle llvm.gcwrite.
787 CI->eraseFromParent();
788 MadeChange = true;
789 break;
790 case Intrinsic::gcread:
791 // Handle llvm.gcread.
792 CI->eraseFromParent();
793 MadeChange = true;
794 break;
795 case Intrinsic::gcroot:
796 // Handle llvm.gcroot.
797 CI->eraseFromParent();
798 MadeChange = true;
799 break;
800 }
801
802 return MadeChange;
803 }
804
805.. _safe-points:
806
807Generating safe points: ``NeededSafePoints``
808--------------------------------------------
809
810LLVM can compute four kinds of safe points:
811
812.. code-block:: c++
813
814 namespace GC {
815 /// PointKind - The type of a collector-safe point.
816 ///
817 enum PointKind {
818 Loop, //< Instr is a loop (backwards branch).
819 Return, //< Instr is a return instruction.
820 PreCall, //< Instr is a call instruction.
821 PostCall //< Instr is the return address of a call.
822 };
823 }
824
825A collector can request any combination of the four by setting the
826``NeededSafePoints`` mask:
827
828.. code-block:: c++
829
830 MyGC::MyGC() {
831 NeededSafePoints = 1 << GC::Loop
832 | 1 << GC::Return
833 | 1 << GC::PreCall
834 | 1 << GC::PostCall;
835 }
836
837It can then use the following routines to access safe points.
838
839.. code-block:: c++
840
841 for (iterator I = begin(), E = end(); I != E; ++I) {
842 GCFunctionInfo *MD = *I;
843 size_t PointCount = MD->size();
844
845 for (GCFunctionInfo::iterator PI = MD->begin(),
846 PE = MD->end(); PI != PE; ++PI) {
847 GC::PointKind PointKind = PI->Kind;
848 unsigned PointNum = PI->Num;
849 }
850 }
851
852Almost every collector requires ``PostCall`` safe points, since these correspond
853to the moments when the function is suspended during a call to a subroutine.
854
855Threaded programs generally require ``Loop`` safe points to guarantee that the
856application will reach a safe point within a bounded amount of time, even if it
857is executing a long-running loop which contains no function calls.
858
859Threaded collectors may also require ``Return`` and ``PreCall`` safe points to
860implement "stop the world" techniques using self-modifying code, where it is
861important that the program not exit the function without reaching a safe point
862(because only the topmost function has been patched).
863
864.. _assembly:
865
866Emitting assembly code: ``GCMetadataPrinter``
867---------------------------------------------
868
869LLVM allows a plugin to print arbitrary assembly code before and after the rest
870of a module's assembly code. At the end of the module, the GC can compile the
871LLVM stack map into assembly code. (At the beginning, this information is not
872yet computed.)
873
874Since AsmWriter and CodeGen are separate components of LLVM, a separate abstract
875base class and registry is provided for printing assembly code, the
876``GCMetadaPrinter`` and ``GCMetadataPrinterRegistry``. The AsmWriter will look
877for such a subclass if the ``GCStrategy`` sets ``UsesMetadata``:
878
879.. code-block:: c++
880
881 MyGC::MyGC() {
882 UsesMetadata = true;
883 }
884
885This separation allows JIT-only clients to be smaller.
886
887Note that LLVM does not currently have analogous APIs to support code generation
888in the JIT, nor using the object writers.
889
890.. code-block:: c++
891
892 // lib/MyGC/MyGCPrinter.cpp - Example LLVM GC printer
893
894 #include "llvm/CodeGen/GCMetadataPrinter.h"
895 #include "llvm/Support/Compiler.h"
896
897 using namespace llvm;
898
899 namespace {
900 class LLVM_LIBRARY_VISIBILITY MyGCPrinter : public GCMetadataPrinter {
901 public:
902 virtual void beginAssembly(std::ostream &OS, AsmPrinter &AP,
903 const TargetAsmInfo &TAI);
904
905 virtual void finishAssembly(std::ostream &OS, AsmPrinter &AP,
906 const TargetAsmInfo &TAI);
907 };
908
909 GCMetadataPrinterRegistry::Add<MyGCPrinter>
910 X("mygc", "My bespoke garbage collector.");
911 }
912
913The collector should use ``AsmPrinter`` and ``TargetAsmInfo`` to print portable
914assembly code to the ``std::ostream``. The collector itself contains the stack
915map for the entire module, and may access the ``GCFunctionInfo`` using its own
916``begin()`` and ``end()`` methods. Here's a realistic example:
917
918.. code-block:: c++
919
920 #include "llvm/CodeGen/AsmPrinter.h"
921 #include "llvm/Function.h"
922 #include "llvm/Target/TargetMachine.h"
923 #include "llvm/DataLayout.h"
924 #include "llvm/Target/TargetAsmInfo.h"
925
926 void MyGCPrinter::beginAssembly(std::ostream &OS, AsmPrinter &AP,
927 const TargetAsmInfo &TAI) {
928 // Nothing to do.
929 }
930
931 void MyGCPrinter::finishAssembly(std::ostream &OS, AsmPrinter &AP,
932 const TargetAsmInfo &TAI) {
933 // Set up for emitting addresses.
934 const char *AddressDirective;
935 int AddressAlignLog;
936 if (AP.TM.getDataLayout()->getPointerSize() == sizeof(int32_t)) {
937 AddressDirective = TAI.getData32bitsDirective();
938 AddressAlignLog = 2;
939 } else {
940 AddressDirective = TAI.getData64bitsDirective();
941 AddressAlignLog = 3;
942 }
943
944 // Put this in the data section.
945 AP.SwitchToDataSection(TAI.getDataSection());
946
947 // For each function...
948 for (iterator FI = begin(), FE = end(); FI != FE; ++FI) {
949 GCFunctionInfo &MD = **FI;
950
951 // Emit this data structure:
952 //
953 // struct {
954 // int32_t PointCount;
955 // struct {
956 // void *SafePointAddress;
957 // int32_t LiveCount;
958 // int32_t LiveOffsets[LiveCount];
959 // } Points[PointCount];
960 // } __gcmap_<FUNCTIONNAME>;
961
962 // Align to address width.
963 AP.EmitAlignment(AddressAlignLog);
964
965 // Emit the symbol by which the stack map entry can be found.
966 std::string Symbol;
967 Symbol += TAI.getGlobalPrefix();
968 Symbol += "__gcmap_";
969 Symbol += MD.getFunction().getName();
970 if (const char *GlobalDirective = TAI.getGlobalDirective())
971 OS << GlobalDirective << Symbol << "\n";
972 OS << TAI.getGlobalPrefix() << Symbol << ":\n";
973
974 // Emit PointCount.
975 AP.EmitInt32(MD.size());
976 AP.EOL("safe point count");
977
978 // And each safe point...
979 for (GCFunctionInfo::iterator PI = MD.begin(),
980 PE = MD.end(); PI != PE; ++PI) {
981 // Align to address width.
982 AP.EmitAlignment(AddressAlignLog);
983
984 // Emit the address of the safe point.
985 OS << AddressDirective
986 << TAI.getPrivateGlobalPrefix() << "label" << PI->Num;
987 AP.EOL("safe point address");
988
989 // Emit the stack frame size.
990 AP.EmitInt32(MD.getFrameSize());
991 AP.EOL("stack frame size");
992
993 // Emit the number of live roots in the function.
994 AP.EmitInt32(MD.live_size(PI));
995 AP.EOL("live root count");
996
997 // And for each live root...
998 for (GCFunctionInfo::live_iterator LI = MD.live_begin(PI),
999 LE = MD.live_end(PI);
1000 LI != LE; ++LI) {
1001 // Print its offset within the stack frame.
1002 AP.EmitInt32(LI->StackOffset);
1003 AP.EOL("stack offset");
1004 }
1005 }
1006 }
1007 }
1008
1009References
1010==========
1011
1012.. _appel89:
1013
1014[Appel89] Runtime Tags Aren't Necessary. Andrew W. Appel. Lisp and Symbolic
1015Computation 19(7):703-705, July 1989.
1016
1017.. _goldberg91:
1018
1019[Goldberg91] Tag-free garbage collection for strongly typed programming
1020languages. Benjamin Goldberg. ACM SIGPLAN PLDI'91.
1021
1022.. _tolmach94:
1023
1024[Tolmach94] Tag-free garbage collection using explicit type parameters. Andrew
1025Tolmach. Proceedings of the 1994 ACM conference on LISP and functional
1026programming.
1027
1028.. _henderson02:
1029
1030[Henderson2002] `Accurate Garbage Collection in an Uncooperative Environment
1031<http://citeseer.ist.psu.edu/henderson02accurate.html>`__
1032