blob: 90099f8283804996db3242d7586fa36987789083 [file] [log] [blame]
Sean Silva18dc5382012-12-09 15:52:47 +00001=====================================
Philip Reamese78cf552015-02-24 19:44:46 +00002Garbage Collection with LLVM
Sean Silva18dc5382012-12-09 15:52:47 +00003=====================================
4
5.. contents::
6 :local:
7
Philip Reames38263192015-02-24 23:34:24 +00008Abstract
9========
Sean Silva18dc5382012-12-09 15:52:47 +000010
Philip Reamese78cf552015-02-24 19:44:46 +000011This document covers how to integrate LLVM into a compiler for a language which
12supports garbage collection. **Note that LLVM itself does not provide a
13garbage collector.** You must provide your own.
14
Philip Reames03f38362015-02-24 23:12:27 +000015Quick Start
16============
Philip Reamese78cf552015-02-24 19:44:46 +000017
Philip Reames03f38362015-02-24 23:12:27 +000018First, you should pick a collector strategy. LLVM includes a number of built
19in ones, but you can also implement a loadable plugin with a custom definition.
20Note that the collector strategy is a description of how LLVM should generate
21code such that it interacts with your collector and runtime, not a description
22of the collector itself.
Philip Reamese78cf552015-02-24 19:44:46 +000023
Philip Reames03f38362015-02-24 23:12:27 +000024Next, mark your generated functions as using your chosen collector strategy.
25From c++, you can call:
Philip Reamese78cf552015-02-24 19:44:46 +000026
27.. code-block:: c++
28
29 F.setGC(<collector description name>);
30
Philip Reamese78cf552015-02-24 19:44:46 +000031
Philip Reames03f38362015-02-24 23:12:27 +000032This will produce IR like the following fragment:
Philip Reamese78cf552015-02-24 19:44:46 +000033
Philip Reames03f38362015-02-24 23:12:27 +000034.. code-block:: llvm
Philip Reamese78cf552015-02-24 19:44:46 +000035
Philip Reames03f38362015-02-24 23:12:27 +000036 define void @foo() gc "<collector description name>" { ... }
Philip Reamese78cf552015-02-24 19:44:46 +000037
38
Philip Reames03f38362015-02-24 23:12:27 +000039When generating LLVM IR for your functions, you will need to:
Philip Reamese78cf552015-02-24 19:44:46 +000040
Philip Reames03f38362015-02-24 23:12:27 +000041* Use ``@llvm.gcread`` and/or ``@llvm.gcwrite`` in place of standard load and
42 store instructions. These intrinsics are used to represent load and store
43 barriers. If you collector does not require such barriers, you can skip
44 this step.
Philip Reamese78cf552015-02-24 19:44:46 +000045
Philip Reames03f38362015-02-24 23:12:27 +000046* Use the memory allocation routines provided by your garbage collector's
47 runtime library.
48
49* If your collector requires them, generate type maps according to your
50 runtime's binary interface. LLVM is not involved in the process. In
51 particular, the LLVM type system is not suitable for conveying such
52 information though the compiler.
53
54* Insert any coordination code required for interacting with your collector.
55 Many collectors require running application code to periodically check a
56 flag and conditionally call a runtime function. This is often referred to
57 as a safepoint poll.
58
59You will need to identify roots (i.e. references to heap objects your collector
60needs to know about) in your generated IR, so that LLVM can encode them into
61your final stack maps. Depending on the collector strategy chosen, this is
62accomplished by using either the ''@llvm.gcroot'' intrinsics or an
63''gc.statepoint'' relocation sequence.
64
65Don't forget to create a root for each intermediate value that is generated when
66evaluating an expression. In ``h(f(), g())``, the result of ``f()`` could
67easily be collected if evaluating ``g()`` triggers a collection.
68
69Finally, you need to link your runtime library with the generated program
70executable (for a static compiler) or ensure the appropriate symbols are
71available for the runtime linker (for a JIT compiler).
Philip Reamese78cf552015-02-24 19:44:46 +000072
Philip Reames38263192015-02-24 23:34:24 +000073
74Introduction
75============
76
Philip Reamese78cf552015-02-24 19:44:46 +000077What is Garbage Collection?
Philip Reames38263192015-02-24 23:34:24 +000078---------------------------
Philip Reamese78cf552015-02-24 19:44:46 +000079
Sean Silva18dc5382012-12-09 15:52:47 +000080Garbage collection is a widely used technique that frees the programmer from
81having to know the lifetimes of heap objects, making software easier to produce
82and maintain. Many programming languages rely on garbage collection for
83automatic memory management. There are two primary forms of garbage collection:
84conservative and accurate.
85
86Conservative garbage collection often does not require any special support from
87either the language or the compiler: it can handle non-type-safe programming
88languages (such as C/C++) and does not require any special information from the
89compiler. The `Boehm collector
90<http://www.hpl.hp.com/personal/Hans_Boehm/gc/>`__ is an example of a
91state-of-the-art conservative collector.
92
93Accurate garbage collection requires the ability to identify all pointers in the
94program at run-time (which requires that the source-language be type-safe in
95most cases). Identifying pointers at run-time requires compiler support to
96locate all places that hold live pointer variables at run-time, including the
97:ref:`processor stack and registers <gcroot>`.
98
99Conservative garbage collection is attractive because it does not require any
100special compiler support, but it does have problems. In particular, because the
101conservative garbage collector cannot *know* that a particular word in the
102machine is a pointer, it cannot move live objects in the heap (preventing the
103use of compacting and generational GC algorithms) and it can occasionally suffer
104from memory leaks due to integer values that happen to point to objects in the
105program. In addition, some aggressive compiler transformations can break
106conservative garbage collectors (though these seem rare in practice).
107
108Accurate garbage collectors do not suffer from any of these problems, but they
109can suffer from degraded scalar optimization of the program. In particular,
110because the runtime must be able to identify and update all pointers active in
111the program, some optimizations are less effective. In practice, however, the
112locality and performance benefits of using aggressive garbage collection
113techniques dominates any low-level losses.
114
115This document describes the mechanisms and interfaces provided by LLVM to
116support accurate garbage collection.
117
Sean Silva18dc5382012-12-09 15:52:47 +0000118Goals and non-goals
119-------------------
120
121LLVM's intermediate representation provides :ref:`garbage collection intrinsics
122<gc_intrinsics>` that offer support for a broad class of collector models. For
123instance, the intrinsics permit:
124
125* semi-space collectors
126
127* mark-sweep collectors
128
129* generational collectors
130
Sean Silva18dc5382012-12-09 15:52:47 +0000131* incremental collectors
132
133* concurrent collectors
134
135* cooperative collectors
136
Philip Reames38263192015-02-24 23:34:24 +0000137* reference counting
Sean Silva18dc5382012-12-09 15:52:47 +0000138
Philip Reames38263192015-02-24 23:34:24 +0000139We hope that the support built into the LLVM IR is sufficient to support a
140broad class of garbage collected languages including Scheme, ML, Java, C#,
141Perl, Python, Lua, Ruby, other scripting languages, and more.
142
143Note that LLVM **does not itself provide a garbage collector** --- this should
144be part of your language's runtime library. LLVM provides a framework for
145describing the garbage collectors requirements to the compiler. In particular,
146LLVM provides support for generating stack maps at call sites, polling for a
147safepoint, and emitting load and store barriers. You can also extend LLVM -
148possibly through a loadable :ref:`code generation plugins <plugin>` - to
Sean Silva18dc5382012-12-09 15:52:47 +0000149generate code and data structures which conforms to the *binary interface*
150specified by the *runtime library*. This is similar to the relationship between
151LLVM and DWARF debugging info, for example. The difference primarily lies in
152the lack of an established standard in the domain of garbage collection --- thus
Philip Reames38263192015-02-24 23:34:24 +0000153the need for a flexible extension mechanism.
Sean Silva18dc5382012-12-09 15:52:47 +0000154
155The aspects of the binary interface with which LLVM's GC support is
156concerned are:
157
Philip Reames38263192015-02-24 23:34:24 +0000158* Creation of GC safepoints within code where collection is allowed to execute
Sean Silva18dc5382012-12-09 15:52:47 +0000159 safely.
160
161* Computation of the stack map. For each safe point in the code, object
162 references within the stack frame must be identified so that the collector may
163 traverse and perhaps update them.
164
165* Write barriers when storing object references to the heap. These are commonly
166 used to optimize incremental scans in generational collectors.
167
168* Emission of read barriers when loading object references. These are useful
169 for interoperating with concurrent collectors.
170
171There are additional areas that LLVM does not directly address:
172
173* Registration of global roots with the runtime.
174
175* Registration of stack map entries with the runtime.
176
177* The functions used by the program to allocate memory, trigger a collection,
178 etc.
179
180* Computation or compilation of type maps, or registration of them with the
181 runtime. These are used to crawl the heap for object references.
182
183In general, LLVM's support for GC does not include features which can be
184adequately addressed with other features of the IR and does not specify a
185particular binary interface. On the plus side, this means that you should be
Philip Reames38263192015-02-24 23:34:24 +0000186able to integrate LLVM with an existing runtime. On the other hand, it can
187have the effect of leaving a lot of work for the developer of a novel
188language. We try to mitigate this by providing built in collector strategy
189descriptions that can work with many common collector designs and easy
190extension points. If you don't already have a specific binary interface
191you need to support, we recommend trying to use one of these built in collector
192strategies.
Philip Reames03f38362015-02-24 23:12:27 +0000193
Sean Silva18dc5382012-12-09 15:52:47 +0000194.. _gc_intrinsics:
195
Philip Reames03f38362015-02-24 23:12:27 +0000196LLVM IR Features
197================
Sean Silva18dc5382012-12-09 15:52:47 +0000198
199This section describes the garbage collection facilities provided by the
200:doc:`LLVM intermediate representation <LangRef>`. The exact behavior of these
201IR features is specified by the binary interface implemented by a :ref:`code
202generation plugin <plugin>`, not by this document.
203
204These facilities are limited to those strictly necessary; they are not intended
205to be a complete interface to any garbage collector. A program will need to
206interface with the GC library using the facilities provided by that program.
207
Sean Silva18dc5382012-12-09 15:52:47 +0000208Specifying GC code generation: ``gc "..."``
209-------------------------------------------
210
211.. code-block:: llvm
212
213 define ty @name(...) gc "name" { ...
214
215The ``gc`` function attribute is used to specify the desired GC style to the
216compiler. Its programmatic equivalent is the ``setGC`` method of ``Function``.
217
218Setting ``gc "name"`` on a function triggers a search for a matching code
219generation plugin "*name*"; it is that plugin which defines the exact nature of
220the code generated to support GC. If none is found, the compiler will raise an
221error.
222
223Specifying the GC style on a per-function basis allows LLVM to link together
224programs that use different garbage collection algorithms (or none at all).
225
226.. _gcroot:
227
228Identifying GC roots on the stack: ``llvm.gcroot``
229--------------------------------------------------
230
231.. code-block:: llvm
232
233 void @llvm.gcroot(i8** %ptrloc, i8* %metadata)
234
235The ``llvm.gcroot`` intrinsic is used to inform LLVM that a stack variable
236references an object on the heap and is to be tracked for garbage collection.
237The exact impact on generated code is specified by a :ref:`compiler plugin
238<plugin>`. All calls to ``llvm.gcroot`` **must** reside inside the first basic
239block.
240
241A compiler which uses mem2reg to raise imperative code using ``alloca`` into SSA
242form need only add a call to ``@llvm.gcroot`` for those variables which a
243pointers into the GC heap.
244
245It is also important to mark intermediate values with ``llvm.gcroot``. For
246example, consider ``h(f(), g())``. Beware leaking the result of ``f()`` in the
247case that ``g()`` triggers a collection. Note, that stack variables must be
248initialized and marked with ``llvm.gcroot`` in function's prologue.
249
250The first argument **must** be a value referring to an alloca instruction or a
251bitcast of an alloca. The second contains a pointer to metadata that should be
252associated with the pointer, and **must** be a constant or global value
253address. If your target collector uses tags, use a null pointer for metadata.
254
255The ``%metadata`` argument can be used to avoid requiring heap objects to have
256'isa' pointers or tag bits. [Appel89_, Goldberg91_, Tolmach94_] If specified,
257its value will be tracked along with the location of the pointer in the stack
258frame.
259
260Consider the following fragment of Java code:
261
262.. code-block:: java
263
264 {
265 Object X; // A null-initialized reference to an object
266 ...
267 }
268
269This block (which may be located in the middle of a function or in a loop nest),
270could be compiled to this LLVM code:
271
272.. code-block:: llvm
273
274 Entry:
275 ;; In the entry block for the function, allocate the
276 ;; stack space for X, which is an LLVM pointer.
277 %X = alloca %Object*
278
279 ;; Tell LLVM that the stack space is a stack root.
280 ;; Java has type-tags on objects, so we pass null as metadata.
281 %tmp = bitcast %Object** %X to i8**
282 call void @llvm.gcroot(i8** %tmp, i8* null)
283 ...
284
285 ;; "CodeBlock" is the block corresponding to the start
286 ;; of the scope above.
287 CodeBlock:
288 ;; Java null-initializes pointers.
289 store %Object* null, %Object** %X
290
291 ...
292
293 ;; As the pointer goes out of scope, store a null value into
294 ;; it, to indicate that the value is no longer live.
295 store %Object* null, %Object** %X
296 ...
297
Sean Silva18dc5382012-12-09 15:52:47 +0000298Reading and writing references in the heap
299------------------------------------------
300
301Some collectors need to be informed when the mutator (the program that needs
302garbage collection) either reads a pointer from or writes a pointer to a field
303of a heap object. The code fragments inserted at these points are called *read
304barriers* and *write barriers*, respectively. The amount of code that needs to
305be executed is usually quite small and not on the critical path of any
306computation, so the overall performance impact of the barrier is tolerable.
307
308Barriers often require access to the *object pointer* rather than the *derived
309pointer* (which is a pointer to the field within the object). Accordingly,
310these intrinsics take both pointers as separate arguments for completeness. In
311this snippet, ``%object`` is the object pointer, and ``%derived`` is the derived
312pointer:
313
314.. code-block:: llvm
315
316 ;; An array type.
317 %class.Array = type { %class.Object, i32, [0 x %class.Object*] }
318 ...
319
320 ;; Load the object pointer from a gcroot.
321 %object = load %class.Array** %object_addr
322
323 ;; Compute the derived pointer.
324 %derived = getelementptr %object, i32 0, i32 2, i32 %n
325
326LLVM does not enforce this relationship between the object and derived pointer
Dmitri Gribenko134f76a2012-12-11 23:35:23 +0000327(although a :ref:`plugin <plugin>` might). However, it would be an unusual
328collector that violated it.
Sean Silva18dc5382012-12-09 15:52:47 +0000329
330The use of these intrinsics is naturally optional if the target GC does require
331the corresponding barrier. Such a GC plugin will replace the intrinsic calls
332with the corresponding ``load`` or ``store`` instruction if they are used.
333
Sean Silva18dc5382012-12-09 15:52:47 +0000334Write barrier: ``llvm.gcwrite``
335^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
336
337.. code-block:: llvm
338
339 void @llvm.gcwrite(i8* %value, i8* %object, i8** %derived)
340
341For write barriers, LLVM provides the ``llvm.gcwrite`` intrinsic function. It
342has exactly the same semantics as a non-volatile ``store`` to the derived
343pointer (the third argument). The exact code generated is specified by a
Dmitri Gribenko134f76a2012-12-11 23:35:23 +0000344compiler :ref:`plugin <plugin>`.
Sean Silva18dc5382012-12-09 15:52:47 +0000345
346Many important algorithms require write barriers, including generational and
347concurrent collectors. Additionally, write barriers could be used to implement
348reference counting.
349
Sean Silva18dc5382012-12-09 15:52:47 +0000350Read barrier: ``llvm.gcread``
351^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
352
353.. code-block:: llvm
354
355 i8* @llvm.gcread(i8* %object, i8** %derived)
356
357For read barriers, LLVM provides the ``llvm.gcread`` intrinsic function. It has
358exactly the same semantics as a non-volatile ``load`` from the derived pointer
Dmitri Gribenko134f76a2012-12-11 23:35:23 +0000359(the second argument). The exact code generated is specified by a
360:ref:`compiler plugin <plugin>`.
Sean Silva18dc5382012-12-09 15:52:47 +0000361
362Read barriers are needed by fewer algorithms than write barriers, and may have a
363greater performance impact since pointer reads are more frequent than writes.
364
365.. _plugin:
366
Philip Reamese78cf552015-02-24 19:44:46 +0000367Built In Collectors
368====================
369
370LLVM includes built in support for several varieties of garbage collectors.
371
372The Shadow Stack GC
373----------------------
374
375To use this collector strategy, mark your functions with:
376
377.. code-block:: c++
378
379 F.setGC("shadow-stack");
380
381Unlike many GC algorithms which rely on a cooperative code generator to compile
382stack maps, this algorithm carefully maintains a linked list of stack roots
383[:ref:`Henderson2002 <henderson02>`]. This so-called "shadow stack" mirrors the
384machine stack. Maintaining this data structure is slower than using a stack map
385compiled into the executable as constant data, but has a significant portability
386advantage because it requires no special support from the target code generator,
387and does not require tricky platform-specific code to crawl the machine stack.
388
389The tradeoff for this simplicity and portability is:
390
391* High overhead per function call.
392
393* Not thread-safe.
394
395Still, it's an easy way to get started. After your compiler and runtime are up
396and running, writing a :ref:`plugin <plugin>` will allow you to take advantage
397of :ref:`more advanced GC features <collector-algos>` of LLVM in order to
398improve performance.
399
Philip Reames03f38362015-02-24 23:12:27 +0000400
401The shadow stack doesn't imply a memory allocation algorithm. A semispace
402collector or building atop ``malloc`` are great places to start, and can be
403implemented with very little code.
404
405When it comes time to collect, however, your runtime needs to traverse the stack
406roots, and for this it needs to integrate with the shadow stack. Luckily, doing
407so is very simple. (This code is heavily commented to help you understand the
408data structure, but there are only 20 lines of meaningful code.)
409
410.. code-block:: c++
411
412 /// @brief The map for a single function's stack frame. One of these is
413 /// compiled as constant data into the executable for each function.
414 ///
415 /// Storage of metadata values is elided if the %metadata parameter to
416 /// @llvm.gcroot is null.
417 struct FrameMap {
418 int32_t NumRoots; //< Number of roots in stack frame.
419 int32_t NumMeta; //< Number of metadata entries. May be < NumRoots.
420 const void *Meta[0]; //< Metadata for each root.
421 };
422
423 /// @brief A link in the dynamic shadow stack. One of these is embedded in
424 /// the stack frame of each function on the call stack.
425 struct StackEntry {
426 StackEntry *Next; //< Link to next stack entry (the caller's).
427 const FrameMap *Map; //< Pointer to constant FrameMap.
428 void *Roots[0]; //< Stack roots (in-place array).
429 };
430
431 /// @brief The head of the singly-linked list of StackEntries. Functions push
432 /// and pop onto this in their prologue and epilogue.
433 ///
434 /// Since there is only a global list, this technique is not threadsafe.
435 StackEntry *llvm_gc_root_chain;
436
437 /// @brief Calls Visitor(root, meta) for each GC root on the stack.
438 /// root and meta are exactly the values passed to
439 /// @llvm.gcroot.
440 ///
441 /// Visitor could be a function to recursively mark live objects. Or it
442 /// might copy them to another heap or generation.
443 ///
444 /// @param Visitor A function to invoke for every GC root on the stack.
445 void visitGCRoots(void (*Visitor)(void **Root, const void *Meta)) {
446 for (StackEntry *R = llvm_gc_root_chain; R; R = R->Next) {
447 unsigned i = 0;
448
449 // For roots [0, NumMeta), the metadata pointer is in the FrameMap.
450 for (unsigned e = R->Map->NumMeta; i != e; ++i)
451 Visitor(&R->Roots[i], R->Map->Meta[i]);
452
453 // For roots [NumMeta, NumRoots), the metadata pointer is null.
454 for (unsigned e = R->Map->NumRoots; i != e; ++i)
455 Visitor(&R->Roots[i], NULL);
456 }
457 }
458
459
Philip Reamese78cf552015-02-24 19:44:46 +0000460The 'Erlang' and 'Ocaml' GCs
461-----------------------------
462
463LLVM ships with two example collectors which leverage the ''gcroot''
464mechanisms. To our knowledge, these are not actually used by any language
465runtime, but they do provide a reasonable starting point for someone interested
466in writing an ''gcroot' compatible GC plugin. In particular, these are the
467only in tree examples of how to produce a custom binary stack map format using
468a ''gcroot'' strategy.
469
470As there names imply, the binary format produced is intended to model that
471used by the Erlang and OCaml compilers respectively.
472
473
474The Statepoint Example GC
475-------------------------
476
477.. code-block:: c++
478
479 F.setGC("statepoint-example");
480
481This GC provides an example of how one might use the infrastructure provided
482by ''gc.statepoint''.
483
484
Philip Reames03f38362015-02-24 23:12:27 +0000485Custom GC Strategies
486====================
487
488If none of the built in GC strategy descriptions met your needs above, you will
489need to define a custom GCStrategy and possibly, a custom LLVM pass to perform
490lowering. Your best example of where to start defining a custom GCStrategy
491would be to look at one of the built in strategies.
492
493You may be able to structure this additional code as a loadable plugin library.
494Loadable plugins are sufficient if all you need is to enable a different
495combination of built in functionality, but if you need to provide a custom
496lowering pass, you will need to build a patched version of LLVM. If you think
497you need a patched build, please ask for advice on llvm-dev. There may be an
498easy way we can extend the support to make it work for your use case without
499requiring a custom build.
500
Philip Reames38263192015-02-24 23:34:24 +0000501Collector Requirements
502----------------------
503
504You should be able to leverage any existing collector library that includes the following elements:
505
506#. A memory allocator which exposes an allocation function your compiled
507 code can call.
508
509#. A binary format for the stack map. A stack map describes the location
510 of references at a safepoint and is used by precise collectors to identify
511 references within a stack frame on the machine stack. Note that collectors
512 which conservatively scan the stack don't require such a structure.
513
514#. A stack crawler to discover functions on the call stack, and enumerate the
515 references listed in the stack map for each call site.
516
517#. A mechanism for identifying references in global locations (e.g. global
518 variables).
519
520#. If you collector requires them, an LLVM IR implementation of your collectors
521 load and store barriers. Note that since many collectors don't require
522 barriers at all, LLVM defaults to lowering such barriers to normal loads
523 and stores unless you arrange otherwise.
524
Philip Reames03f38362015-02-24 23:12:27 +0000525
Sean Silva18dc5382012-12-09 15:52:47 +0000526Implementing a collector plugin
Philip Reames03f38362015-02-24 23:12:27 +0000527-------------------------------
Sean Silva18dc5382012-12-09 15:52:47 +0000528
529User code specifies which GC code generation to use with the ``gc`` function
530attribute or, equivalently, with the ``setGC`` method of ``Function``.
531
532To implement a GC plugin, it is necessary to subclass ``llvm::GCStrategy``,
533which can be accomplished in a few lines of boilerplate code. LLVM's
534infrastructure provides access to several important algorithms. For an
535uncontroversial collector, all that remains may be to compile LLVM's computed
536stack map to assembly code (using the binary representation expected by the
537runtime library). This can be accomplished in about 100 lines of code.
538
539This is not the appropriate place to implement a garbage collected heap or a
540garbage collector itself. That code should exist in the language's runtime
541library. The compiler plugin is responsible for generating code which conforms
542to the binary interface defined by library, most essentially the :ref:`stack map
543<stack-map>`.
544
545To subclass ``llvm::GCStrategy`` and register it with the compiler:
546
547.. code-block:: c++
548
549 // lib/MyGC/MyGC.cpp - Example LLVM GC plugin
550
551 #include "llvm/CodeGen/GCStrategy.h"
552 #include "llvm/CodeGen/GCMetadata.h"
553 #include "llvm/Support/Compiler.h"
554
555 using namespace llvm;
556
557 namespace {
558 class LLVM_LIBRARY_VISIBILITY MyGC : public GCStrategy {
559 public:
560 MyGC() {}
561 };
562
563 GCRegistry::Add<MyGC>
564 X("mygc", "My bespoke garbage collector.");
565 }
566
567This boilerplate collector does nothing. More specifically:
568
569* ``llvm.gcread`` calls are replaced with the corresponding ``load``
570 instruction.
571
572* ``llvm.gcwrite`` calls are replaced with the corresponding ``store``
573 instruction.
574
575* No safe points are added to the code.
576
577* The stack map is not compiled into the executable.
578
Rafael Espindola730df072014-03-12 22:40:22 +0000579Using the LLVM makefiles, this code
Sean Silva18dc5382012-12-09 15:52:47 +0000580can be compiled as a plugin using a simple makefile:
581
582.. code-block:: make
583
584 # lib/MyGC/Makefile
585
586 LEVEL := ../..
587 LIBRARYNAME = MyGC
588 LOADABLE_MODULE = 1
589
590 include $(LEVEL)/Makefile.common
591
592Once the plugin is compiled, code using it may be compiled using ``llc
593-load=MyGC.so`` (though MyGC.so may have some other platform-specific
594extension):
595
596::
597
598 $ cat sample.ll
599 define void @f() gc "mygc" {
600 entry:
Bill Wendling547a7af2013-10-18 23:09:06 +0000601 ret void
Sean Silva18dc5382012-12-09 15:52:47 +0000602 }
603 $ llvm-as < sample.ll | llc -load=MyGC.so
604
605It is also possible to statically link the collector plugin into tools, such as
606a language-specific compiler front-end.
607
608.. _collector-algos:
609
610Overview of available features
611------------------------------
612
613``GCStrategy`` provides a range of features through which a plugin may do useful
614work. Some of these are callbacks, some are algorithms that can be enabled,
615disabled, or customized. This matrix summarizes the supported (and planned)
616features and correlates them with the collection techniques which typically
617require them.
618
619.. |v| unicode:: 0x2714
620 :trim:
621
622.. |x| unicode:: 0x2718
623 :trim:
624
625+------------+------+--------+----------+-------+---------+-------------+----------+------------+
626| Algorithm | Done | Shadow | refcount | mark- | copying | incremental | threaded | concurrent |
627| | | stack | | sweep | | | | |
628+============+======+========+==========+=======+=========+=============+==========+============+
629| stack map | |v| | | | |x| | |x| | |x| | |x| | |x| |
630+------------+------+--------+----------+-------+---------+-------------+----------+------------+
631| initialize | |v| | |x| | |x| | |x| | |x| | |x| | |x| | |x| |
632| roots | | | | | | | | |
633+------------+------+--------+----------+-------+---------+-------------+----------+------------+
634| derived | NO | | | | | | **N**\* | **N**\* |
635| pointers | | | | | | | | |
636+------------+------+--------+----------+-------+---------+-------------+----------+------------+
637| **custom | |v| | | | | | | | |
638| lowering** | | | | | | | | |
639+------------+------+--------+----------+-------+---------+-------------+----------+------------+
640| *gcroot* | |v| | |x| | |x| | | | | | |
641+------------+------+--------+----------+-------+---------+-------------+----------+------------+
642| *gcwrite* | |v| | | |x| | | | |x| | | |x| |
643+------------+------+--------+----------+-------+---------+-------------+----------+------------+
644| *gcread* | |v| | | | | | | | |x| |
645+------------+------+--------+----------+-------+---------+-------------+----------+------------+
646| **safe | | | | | | | | |
647| points** | | | | | | | | |
648+------------+------+--------+----------+-------+---------+-------------+----------+------------+
649| *in | |v| | | | |x| | |x| | |x| | |x| | |x| |
650| calls* | | | | | | | | |
651+------------+------+--------+----------+-------+---------+-------------+----------+------------+
652| *before | |v| | | | | | | |x| | |x| |
653| calls* | | | | | | | | |
654+------------+------+--------+----------+-------+---------+-------------+----------+------------+
655| *for | NO | | | | | | **N** | **N** |
656| loops* | | | | | | | | |
657+------------+------+--------+----------+-------+---------+-------------+----------+------------+
658| *before | |v| | | | | | | |x| | |x| |
659| escape* | | | | | | | | |
660+------------+------+--------+----------+-------+---------+-------------+----------+------------+
661| emit code | NO | | | | | | **N** | **N** |
662| at safe | | | | | | | | |
663| points | | | | | | | | |
664+------------+------+--------+----------+-------+---------+-------------+----------+------------+
665| **output** | | | | | | | | |
666+------------+------+--------+----------+-------+---------+-------------+----------+------------+
667| *assembly* | |v| | | | |x| | |x| | |x| | |x| | |x| |
668+------------+------+--------+----------+-------+---------+-------------+----------+------------+
669| *JIT* | NO | | | **?** | **?** | **?** | **?** | **?** |
670+------------+------+--------+----------+-------+---------+-------------+----------+------------+
671| *obj* | NO | | | **?** | **?** | **?** | **?** | **?** |
672+------------+------+--------+----------+-------+---------+-------------+----------+------------+
673| live | NO | | | **?** | **?** | **?** | **?** | **?** |
674| analysis | | | | | | | | |
675+------------+------+--------+----------+-------+---------+-------------+----------+------------+
676| register | NO | | | **?** | **?** | **?** | **?** | **?** |
677| map | | | | | | | | |
678+------------+------+--------+----------+-------+---------+-------------+----------+------------+
679| \* Derived pointers only pose a hasard to copying collections. |
680+------------+------+--------+----------+-------+---------+-------------+----------+------------+
681| **?** denotes a feature which could be utilized if available. |
682+------------+------+--------+----------+-------+---------+-------------+----------+------------+
683
684To be clear, the collection techniques above are defined as:
685
686Shadow Stack
687 The mutator carefully maintains a linked list of stack roots.
688
689Reference Counting
690 The mutator maintains a reference count for each object and frees an object
691 when its count falls to zero.
692
693Mark-Sweep
694 When the heap is exhausted, the collector marks reachable objects starting
695 from the roots, then deallocates unreachable objects in a sweep phase.
696
697Copying
698 As reachability analysis proceeds, the collector copies objects from one heap
699 area to another, compacting them in the process. Copying collectors enable
700 highly efficient "bump pointer" allocation and can improve locality of
701 reference.
702
703Incremental
704 (Including generational collectors.) Incremental collectors generally have all
705 the properties of a copying collector (regardless of whether the mature heap
706 is compacting), but bring the added complexity of requiring write barriers.
707
708Threaded
709 Denotes a multithreaded mutator; the collector must still stop the mutator
710 ("stop the world") before beginning reachability analysis. Stopping a
711 multithreaded mutator is a complicated problem. It generally requires highly
Alp Tokercf218752014-06-30 18:57:16 +0000712 platform-specific code in the runtime, and the production of carefully
Sean Silva18dc5382012-12-09 15:52:47 +0000713 designed machine code at safe points.
714
715Concurrent
716 In this technique, the mutator and the collector run concurrently, with the
717 goal of eliminating pause times. In a *cooperative* collector, the mutator
718 further aids with collection should a pause occur, allowing collection to take
719 advantage of multiprocessor hosts. The "stop the world" problem of threaded
720 collectors is generally still present to a limited extent. Sophisticated
721 marking algorithms are necessary. Read barriers may be necessary.
722
723As the matrix indicates, LLVM's garbage collection infrastructure is already
724suitable for a wide variety of collectors, but does not currently extend to
725multithreaded programs. This will be added in the future as there is
726interest.
727
728.. _stack-map:
729
730Computing stack maps
731--------------------
732
733LLVM automatically computes a stack map. One of the most important features
734of a ``GCStrategy`` is to compile this information into the executable in
735the binary representation expected by the runtime library.
736
737The stack map consists of the location and identity of each GC root in the
738each function in the module. For each root:
739
740* ``RootNum``: The index of the root.
741
742* ``StackOffset``: The offset of the object relative to the frame pointer.
743
744* ``RootMetadata``: The value passed as the ``%metadata`` parameter to the
745 ``@llvm.gcroot`` intrinsic.
746
747Also, for the function as a whole:
748
749* ``getFrameSize()``: The overall size of the function's initial stack frame,
750 not accounting for any dynamic allocation.
751
752* ``roots_size()``: The count of roots in the function.
753
754To access the stack map, use ``GCFunctionMetadata::roots_begin()`` and
755-``end()`` from the :ref:`GCMetadataPrinter <assembly>`:
756
757.. code-block:: c++
758
759 for (iterator I = begin(), E = end(); I != E; ++I) {
760 GCFunctionInfo *FI = *I;
761 unsigned FrameSize = FI->getFrameSize();
762 size_t RootCount = FI->roots_size();
763
764 for (GCFunctionInfo::roots_iterator RI = FI->roots_begin(),
765 RE = FI->roots_end();
766 RI != RE; ++RI) {
767 int RootNum = RI->Num;
768 int RootStackOffset = RI->StackOffset;
769 Constant *RootMetadata = RI->Metadata;
770 }
771 }
772
773If the ``llvm.gcroot`` intrinsic is eliminated before code generation by a
774custom lowering pass, LLVM will compute an empty stack map. This may be useful
775for collector plugins which implement reference counting or a shadow stack.
776
777.. _init-roots:
778
779Initializing roots to null: ``InitRoots``
780-----------------------------------------
781
782.. code-block:: c++
783
784 MyGC::MyGC() {
785 InitRoots = true;
786 }
787
788When set, LLVM will automatically initialize each root to ``null`` upon entry to
789the function. This prevents the GC's sweep phase from visiting uninitialized
790pointers, which will almost certainly cause it to crash. This initialization
791occurs before custom lowering, so the two may be used together.
792
793Since LLVM does not yet compute liveness information, there is no means of
794distinguishing an uninitialized stack root from an initialized one. Therefore,
795this feature should be used by all GC plugins. It is enabled by default.
796
Sean Silva18dc5382012-12-09 15:52:47 +0000797Custom lowering of intrinsics: ``CustomRoots``, ``CustomReadBarriers``, and ``CustomWriteBarriers``
798---------------------------------------------------------------------------------------------------
799
Philip Reames23cf2e22015-01-28 19:28:03 +0000800For GCs which use barriers or unusual treatment of stack roots, these
801flags allow the collector to perform arbitrary transformations of the
802LLVM IR:
Sean Silva18dc5382012-12-09 15:52:47 +0000803
804.. code-block:: c++
805
806 class MyGC : public GCStrategy {
807 public:
808 MyGC() {
809 CustomRoots = true;
810 CustomReadBarriers = true;
811 CustomWriteBarriers = true;
812 }
Sean Silva18dc5382012-12-09 15:52:47 +0000813 };
814
Philip Reames23cf2e22015-01-28 19:28:03 +0000815If any of these flags are set, LLVM suppresses its default lowering for
816the corresponding intrinsics. Instead, you must provide a custom Pass
817which lowers the intrinsics as desired. If you have opted in to custom
818lowering of a particular intrinsic your pass **must** eliminate all
819instances of the corresponding intrinsic in functions which opt in to
820your GC. The best example of such a pass is the ShadowStackGC and it's
821ShadowStackGCLowering pass.
Sean Silva18dc5382012-12-09 15:52:47 +0000822
Philip Reames23cf2e22015-01-28 19:28:03 +0000823There is currently no way to register such a custom lowering pass
824without building a custom copy of LLVM.
Sean Silva18dc5382012-12-09 15:52:47 +0000825
826.. _safe-points:
827
828Generating safe points: ``NeededSafePoints``
829--------------------------------------------
830
831LLVM can compute four kinds of safe points:
832
833.. code-block:: c++
834
835 namespace GC {
836 /// PointKind - The type of a collector-safe point.
837 ///
838 enum PointKind {
839 Loop, //< Instr is a loop (backwards branch).
840 Return, //< Instr is a return instruction.
841 PreCall, //< Instr is a call instruction.
842 PostCall //< Instr is the return address of a call.
843 };
844 }
845
846A collector can request any combination of the four by setting the
847``NeededSafePoints`` mask:
848
849.. code-block:: c++
850
851 MyGC::MyGC() {
852 NeededSafePoints = 1 << GC::Loop
853 | 1 << GC::Return
854 | 1 << GC::PreCall
855 | 1 << GC::PostCall;
856 }
857
858It can then use the following routines to access safe points.
859
860.. code-block:: c++
861
862 for (iterator I = begin(), E = end(); I != E; ++I) {
863 GCFunctionInfo *MD = *I;
864 size_t PointCount = MD->size();
865
866 for (GCFunctionInfo::iterator PI = MD->begin(),
867 PE = MD->end(); PI != PE; ++PI) {
868 GC::PointKind PointKind = PI->Kind;
869 unsigned PointNum = PI->Num;
870 }
871 }
872
873Almost every collector requires ``PostCall`` safe points, since these correspond
874to the moments when the function is suspended during a call to a subroutine.
875
876Threaded programs generally require ``Loop`` safe points to guarantee that the
877application will reach a safe point within a bounded amount of time, even if it
878is executing a long-running loop which contains no function calls.
879
880Threaded collectors may also require ``Return`` and ``PreCall`` safe points to
881implement "stop the world" techniques using self-modifying code, where it is
882important that the program not exit the function without reaching a safe point
883(because only the topmost function has been patched).
884
885.. _assembly:
886
887Emitting assembly code: ``GCMetadataPrinter``
888---------------------------------------------
889
890LLVM allows a plugin to print arbitrary assembly code before and after the rest
891of a module's assembly code. At the end of the module, the GC can compile the
892LLVM stack map into assembly code. (At the beginning, this information is not
893yet computed.)
894
895Since AsmWriter and CodeGen are separate components of LLVM, a separate abstract
896base class and registry is provided for printing assembly code, the
897``GCMetadaPrinter`` and ``GCMetadataPrinterRegistry``. The AsmWriter will look
898for such a subclass if the ``GCStrategy`` sets ``UsesMetadata``:
899
900.. code-block:: c++
901
902 MyGC::MyGC() {
903 UsesMetadata = true;
904 }
905
906This separation allows JIT-only clients to be smaller.
907
908Note that LLVM does not currently have analogous APIs to support code generation
909in the JIT, nor using the object writers.
910
911.. code-block:: c++
912
913 // lib/MyGC/MyGCPrinter.cpp - Example LLVM GC printer
914
915 #include "llvm/CodeGen/GCMetadataPrinter.h"
916 #include "llvm/Support/Compiler.h"
917
918 using namespace llvm;
919
920 namespace {
921 class LLVM_LIBRARY_VISIBILITY MyGCPrinter : public GCMetadataPrinter {
922 public:
Bill Wendling547a7af2013-10-18 23:09:06 +0000923 virtual void beginAssembly(AsmPrinter &AP);
Sean Silva18dc5382012-12-09 15:52:47 +0000924
Bill Wendling547a7af2013-10-18 23:09:06 +0000925 virtual void finishAssembly(AsmPrinter &AP);
Sean Silva18dc5382012-12-09 15:52:47 +0000926 };
927
928 GCMetadataPrinterRegistry::Add<MyGCPrinter>
929 X("mygc", "My bespoke garbage collector.");
930 }
931
Bill Wendling0b55b4a2013-10-18 23:11:25 +0000932The collector should use ``AsmPrinter`` to print portable assembly code. The
933collector itself contains the stack map for the entire module, and may access
934the ``GCFunctionInfo`` using its own ``begin()`` and ``end()`` methods. Here's
935a realistic example:
Sean Silva18dc5382012-12-09 15:52:47 +0000936
937.. code-block:: c++
938
939 #include "llvm/CodeGen/AsmPrinter.h"
Benjamin Kramer9f566a52013-07-08 19:59:35 +0000940 #include "llvm/IR/Function.h"
941 #include "llvm/IR/DataLayout.h"
Sean Silva18dc5382012-12-09 15:52:47 +0000942 #include "llvm/Target/TargetAsmInfo.h"
Benjamin Kramer9f566a52013-07-08 19:59:35 +0000943 #include "llvm/Target/TargetMachine.h"
Sean Silva18dc5382012-12-09 15:52:47 +0000944
Bill Wendling547a7af2013-10-18 23:09:06 +0000945 void MyGCPrinter::beginAssembly(AsmPrinter &AP) {
Sean Silva18dc5382012-12-09 15:52:47 +0000946 // Nothing to do.
947 }
948
Bill Wendling547a7af2013-10-18 23:09:06 +0000949 void MyGCPrinter::finishAssembly(AsmPrinter &AP) {
950 MCStreamer &OS = AP.OutStreamer;
Eric Christopherd9134482014-08-04 21:25:23 +0000951 unsigned IntPtrSize = AP.TM.getSubtargetImpl()->getDataLayout()->getPointerSize();
Sean Silva18dc5382012-12-09 15:52:47 +0000952
953 // Put this in the data section.
Bill Wendling547a7af2013-10-18 23:09:06 +0000954 OS.SwitchSection(AP.getObjFileLowering().getDataSection());
Sean Silva18dc5382012-12-09 15:52:47 +0000955
956 // For each function...
957 for (iterator FI = begin(), FE = end(); FI != FE; ++FI) {
958 GCFunctionInfo &MD = **FI;
959
Bill Wendling547a7af2013-10-18 23:09:06 +0000960 // A compact GC layout. Emit this data structure:
Sean Silva18dc5382012-12-09 15:52:47 +0000961 //
962 // struct {
963 // int32_t PointCount;
Bill Wendling547a7af2013-10-18 23:09:06 +0000964 // void *SafePointAddress[PointCount];
965 // int32_t StackFrameSize; // in words
966 // int32_t StackArity;
967 // int32_t LiveCount;
968 // int32_t LiveOffsets[LiveCount];
Sean Silva18dc5382012-12-09 15:52:47 +0000969 // } __gcmap_<FUNCTIONNAME>;
970
971 // Align to address width.
Bill Wendling547a7af2013-10-18 23:09:06 +0000972 AP.EmitAlignment(IntPtrSize == 4 ? 2 : 3);
Sean Silva18dc5382012-12-09 15:52:47 +0000973
974 // Emit PointCount.
Bill Wendling547a7af2013-10-18 23:09:06 +0000975 OS.AddComment("safe point count");
Sean Silva18dc5382012-12-09 15:52:47 +0000976 AP.EmitInt32(MD.size());
Sean Silva18dc5382012-12-09 15:52:47 +0000977
978 // And each safe point...
979 for (GCFunctionInfo::iterator PI = MD.begin(),
Bill Wendling547a7af2013-10-18 23:09:06 +0000980 PE = MD.end(); PI != PE; ++PI) {
Sean Silva18dc5382012-12-09 15:52:47 +0000981 // Emit the address of the safe point.
Bill Wendling547a7af2013-10-18 23:09:06 +0000982 OS.AddComment("safe point address");
983 MCSymbol *Label = PI->Label;
984 AP.EmitLabelPlusOffset(Label/*Hi*/, 0/*Offset*/, 4/*Size*/);
985 }
Sean Silva18dc5382012-12-09 15:52:47 +0000986
Bill Wendling547a7af2013-10-18 23:09:06 +0000987 // Stack information never change in safe points! Only print info from the
988 // first call-site.
989 GCFunctionInfo::iterator PI = MD.begin();
Sean Silva18dc5382012-12-09 15:52:47 +0000990
Bill Wendling547a7af2013-10-18 23:09:06 +0000991 // Emit the stack frame size.
992 OS.AddComment("stack frame size (in words)");
993 AP.EmitInt32(MD.getFrameSize() / IntPtrSize);
Sean Silva18dc5382012-12-09 15:52:47 +0000994
Bill Wendling547a7af2013-10-18 23:09:06 +0000995 // Emit stack arity, i.e. the number of stacked arguments.
996 unsigned RegisteredArgs = IntPtrSize == 4 ? 5 : 6;
997 unsigned StackArity = MD.getFunction().arg_size() > RegisteredArgs ?
998 MD.getFunction().arg_size() - RegisteredArgs : 0;
999 OS.AddComment("stack arity");
1000 AP.EmitInt32(StackArity);
1001
1002 // Emit the number of live roots in the function.
1003 OS.AddComment("live root count");
1004 AP.EmitInt32(MD.live_size(PI));
1005
1006 // And for each live root...
1007 for (GCFunctionInfo::live_iterator LI = MD.live_begin(PI),
1008 LE = MD.live_end(PI);
1009 LI != LE; ++LI) {
1010 // Emit live root's offset within the stack frame.
1011 OS.AddComment("stack index (offset / wordsize)");
1012 AP.EmitInt32(LI->StackOffset);
Sean Silva18dc5382012-12-09 15:52:47 +00001013 }
1014 }
1015 }
1016
1017References
1018==========
1019
1020.. _appel89:
1021
1022[Appel89] Runtime Tags Aren't Necessary. Andrew W. Appel. Lisp and Symbolic
1023Computation 19(7):703-705, July 1989.
1024
1025.. _goldberg91:
1026
1027[Goldberg91] Tag-free garbage collection for strongly typed programming
1028languages. Benjamin Goldberg. ACM SIGPLAN PLDI'91.
1029
1030.. _tolmach94:
1031
1032[Tolmach94] Tag-free garbage collection using explicit type parameters. Andrew
1033Tolmach. Proceedings of the 1994 ACM conference on LISP and functional
1034programming.
1035
1036.. _henderson02:
1037
1038[Henderson2002] `Accurate Garbage Collection in an Uncooperative Environment
1039<http://citeseer.ist.psu.edu/henderson02accurate.html>`__