blob: 822f212ddbeb75c5b6c2bdad29fa9086d43792e0 [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
Philip Reames50e9aed2015-02-24 23:51:37 +0000201IR features is specified by the selected :ref:`GC strategy description
202<plugin>`.
Sean Silva18dc5382012-12-09 15:52:47 +0000203
Sean Silva18dc5382012-12-09 15:52:47 +0000204Specifying GC code generation: ``gc "..."``
205-------------------------------------------
206
207.. code-block:: llvm
208
Philip Reames50e9aed2015-02-24 23:51:37 +0000209 define <returntype> @name(...) gc "name" { ... }
Sean Silva18dc5382012-12-09 15:52:47 +0000210
Philip Reames50e9aed2015-02-24 23:51:37 +0000211The ``gc`` function attribute is used to specify the desired GC strategy to the
Sean Silva18dc5382012-12-09 15:52:47 +0000212compiler. Its programmatic equivalent is the ``setGC`` method of ``Function``.
213
Philip Reames50e9aed2015-02-24 23:51:37 +0000214Setting ``gc "name"`` on a function triggers a search for a matching subclass
215of GCStrategy. Some collector strategies are built in. You can add others
216using either the loadable plugin mechanism, or by patching your copy of LLVM.
217It is the selected GC strategy which defines the exact nature of the code
218generated to support GC. If none is found, the compiler will raise an error.
Sean Silva18dc5382012-12-09 15:52:47 +0000219
220Specifying the GC style on a per-function basis allows LLVM to link together
221programs that use different garbage collection algorithms (or none at all).
222
223.. _gcroot:
224
225Identifying GC roots on the stack: ``llvm.gcroot``
226--------------------------------------------------
227
228.. code-block:: llvm
229
230 void @llvm.gcroot(i8** %ptrloc, i8* %metadata)
231
232The ``llvm.gcroot`` intrinsic is used to inform LLVM that a stack variable
233references an object on the heap and is to be tracked for garbage collection.
234The exact impact on generated code is specified by a :ref:`compiler plugin
235<plugin>`. All calls to ``llvm.gcroot`` **must** reside inside the first basic
236block.
237
238A compiler which uses mem2reg to raise imperative code using ``alloca`` into SSA
239form need only add a call to ``@llvm.gcroot`` for those variables which a
240pointers into the GC heap.
241
242It is also important to mark intermediate values with ``llvm.gcroot``. For
243example, consider ``h(f(), g())``. Beware leaking the result of ``f()`` in the
244case that ``g()`` triggers a collection. Note, that stack variables must be
245initialized and marked with ``llvm.gcroot`` in function's prologue.
246
247The first argument **must** be a value referring to an alloca instruction or a
248bitcast of an alloca. The second contains a pointer to metadata that should be
249associated with the pointer, and **must** be a constant or global value
250address. If your target collector uses tags, use a null pointer for metadata.
251
252The ``%metadata`` argument can be used to avoid requiring heap objects to have
253'isa' pointers or tag bits. [Appel89_, Goldberg91_, Tolmach94_] If specified,
254its value will be tracked along with the location of the pointer in the stack
255frame.
256
257Consider the following fragment of Java code:
258
259.. code-block:: java
260
261 {
262 Object X; // A null-initialized reference to an object
263 ...
264 }
265
266This block (which may be located in the middle of a function or in a loop nest),
267could be compiled to this LLVM code:
268
269.. code-block:: llvm
270
271 Entry:
272 ;; In the entry block for the function, allocate the
273 ;; stack space for X, which is an LLVM pointer.
274 %X = alloca %Object*
275
276 ;; Tell LLVM that the stack space is a stack root.
277 ;; Java has type-tags on objects, so we pass null as metadata.
278 %tmp = bitcast %Object** %X to i8**
279 call void @llvm.gcroot(i8** %tmp, i8* null)
280 ...
281
282 ;; "CodeBlock" is the block corresponding to the start
283 ;; of the scope above.
284 CodeBlock:
285 ;; Java null-initializes pointers.
286 store %Object* null, %Object** %X
287
288 ...
289
290 ;; As the pointer goes out of scope, store a null value into
291 ;; it, to indicate that the value is no longer live.
292 store %Object* null, %Object** %X
293 ...
294
Sean Silva18dc5382012-12-09 15:52:47 +0000295Reading and writing references in the heap
296------------------------------------------
297
298Some collectors need to be informed when the mutator (the program that needs
299garbage collection) either reads a pointer from or writes a pointer to a field
300of a heap object. The code fragments inserted at these points are called *read
301barriers* and *write barriers*, respectively. The amount of code that needs to
302be executed is usually quite small and not on the critical path of any
303computation, so the overall performance impact of the barrier is tolerable.
304
305Barriers often require access to the *object pointer* rather than the *derived
306pointer* (which is a pointer to the field within the object). Accordingly,
307these intrinsics take both pointers as separate arguments for completeness. In
308this snippet, ``%object`` is the object pointer, and ``%derived`` is the derived
309pointer:
310
311.. code-block:: llvm
312
313 ;; An array type.
314 %class.Array = type { %class.Object, i32, [0 x %class.Object*] }
315 ...
316
317 ;; Load the object pointer from a gcroot.
318 %object = load %class.Array** %object_addr
319
320 ;; Compute the derived pointer.
321 %derived = getelementptr %object, i32 0, i32 2, i32 %n
322
323LLVM does not enforce this relationship between the object and derived pointer
Philip Reames50e9aed2015-02-24 23:51:37 +0000324(although a particular :ref:`collector strategy <plugin>` might). However, it
325would be an unusual collector that violated it.
Sean Silva18dc5382012-12-09 15:52:47 +0000326
Philip Reames50e9aed2015-02-24 23:51:37 +0000327The use of these intrinsics is naturally optional if the target GC does not
328require the corresponding barrier. The GC strategy used with such a collector
329should replace the intrinsic calls with the corresponding ``load`` or
330``store`` instruction if they are used.
331
332One known deficiency with the current design is that the barrier intrinsics do
333not include the size or alignment of the underlying operation performed. It is
334currently assumed that the operation is of pointer size and the alignment is
335assumed to be the target machine's default alignment.
Sean Silva18dc5382012-12-09 15:52:47 +0000336
Sean Silva18dc5382012-12-09 15:52:47 +0000337Write barrier: ``llvm.gcwrite``
338^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
339
340.. code-block:: llvm
341
342 void @llvm.gcwrite(i8* %value, i8* %object, i8** %derived)
343
344For write barriers, LLVM provides the ``llvm.gcwrite`` intrinsic function. It
345has exactly the same semantics as a non-volatile ``store`` to the derived
Philip Reames50e9aed2015-02-24 23:51:37 +0000346pointer (the third argument). The exact code generated is specified by the
347Function's selected :ref:`GC strategy <plugin>`.
Sean Silva18dc5382012-12-09 15:52:47 +0000348
349Many important algorithms require write barriers, including generational and
350concurrent collectors. Additionally, write barriers could be used to implement
351reference counting.
352
Sean Silva18dc5382012-12-09 15:52:47 +0000353Read barrier: ``llvm.gcread``
354^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
355
356.. code-block:: llvm
357
358 i8* @llvm.gcread(i8* %object, i8** %derived)
359
360For read barriers, LLVM provides the ``llvm.gcread`` intrinsic function. It has
361exactly the same semantics as a non-volatile ``load`` from the derived pointer
Philip Reames50e9aed2015-02-24 23:51:37 +0000362(the second argument). The exact code generated is specified by the Function's
363selected :ref:`GC strategy <plugin>`.
Sean Silva18dc5382012-12-09 15:52:47 +0000364
365Read barriers are needed by fewer algorithms than write barriers, and may have a
366greater performance impact since pointer reads are more frequent than writes.
367
368.. _plugin:
369
Philip Reamese78cf552015-02-24 19:44:46 +0000370Built In Collectors
371====================
372
373LLVM includes built in support for several varieties of garbage collectors.
374
375The Shadow Stack GC
376----------------------
377
378To use this collector strategy, mark your functions with:
379
380.. code-block:: c++
381
382 F.setGC("shadow-stack");
383
384Unlike many GC algorithms which rely on a cooperative code generator to compile
385stack maps, this algorithm carefully maintains a linked list of stack roots
386[:ref:`Henderson2002 <henderson02>`]. This so-called "shadow stack" mirrors the
387machine stack. Maintaining this data structure is slower than using a stack map
388compiled into the executable as constant data, but has a significant portability
389advantage because it requires no special support from the target code generator,
390and does not require tricky platform-specific code to crawl the machine stack.
391
392The tradeoff for this simplicity and portability is:
393
394* High overhead per function call.
395
396* Not thread-safe.
397
398Still, it's an easy way to get started. After your compiler and runtime are up
399and running, writing a :ref:`plugin <plugin>` will allow you to take advantage
400of :ref:`more advanced GC features <collector-algos>` of LLVM in order to
401improve performance.
402
Philip Reames03f38362015-02-24 23:12:27 +0000403
404The shadow stack doesn't imply a memory allocation algorithm. A semispace
405collector or building atop ``malloc`` are great places to start, and can be
406implemented with very little code.
407
408When it comes time to collect, however, your runtime needs to traverse the stack
409roots, and for this it needs to integrate with the shadow stack. Luckily, doing
410so is very simple. (This code is heavily commented to help you understand the
411data structure, but there are only 20 lines of meaningful code.)
412
413.. code-block:: c++
414
415 /// @brief The map for a single function's stack frame. One of these is
416 /// compiled as constant data into the executable for each function.
417 ///
418 /// Storage of metadata values is elided if the %metadata parameter to
419 /// @llvm.gcroot is null.
420 struct FrameMap {
421 int32_t NumRoots; //< Number of roots in stack frame.
422 int32_t NumMeta; //< Number of metadata entries. May be < NumRoots.
423 const void *Meta[0]; //< Metadata for each root.
424 };
425
426 /// @brief A link in the dynamic shadow stack. One of these is embedded in
427 /// the stack frame of each function on the call stack.
428 struct StackEntry {
429 StackEntry *Next; //< Link to next stack entry (the caller's).
430 const FrameMap *Map; //< Pointer to constant FrameMap.
431 void *Roots[0]; //< Stack roots (in-place array).
432 };
433
434 /// @brief The head of the singly-linked list of StackEntries. Functions push
435 /// and pop onto this in their prologue and epilogue.
436 ///
437 /// Since there is only a global list, this technique is not threadsafe.
438 StackEntry *llvm_gc_root_chain;
439
440 /// @brief Calls Visitor(root, meta) for each GC root on the stack.
441 /// root and meta are exactly the values passed to
442 /// @llvm.gcroot.
443 ///
444 /// Visitor could be a function to recursively mark live objects. Or it
445 /// might copy them to another heap or generation.
446 ///
447 /// @param Visitor A function to invoke for every GC root on the stack.
448 void visitGCRoots(void (*Visitor)(void **Root, const void *Meta)) {
449 for (StackEntry *R = llvm_gc_root_chain; R; R = R->Next) {
450 unsigned i = 0;
451
452 // For roots [0, NumMeta), the metadata pointer is in the FrameMap.
453 for (unsigned e = R->Map->NumMeta; i != e; ++i)
454 Visitor(&R->Roots[i], R->Map->Meta[i]);
455
456 // For roots [NumMeta, NumRoots), the metadata pointer is null.
457 for (unsigned e = R->Map->NumRoots; i != e; ++i)
458 Visitor(&R->Roots[i], NULL);
459 }
460 }
461
462
Philip Reamese78cf552015-02-24 19:44:46 +0000463The 'Erlang' and 'Ocaml' GCs
464-----------------------------
465
466LLVM ships with two example collectors which leverage the ''gcroot''
467mechanisms. To our knowledge, these are not actually used by any language
468runtime, but they do provide a reasonable starting point for someone interested
469in writing an ''gcroot' compatible GC plugin. In particular, these are the
470only in tree examples of how to produce a custom binary stack map format using
471a ''gcroot'' strategy.
472
473As there names imply, the binary format produced is intended to model that
474used by the Erlang and OCaml compilers respectively.
475
476
477The Statepoint Example GC
478-------------------------
479
480.. code-block:: c++
481
482 F.setGC("statepoint-example");
483
484This GC provides an example of how one might use the infrastructure provided
485by ''gc.statepoint''.
486
487
Philip Reames03f38362015-02-24 23:12:27 +0000488Custom GC Strategies
489====================
490
491If none of the built in GC strategy descriptions met your needs above, you will
492need to define a custom GCStrategy and possibly, a custom LLVM pass to perform
493lowering. Your best example of where to start defining a custom GCStrategy
494would be to look at one of the built in strategies.
495
496You may be able to structure this additional code as a loadable plugin library.
497Loadable plugins are sufficient if all you need is to enable a different
498combination of built in functionality, but if you need to provide a custom
499lowering pass, you will need to build a patched version of LLVM. If you think
500you need a patched build, please ask for advice on llvm-dev. There may be an
501easy way we can extend the support to make it work for your use case without
502requiring a custom build.
503
Philip Reames38263192015-02-24 23:34:24 +0000504Collector Requirements
505----------------------
506
507You should be able to leverage any existing collector library that includes the following elements:
508
509#. A memory allocator which exposes an allocation function your compiled
510 code can call.
511
512#. A binary format for the stack map. A stack map describes the location
513 of references at a safepoint and is used by precise collectors to identify
514 references within a stack frame on the machine stack. Note that collectors
515 which conservatively scan the stack don't require such a structure.
516
517#. A stack crawler to discover functions on the call stack, and enumerate the
518 references listed in the stack map for each call site.
519
520#. A mechanism for identifying references in global locations (e.g. global
521 variables).
522
523#. If you collector requires them, an LLVM IR implementation of your collectors
524 load and store barriers. Note that since many collectors don't require
525 barriers at all, LLVM defaults to lowering such barriers to normal loads
526 and stores unless you arrange otherwise.
527
Philip Reames03f38362015-02-24 23:12:27 +0000528
Sean Silva18dc5382012-12-09 15:52:47 +0000529Implementing a collector plugin
Philip Reames03f38362015-02-24 23:12:27 +0000530-------------------------------
Sean Silva18dc5382012-12-09 15:52:47 +0000531
532User code specifies which GC code generation to use with the ``gc`` function
533attribute or, equivalently, with the ``setGC`` method of ``Function``.
534
535To implement a GC plugin, it is necessary to subclass ``llvm::GCStrategy``,
536which can be accomplished in a few lines of boilerplate code. LLVM's
537infrastructure provides access to several important algorithms. For an
538uncontroversial collector, all that remains may be to compile LLVM's computed
539stack map to assembly code (using the binary representation expected by the
540runtime library). This can be accomplished in about 100 lines of code.
541
542This is not the appropriate place to implement a garbage collected heap or a
543garbage collector itself. That code should exist in the language's runtime
544library. The compiler plugin is responsible for generating code which conforms
545to the binary interface defined by library, most essentially the :ref:`stack map
546<stack-map>`.
547
548To subclass ``llvm::GCStrategy`` and register it with the compiler:
549
550.. code-block:: c++
551
552 // lib/MyGC/MyGC.cpp - Example LLVM GC plugin
553
554 #include "llvm/CodeGen/GCStrategy.h"
555 #include "llvm/CodeGen/GCMetadata.h"
556 #include "llvm/Support/Compiler.h"
557
558 using namespace llvm;
559
560 namespace {
561 class LLVM_LIBRARY_VISIBILITY MyGC : public GCStrategy {
562 public:
563 MyGC() {}
564 };
565
566 GCRegistry::Add<MyGC>
567 X("mygc", "My bespoke garbage collector.");
568 }
569
570This boilerplate collector does nothing. More specifically:
571
572* ``llvm.gcread`` calls are replaced with the corresponding ``load``
573 instruction.
574
575* ``llvm.gcwrite`` calls are replaced with the corresponding ``store``
576 instruction.
577
578* No safe points are added to the code.
579
580* The stack map is not compiled into the executable.
581
Rafael Espindola730df072014-03-12 22:40:22 +0000582Using the LLVM makefiles, this code
Sean Silva18dc5382012-12-09 15:52:47 +0000583can be compiled as a plugin using a simple makefile:
584
585.. code-block:: make
586
587 # lib/MyGC/Makefile
588
589 LEVEL := ../..
590 LIBRARYNAME = MyGC
591 LOADABLE_MODULE = 1
592
593 include $(LEVEL)/Makefile.common
594
595Once the plugin is compiled, code using it may be compiled using ``llc
596-load=MyGC.so`` (though MyGC.so may have some other platform-specific
597extension):
598
599::
600
601 $ cat sample.ll
602 define void @f() gc "mygc" {
603 entry:
Bill Wendling547a7af2013-10-18 23:09:06 +0000604 ret void
Sean Silva18dc5382012-12-09 15:52:47 +0000605 }
606 $ llvm-as < sample.ll | llc -load=MyGC.so
607
608It is also possible to statically link the collector plugin into tools, such as
609a language-specific compiler front-end.
610
611.. _collector-algos:
612
613Overview of available features
614------------------------------
615
616``GCStrategy`` provides a range of features through which a plugin may do useful
617work. Some of these are callbacks, some are algorithms that can be enabled,
618disabled, or customized. This matrix summarizes the supported (and planned)
619features and correlates them with the collection techniques which typically
620require them.
621
622.. |v| unicode:: 0x2714
623 :trim:
624
625.. |x| unicode:: 0x2718
626 :trim:
627
628+------------+------+--------+----------+-------+---------+-------------+----------+------------+
629| Algorithm | Done | Shadow | refcount | mark- | copying | incremental | threaded | concurrent |
630| | | stack | | sweep | | | | |
631+============+======+========+==========+=======+=========+=============+==========+============+
632| stack map | |v| | | | |x| | |x| | |x| | |x| | |x| |
633+------------+------+--------+----------+-------+---------+-------------+----------+------------+
634| initialize | |v| | |x| | |x| | |x| | |x| | |x| | |x| | |x| |
635| roots | | | | | | | | |
636+------------+------+--------+----------+-------+---------+-------------+----------+------------+
637| derived | NO | | | | | | **N**\* | **N**\* |
638| pointers | | | | | | | | |
639+------------+------+--------+----------+-------+---------+-------------+----------+------------+
640| **custom | |v| | | | | | | | |
641| lowering** | | | | | | | | |
642+------------+------+--------+----------+-------+---------+-------------+----------+------------+
643| *gcroot* | |v| | |x| | |x| | | | | | |
644+------------+------+--------+----------+-------+---------+-------------+----------+------------+
645| *gcwrite* | |v| | | |x| | | | |x| | | |x| |
646+------------+------+--------+----------+-------+---------+-------------+----------+------------+
647| *gcread* | |v| | | | | | | | |x| |
648+------------+------+--------+----------+-------+---------+-------------+----------+------------+
649| **safe | | | | | | | | |
650| points** | | | | | | | | |
651+------------+------+--------+----------+-------+---------+-------------+----------+------------+
652| *in | |v| | | | |x| | |x| | |x| | |x| | |x| |
653| calls* | | | | | | | | |
654+------------+------+--------+----------+-------+---------+-------------+----------+------------+
655| *before | |v| | | | | | | |x| | |x| |
656| calls* | | | | | | | | |
657+------------+------+--------+----------+-------+---------+-------------+----------+------------+
658| *for | NO | | | | | | **N** | **N** |
659| loops* | | | | | | | | |
660+------------+------+--------+----------+-------+---------+-------------+----------+------------+
661| *before | |v| | | | | | | |x| | |x| |
662| escape* | | | | | | | | |
663+------------+------+--------+----------+-------+---------+-------------+----------+------------+
664| emit code | NO | | | | | | **N** | **N** |
665| at safe | | | | | | | | |
666| points | | | | | | | | |
667+------------+------+--------+----------+-------+---------+-------------+----------+------------+
668| **output** | | | | | | | | |
669+------------+------+--------+----------+-------+---------+-------------+----------+------------+
670| *assembly* | |v| | | | |x| | |x| | |x| | |x| | |x| |
671+------------+------+--------+----------+-------+---------+-------------+----------+------------+
672| *JIT* | NO | | | **?** | **?** | **?** | **?** | **?** |
673+------------+------+--------+----------+-------+---------+-------------+----------+------------+
674| *obj* | NO | | | **?** | **?** | **?** | **?** | **?** |
675+------------+------+--------+----------+-------+---------+-------------+----------+------------+
676| live | NO | | | **?** | **?** | **?** | **?** | **?** |
677| analysis | | | | | | | | |
678+------------+------+--------+----------+-------+---------+-------------+----------+------------+
679| register | NO | | | **?** | **?** | **?** | **?** | **?** |
680| map | | | | | | | | |
681+------------+------+--------+----------+-------+---------+-------------+----------+------------+
682| \* Derived pointers only pose a hasard to copying collections. |
683+------------+------+--------+----------+-------+---------+-------------+----------+------------+
684| **?** denotes a feature which could be utilized if available. |
685+------------+------+--------+----------+-------+---------+-------------+----------+------------+
686
687To be clear, the collection techniques above are defined as:
688
689Shadow Stack
690 The mutator carefully maintains a linked list of stack roots.
691
692Reference Counting
693 The mutator maintains a reference count for each object and frees an object
694 when its count falls to zero.
695
696Mark-Sweep
697 When the heap is exhausted, the collector marks reachable objects starting
698 from the roots, then deallocates unreachable objects in a sweep phase.
699
700Copying
701 As reachability analysis proceeds, the collector copies objects from one heap
702 area to another, compacting them in the process. Copying collectors enable
703 highly efficient "bump pointer" allocation and can improve locality of
704 reference.
705
706Incremental
707 (Including generational collectors.) Incremental collectors generally have all
708 the properties of a copying collector (regardless of whether the mature heap
709 is compacting), but bring the added complexity of requiring write barriers.
710
711Threaded
712 Denotes a multithreaded mutator; the collector must still stop the mutator
713 ("stop the world") before beginning reachability analysis. Stopping a
714 multithreaded mutator is a complicated problem. It generally requires highly
Alp Tokercf218752014-06-30 18:57:16 +0000715 platform-specific code in the runtime, and the production of carefully
Sean Silva18dc5382012-12-09 15:52:47 +0000716 designed machine code at safe points.
717
718Concurrent
719 In this technique, the mutator and the collector run concurrently, with the
720 goal of eliminating pause times. In a *cooperative* collector, the mutator
721 further aids with collection should a pause occur, allowing collection to take
722 advantage of multiprocessor hosts. The "stop the world" problem of threaded
723 collectors is generally still present to a limited extent. Sophisticated
724 marking algorithms are necessary. Read barriers may be necessary.
725
726As the matrix indicates, LLVM's garbage collection infrastructure is already
727suitable for a wide variety of collectors, but does not currently extend to
728multithreaded programs. This will be added in the future as there is
729interest.
730
731.. _stack-map:
732
733Computing stack maps
734--------------------
735
736LLVM automatically computes a stack map. One of the most important features
737of a ``GCStrategy`` is to compile this information into the executable in
738the binary representation expected by the runtime library.
739
740The stack map consists of the location and identity of each GC root in the
741each function in the module. For each root:
742
743* ``RootNum``: The index of the root.
744
745* ``StackOffset``: The offset of the object relative to the frame pointer.
746
747* ``RootMetadata``: The value passed as the ``%metadata`` parameter to the
748 ``@llvm.gcroot`` intrinsic.
749
750Also, for the function as a whole:
751
752* ``getFrameSize()``: The overall size of the function's initial stack frame,
753 not accounting for any dynamic allocation.
754
755* ``roots_size()``: The count of roots in the function.
756
757To access the stack map, use ``GCFunctionMetadata::roots_begin()`` and
758-``end()`` from the :ref:`GCMetadataPrinter <assembly>`:
759
760.. code-block:: c++
761
762 for (iterator I = begin(), E = end(); I != E; ++I) {
763 GCFunctionInfo *FI = *I;
764 unsigned FrameSize = FI->getFrameSize();
765 size_t RootCount = FI->roots_size();
766
767 for (GCFunctionInfo::roots_iterator RI = FI->roots_begin(),
768 RE = FI->roots_end();
769 RI != RE; ++RI) {
770 int RootNum = RI->Num;
771 int RootStackOffset = RI->StackOffset;
772 Constant *RootMetadata = RI->Metadata;
773 }
774 }
775
776If the ``llvm.gcroot`` intrinsic is eliminated before code generation by a
777custom lowering pass, LLVM will compute an empty stack map. This may be useful
778for collector plugins which implement reference counting or a shadow stack.
779
780.. _init-roots:
781
782Initializing roots to null: ``InitRoots``
783-----------------------------------------
784
785.. code-block:: c++
786
787 MyGC::MyGC() {
788 InitRoots = true;
789 }
790
791When set, LLVM will automatically initialize each root to ``null`` upon entry to
792the function. This prevents the GC's sweep phase from visiting uninitialized
793pointers, which will almost certainly cause it to crash. This initialization
794occurs before custom lowering, so the two may be used together.
795
796Since LLVM does not yet compute liveness information, there is no means of
797distinguishing an uninitialized stack root from an initialized one. Therefore,
798this feature should be used by all GC plugins. It is enabled by default.
799
Sean Silva18dc5382012-12-09 15:52:47 +0000800Custom lowering of intrinsics: ``CustomRoots``, ``CustomReadBarriers``, and ``CustomWriteBarriers``
801---------------------------------------------------------------------------------------------------
802
Philip Reames23cf2e22015-01-28 19:28:03 +0000803For GCs which use barriers or unusual treatment of stack roots, these
804flags allow the collector to perform arbitrary transformations of the
805LLVM IR:
Sean Silva18dc5382012-12-09 15:52:47 +0000806
807.. code-block:: c++
808
809 class MyGC : public GCStrategy {
810 public:
811 MyGC() {
812 CustomRoots = true;
813 CustomReadBarriers = true;
814 CustomWriteBarriers = true;
815 }
Sean Silva18dc5382012-12-09 15:52:47 +0000816 };
817
Philip Reames23cf2e22015-01-28 19:28:03 +0000818If any of these flags are set, LLVM suppresses its default lowering for
819the corresponding intrinsics. Instead, you must provide a custom Pass
820which lowers the intrinsics as desired. If you have opted in to custom
821lowering of a particular intrinsic your pass **must** eliminate all
822instances of the corresponding intrinsic in functions which opt in to
823your GC. The best example of such a pass is the ShadowStackGC and it's
824ShadowStackGCLowering pass.
Sean Silva18dc5382012-12-09 15:52:47 +0000825
Philip Reames23cf2e22015-01-28 19:28:03 +0000826There is currently no way to register such a custom lowering pass
827without building a custom copy of LLVM.
Sean Silva18dc5382012-12-09 15:52:47 +0000828
829.. _safe-points:
830
831Generating safe points: ``NeededSafePoints``
832--------------------------------------------
833
834LLVM can compute four kinds of safe points:
835
836.. code-block:: c++
837
838 namespace GC {
839 /// PointKind - The type of a collector-safe point.
840 ///
841 enum PointKind {
842 Loop, //< Instr is a loop (backwards branch).
843 Return, //< Instr is a return instruction.
844 PreCall, //< Instr is a call instruction.
845 PostCall //< Instr is the return address of a call.
846 };
847 }
848
849A collector can request any combination of the four by setting the
850``NeededSafePoints`` mask:
851
852.. code-block:: c++
853
854 MyGC::MyGC() {
855 NeededSafePoints = 1 << GC::Loop
856 | 1 << GC::Return
857 | 1 << GC::PreCall
858 | 1 << GC::PostCall;
859 }
860
861It can then use the following routines to access safe points.
862
863.. code-block:: c++
864
865 for (iterator I = begin(), E = end(); I != E; ++I) {
866 GCFunctionInfo *MD = *I;
867 size_t PointCount = MD->size();
868
869 for (GCFunctionInfo::iterator PI = MD->begin(),
870 PE = MD->end(); PI != PE; ++PI) {
871 GC::PointKind PointKind = PI->Kind;
872 unsigned PointNum = PI->Num;
873 }
874 }
875
876Almost every collector requires ``PostCall`` safe points, since these correspond
877to the moments when the function is suspended during a call to a subroutine.
878
879Threaded programs generally require ``Loop`` safe points to guarantee that the
880application will reach a safe point within a bounded amount of time, even if it
881is executing a long-running loop which contains no function calls.
882
883Threaded collectors may also require ``Return`` and ``PreCall`` safe points to
884implement "stop the world" techniques using self-modifying code, where it is
885important that the program not exit the function without reaching a safe point
886(because only the topmost function has been patched).
887
888.. _assembly:
889
890Emitting assembly code: ``GCMetadataPrinter``
891---------------------------------------------
892
893LLVM allows a plugin to print arbitrary assembly code before and after the rest
894of a module's assembly code. At the end of the module, the GC can compile the
895LLVM stack map into assembly code. (At the beginning, this information is not
896yet computed.)
897
898Since AsmWriter and CodeGen are separate components of LLVM, a separate abstract
899base class and registry is provided for printing assembly code, the
900``GCMetadaPrinter`` and ``GCMetadataPrinterRegistry``. The AsmWriter will look
901for such a subclass if the ``GCStrategy`` sets ``UsesMetadata``:
902
903.. code-block:: c++
904
905 MyGC::MyGC() {
906 UsesMetadata = true;
907 }
908
909This separation allows JIT-only clients to be smaller.
910
911Note that LLVM does not currently have analogous APIs to support code generation
912in the JIT, nor using the object writers.
913
914.. code-block:: c++
915
916 // lib/MyGC/MyGCPrinter.cpp - Example LLVM GC printer
917
918 #include "llvm/CodeGen/GCMetadataPrinter.h"
919 #include "llvm/Support/Compiler.h"
920
921 using namespace llvm;
922
923 namespace {
924 class LLVM_LIBRARY_VISIBILITY MyGCPrinter : public GCMetadataPrinter {
925 public:
Bill Wendling547a7af2013-10-18 23:09:06 +0000926 virtual void beginAssembly(AsmPrinter &AP);
Sean Silva18dc5382012-12-09 15:52:47 +0000927
Bill Wendling547a7af2013-10-18 23:09:06 +0000928 virtual void finishAssembly(AsmPrinter &AP);
Sean Silva18dc5382012-12-09 15:52:47 +0000929 };
930
931 GCMetadataPrinterRegistry::Add<MyGCPrinter>
932 X("mygc", "My bespoke garbage collector.");
933 }
934
Bill Wendling0b55b4a2013-10-18 23:11:25 +0000935The collector should use ``AsmPrinter`` to print portable assembly code. The
936collector itself contains the stack map for the entire module, and may access
937the ``GCFunctionInfo`` using its own ``begin()`` and ``end()`` methods. Here's
938a realistic example:
Sean Silva18dc5382012-12-09 15:52:47 +0000939
940.. code-block:: c++
941
942 #include "llvm/CodeGen/AsmPrinter.h"
Benjamin Kramer9f566a52013-07-08 19:59:35 +0000943 #include "llvm/IR/Function.h"
944 #include "llvm/IR/DataLayout.h"
Sean Silva18dc5382012-12-09 15:52:47 +0000945 #include "llvm/Target/TargetAsmInfo.h"
Benjamin Kramer9f566a52013-07-08 19:59:35 +0000946 #include "llvm/Target/TargetMachine.h"
Sean Silva18dc5382012-12-09 15:52:47 +0000947
Bill Wendling547a7af2013-10-18 23:09:06 +0000948 void MyGCPrinter::beginAssembly(AsmPrinter &AP) {
Sean Silva18dc5382012-12-09 15:52:47 +0000949 // Nothing to do.
950 }
951
Bill Wendling547a7af2013-10-18 23:09:06 +0000952 void MyGCPrinter::finishAssembly(AsmPrinter &AP) {
953 MCStreamer &OS = AP.OutStreamer;
Eric Christopherd9134482014-08-04 21:25:23 +0000954 unsigned IntPtrSize = AP.TM.getSubtargetImpl()->getDataLayout()->getPointerSize();
Sean Silva18dc5382012-12-09 15:52:47 +0000955
956 // Put this in the data section.
Bill Wendling547a7af2013-10-18 23:09:06 +0000957 OS.SwitchSection(AP.getObjFileLowering().getDataSection());
Sean Silva18dc5382012-12-09 15:52:47 +0000958
959 // For each function...
960 for (iterator FI = begin(), FE = end(); FI != FE; ++FI) {
961 GCFunctionInfo &MD = **FI;
962
Bill Wendling547a7af2013-10-18 23:09:06 +0000963 // A compact GC layout. Emit this data structure:
Sean Silva18dc5382012-12-09 15:52:47 +0000964 //
965 // struct {
966 // int32_t PointCount;
Bill Wendling547a7af2013-10-18 23:09:06 +0000967 // void *SafePointAddress[PointCount];
968 // int32_t StackFrameSize; // in words
969 // int32_t StackArity;
970 // int32_t LiveCount;
971 // int32_t LiveOffsets[LiveCount];
Sean Silva18dc5382012-12-09 15:52:47 +0000972 // } __gcmap_<FUNCTIONNAME>;
973
974 // Align to address width.
Bill Wendling547a7af2013-10-18 23:09:06 +0000975 AP.EmitAlignment(IntPtrSize == 4 ? 2 : 3);
Sean Silva18dc5382012-12-09 15:52:47 +0000976
977 // Emit PointCount.
Bill Wendling547a7af2013-10-18 23:09:06 +0000978 OS.AddComment("safe point count");
Sean Silva18dc5382012-12-09 15:52:47 +0000979 AP.EmitInt32(MD.size());
Sean Silva18dc5382012-12-09 15:52:47 +0000980
981 // And each safe point...
982 for (GCFunctionInfo::iterator PI = MD.begin(),
Bill Wendling547a7af2013-10-18 23:09:06 +0000983 PE = MD.end(); PI != PE; ++PI) {
Sean Silva18dc5382012-12-09 15:52:47 +0000984 // Emit the address of the safe point.
Bill Wendling547a7af2013-10-18 23:09:06 +0000985 OS.AddComment("safe point address");
986 MCSymbol *Label = PI->Label;
987 AP.EmitLabelPlusOffset(Label/*Hi*/, 0/*Offset*/, 4/*Size*/);
988 }
Sean Silva18dc5382012-12-09 15:52:47 +0000989
Bill Wendling547a7af2013-10-18 23:09:06 +0000990 // Stack information never change in safe points! Only print info from the
991 // first call-site.
992 GCFunctionInfo::iterator PI = MD.begin();
Sean Silva18dc5382012-12-09 15:52:47 +0000993
Bill Wendling547a7af2013-10-18 23:09:06 +0000994 // Emit the stack frame size.
995 OS.AddComment("stack frame size (in words)");
996 AP.EmitInt32(MD.getFrameSize() / IntPtrSize);
Sean Silva18dc5382012-12-09 15:52:47 +0000997
Bill Wendling547a7af2013-10-18 23:09:06 +0000998 // Emit stack arity, i.e. the number of stacked arguments.
999 unsigned RegisteredArgs = IntPtrSize == 4 ? 5 : 6;
1000 unsigned StackArity = MD.getFunction().arg_size() > RegisteredArgs ?
1001 MD.getFunction().arg_size() - RegisteredArgs : 0;
1002 OS.AddComment("stack arity");
1003 AP.EmitInt32(StackArity);
1004
1005 // Emit the number of live roots in the function.
1006 OS.AddComment("live root count");
1007 AP.EmitInt32(MD.live_size(PI));
1008
1009 // And for each live root...
1010 for (GCFunctionInfo::live_iterator LI = MD.live_begin(PI),
1011 LE = MD.live_end(PI);
1012 LI != LE; ++LI) {
1013 // Emit live root's offset within the stack frame.
1014 OS.AddComment("stack index (offset / wordsize)");
1015 AP.EmitInt32(LI->StackOffset);
Sean Silva18dc5382012-12-09 15:52:47 +00001016 }
1017 }
1018 }
1019
1020References
1021==========
1022
1023.. _appel89:
1024
1025[Appel89] Runtime Tags Aren't Necessary. Andrew W. Appel. Lisp and Symbolic
1026Computation 19(7):703-705, July 1989.
1027
1028.. _goldberg91:
1029
1030[Goldberg91] Tag-free garbage collection for strongly typed programming
1031languages. Benjamin Goldberg. ACM SIGPLAN PLDI'91.
1032
1033.. _tolmach94:
1034
1035[Tolmach94] Tag-free garbage collection using explicit type parameters. Andrew
1036Tolmach. Proceedings of the 1994 ACM conference on LISP and functional
1037programming.
1038
1039.. _henderson02:
1040
1041[Henderson2002] `Accurate Garbage Collection in an Uncooperative Environment
1042<http://citeseer.ist.psu.edu/henderson02accurate.html>`__