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