1 =====================================
2 Accurate Garbage Collection with LLVM
3 =====================================
8 .. sectionauthor:: Chris Lattner <sabre@nondot.org> and
14 Garbage collection is a widely used technique that frees the programmer from
15 having to know the lifetimes of heap objects, making software easier to produce
16 and maintain. Many programming languages rely on garbage collection for
17 automatic memory management. There are two primary forms of garbage collection:
18 conservative and accurate.
20 Conservative garbage collection often does not require any special support from
21 either the language or the compiler: it can handle non-type-safe programming
22 languages (such as C/C++) and does not require any special information from the
23 compiler. The `Boehm collector
24 <http://www.hpl.hp.com/personal/Hans_Boehm/gc/>`__ is an example of a
25 state-of-the-art conservative collector.
27 Accurate garbage collection requires the ability to identify all pointers in the
28 program at run-time (which requires that the source-language be type-safe in
29 most cases). Identifying pointers at run-time requires compiler support to
30 locate all places that hold live pointer variables at run-time, including the
31 :ref:`processor stack and registers <gcroot>`.
33 Conservative garbage collection is attractive because it does not require any
34 special compiler support, but it does have problems. In particular, because the
35 conservative garbage collector cannot *know* that a particular word in the
36 machine is a pointer, it cannot move live objects in the heap (preventing the
37 use of compacting and generational GC algorithms) and it can occasionally suffer
38 from memory leaks due to integer values that happen to point to objects in the
39 program. In addition, some aggressive compiler transformations can break
40 conservative garbage collectors (though these seem rare in practice).
42 Accurate garbage collectors do not suffer from any of these problems, but they
43 can suffer from degraded scalar optimization of the program. In particular,
44 because the runtime must be able to identify and update all pointers active in
45 the program, some optimizations are less effective. In practice, however, the
46 locality and performance benefits of using aggressive garbage collection
47 techniques dominates any low-level losses.
49 This document describes the mechanisms and interfaces provided by LLVM to
50 support accurate garbage collection.
55 LLVM's intermediate representation provides :ref:`garbage collection intrinsics
56 <gc_intrinsics>` that offer support for a broad class of collector models. For
57 instance, the intrinsics permit:
59 * semi-space collectors
61 * mark-sweep collectors
63 * generational collectors
67 * incremental collectors
69 * concurrent collectors
71 * cooperative collectors
73 We hope that the primitive support built into the LLVM IR is sufficient to
74 support a broad class of garbage collected languages including Scheme, ML, Java,
75 C#, Perl, Python, Lua, Ruby, other scripting languages, and more.
77 However, LLVM does not itself provide a garbage collector --- this should be
78 part of your language's runtime library. LLVM provides a framework for compile
79 time :ref:`code generation plugins <plugin>`. The role of these plugins is to
80 generate code and data structures which conforms to the *binary interface*
81 specified by the *runtime library*. This is similar to the relationship between
82 LLVM and DWARF debugging info, for example. The difference primarily lies in
83 the lack of an established standard in the domain of garbage collection --- thus
86 The aspects of the binary interface with which LLVM's GC support is
89 * Creation of GC-safe points within code where collection is allowed to execute
92 * Computation of the stack map. For each safe point in the code, object
93 references within the stack frame must be identified so that the collector may
94 traverse and perhaps update them.
96 * Write barriers when storing object references to the heap. These are commonly
97 used to optimize incremental scans in generational collectors.
99 * Emission of read barriers when loading object references. These are useful
100 for interoperating with concurrent collectors.
102 There are additional areas that LLVM does not directly address:
104 * Registration of global roots with the runtime.
106 * Registration of stack map entries with the runtime.
108 * The functions used by the program to allocate memory, trigger a collection,
111 * Computation or compilation of type maps, or registration of them with the
112 runtime. These are used to crawl the heap for object references.
114 In general, LLVM's support for GC does not include features which can be
115 adequately addressed with other features of the IR and does not specify a
116 particular binary interface. On the plus side, this means that you should be
117 able to integrate LLVM with an existing runtime. On the other hand, it leaves a
118 lot of work for the developer of a novel language. However, it's easy to get
119 started quickly and scale up to a more sophisticated implementation as your
125 Using a GC with LLVM implies many things, for example:
127 * Write a runtime library or find an existing one which implements a GC heap.
129 #. Implement a memory allocator.
131 #. Design a binary interface for the stack map, used to identify references
132 within a stack frame on the machine stack.\*
134 #. Implement a stack crawler to discover functions on the call stack.\*
136 #. Implement a registry for global roots.
138 #. Design a binary interface for type maps, used to identify references
141 #. Implement a collection routine bringing together all of the above.
143 * Emit compatible code from your compiler.
145 * Initialization in the main function.
147 * Use the ``gc "..."`` attribute to enable GC code generation (or
150 * Use ``@llvm.gcroot`` to mark stack roots.
152 * Use ``@llvm.gcread`` and/or ``@llvm.gcwrite`` to manipulate GC references,
155 * Allocate memory using the GC allocation routine provided by the runtime
158 * Generate type maps according to your runtime's binary interface.
160 * Write a compiler plugin to interface LLVM with the runtime library.\*
162 * Lower ``@llvm.gcread`` and ``@llvm.gcwrite`` to appropriate code
165 * Compile LLVM's stack map to the binary form expected by the runtime.
167 * Load the plugin into the compiler. Use ``llc -load`` or link the plugin
168 statically with your language's compiler.\*
170 * Link program executables with the runtime.
172 To help with several of these tasks (those indicated with a \*), LLVM includes a
173 highly portable, built-in ShadowStack code generator. It is compiled into
174 ``llc`` and works even with the interpreter and C backends.
179 To turn the shadow stack on for your functions, first call:
183 F.setGC("shadow-stack");
185 for each function your compiler emits. Since the shadow stack is built into
186 LLVM, you do not need to load a plugin.
188 Your compiler must also use ``@llvm.gcroot`` as documented. Don't forget to
189 create a root for each intermediate value that is generated when evaluating an
190 expression. In ``h(f(), g())``, the result of ``f()`` could easily be collected
191 if evaluating ``g()`` triggers a collection.
193 There's no need to use ``@llvm.gcread`` and ``@llvm.gcwrite`` over plain
194 ``load`` and ``store`` for now. You will need them when switching to a more
200 The shadow stack doesn't imply a memory allocation algorithm. A semispace
201 collector or building atop ``malloc`` are great places to start, and can be
202 implemented with very little code.
204 When it comes time to collect, however, your runtime needs to traverse the stack
205 roots, and for this it needs to integrate with the shadow stack. Luckily, doing
206 so is very simple. (This code is heavily commented to help you understand the
207 data structure, but there are only 20 lines of meaningful code.)
211 /// @brief The map for a single function's stack frame. One of these is
212 /// compiled as constant data into the executable for each function.
214 /// Storage of metadata values is elided if the %metadata parameter to
215 /// @llvm.gcroot is null.
217 int32_t NumRoots; //< Number of roots in stack frame.
218 int32_t NumMeta; //< Number of metadata entries. May be < NumRoots.
219 const void *Meta[0]; //< Metadata for each root.
222 /// @brief A link in the dynamic shadow stack. One of these is embedded in
223 /// the stack frame of each function on the call stack.
225 StackEntry *Next; //< Link to next stack entry (the caller's).
226 const FrameMap *Map; //< Pointer to constant FrameMap.
227 void *Roots[0]; //< Stack roots (in-place array).
230 /// @brief The head of the singly-linked list of StackEntries. Functions push
231 /// and pop onto this in their prologue and epilogue.
233 /// Since there is only a global list, this technique is not threadsafe.
234 StackEntry *llvm_gc_root_chain;
236 /// @brief Calls Visitor(root, meta) for each GC root on the stack.
237 /// root and meta are exactly the values passed to
240 /// Visitor could be a function to recursively mark live objects. Or it
241 /// might copy them to another heap or generation.
243 /// @param Visitor A function to invoke for every GC root on the stack.
244 void visitGCRoots(void (*Visitor)(void **Root, const void *Meta)) {
245 for (StackEntry *R = llvm_gc_root_chain; R; R = R->Next) {
248 // For roots [0, NumMeta), the metadata pointer is in the FrameMap.
249 for (unsigned e = R->Map->NumMeta; i != e; ++i)
250 Visitor(&R->Roots[i], R->Map->Meta[i]);
252 // For roots [NumMeta, NumRoots), the metadata pointer is null.
253 for (unsigned e = R->Map->NumRoots; i != e; ++i)
254 Visitor(&R->Roots[i], NULL);
258 About the shadow stack
259 ----------------------
261 Unlike many GC algorithms which rely on a cooperative code generator to compile
262 stack maps, this algorithm carefully maintains a linked list of stack roots
263 [:ref:`Henderson2002 <henderson02>`]. This so-called "shadow stack" mirrors the
264 machine stack. Maintaining this data structure is slower than using a stack map
265 compiled into the executable as constant data, but has a significant portability
266 advantage because it requires no special support from the target code generator,
267 and does not require tricky platform-specific code to crawl the machine stack.
269 The tradeoff for this simplicity and portability is:
271 * High overhead per function call.
275 Still, it's an easy way to get started. After your compiler and runtime are up
276 and running, writing a :ref:`plugin <plugin>` will allow you to take advantage
277 of :ref:`more advanced GC features <collector-algos>` of LLVM in order to
285 This section describes the garbage collection facilities provided by the
286 :doc:`LLVM intermediate representation <LangRef>`. The exact behavior of these
287 IR features is specified by the binary interface implemented by a :ref:`code
288 generation plugin <plugin>`, not by this document.
290 These facilities are limited to those strictly necessary; they are not intended
291 to be a complete interface to any garbage collector. A program will need to
292 interface with the GC library using the facilities provided by that program.
294 Specifying GC code generation: ``gc "..."``
295 -------------------------------------------
299 define ty @name(...) gc "name" { ...
301 The ``gc`` function attribute is used to specify the desired GC style to the
302 compiler. Its programmatic equivalent is the ``setGC`` method of ``Function``.
304 Setting ``gc "name"`` on a function triggers a search for a matching code
305 generation plugin "*name*"; it is that plugin which defines the exact nature of
306 the code generated to support GC. If none is found, the compiler will raise an
309 Specifying the GC style on a per-function basis allows LLVM to link together
310 programs that use different garbage collection algorithms (or none at all).
314 Identifying GC roots on the stack: ``llvm.gcroot``
315 --------------------------------------------------
319 void @llvm.gcroot(i8** %ptrloc, i8* %metadata)
321 The ``llvm.gcroot`` intrinsic is used to inform LLVM that a stack variable
322 references an object on the heap and is to be tracked for garbage collection.
323 The exact impact on generated code is specified by a :ref:`compiler plugin
324 <plugin>`. All calls to ``llvm.gcroot`` **must** reside inside the first basic
327 A compiler which uses mem2reg to raise imperative code using ``alloca`` into SSA
328 form need only add a call to ``@llvm.gcroot`` for those variables which a
329 pointers into the GC heap.
331 It is also important to mark intermediate values with ``llvm.gcroot``. For
332 example, consider ``h(f(), g())``. Beware leaking the result of ``f()`` in the
333 case that ``g()`` triggers a collection. Note, that stack variables must be
334 initialized and marked with ``llvm.gcroot`` in function's prologue.
336 The first argument **must** be a value referring to an alloca instruction or a
337 bitcast of an alloca. The second contains a pointer to metadata that should be
338 associated with the pointer, and **must** be a constant or global value
339 address. If your target collector uses tags, use a null pointer for metadata.
341 The ``%metadata`` argument can be used to avoid requiring heap objects to have
342 'isa' pointers or tag bits. [Appel89_, Goldberg91_, Tolmach94_] If specified,
343 its value will be tracked along with the location of the pointer in the stack
346 Consider the following fragment of Java code:
351 Object X; // A null-initialized reference to an object
355 This block (which may be located in the middle of a function or in a loop nest),
356 could be compiled to this LLVM code:
361 ;; In the entry block for the function, allocate the
362 ;; stack space for X, which is an LLVM pointer.
365 ;; Tell LLVM that the stack space is a stack root.
366 ;; Java has type-tags on objects, so we pass null as metadata.
367 %tmp = bitcast %Object** %X to i8**
368 call void @llvm.gcroot(i8** %tmp, i8* null)
371 ;; "CodeBlock" is the block corresponding to the start
372 ;; of the scope above.
374 ;; Java null-initializes pointers.
375 store %Object* null, %Object** %X
379 ;; As the pointer goes out of scope, store a null value into
380 ;; it, to indicate that the value is no longer live.
381 store %Object* null, %Object** %X
384 Reading and writing references in the heap
385 ------------------------------------------
387 Some collectors need to be informed when the mutator (the program that needs
388 garbage collection) either reads a pointer from or writes a pointer to a field
389 of a heap object. The code fragments inserted at these points are called *read
390 barriers* and *write barriers*, respectively. The amount of code that needs to
391 be executed is usually quite small and not on the critical path of any
392 computation, so the overall performance impact of the barrier is tolerable.
394 Barriers often require access to the *object pointer* rather than the *derived
395 pointer* (which is a pointer to the field within the object). Accordingly,
396 these intrinsics take both pointers as separate arguments for completeness. In
397 this snippet, ``%object`` is the object pointer, and ``%derived`` is the derived
403 %class.Array = type { %class.Object, i32, [0 x %class.Object*] }
406 ;; Load the object pointer from a gcroot.
407 %object = load %class.Array** %object_addr
409 ;; Compute the derived pointer.
410 %derived = getelementptr %object, i32 0, i32 2, i32 %n
412 LLVM does not enforce this relationship between the object and derived pointer
413 (although a :ref:`plugin <plugin>` might). However, it would be an unusual
414 collector that violated it.
416 The use of these intrinsics is naturally optional if the target GC does require
417 the corresponding barrier. Such a GC plugin will replace the intrinsic calls
418 with the corresponding ``load`` or ``store`` instruction if they are used.
420 Write barrier: ``llvm.gcwrite``
421 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
425 void @llvm.gcwrite(i8* %value, i8* %object, i8** %derived)
427 For write barriers, LLVM provides the ``llvm.gcwrite`` intrinsic function. It
428 has exactly the same semantics as a non-volatile ``store`` to the derived
429 pointer (the third argument). The exact code generated is specified by a
430 compiler :ref:`plugin <plugin>`.
432 Many important algorithms require write barriers, including generational and
433 concurrent collectors. Additionally, write barriers could be used to implement
436 Read barrier: ``llvm.gcread``
437 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
441 i8* @llvm.gcread(i8* %object, i8** %derived)
443 For read barriers, LLVM provides the ``llvm.gcread`` intrinsic function. It has
444 exactly the same semantics as a non-volatile ``load`` from the derived pointer
445 (the second argument). The exact code generated is specified by a
446 :ref:`compiler plugin <plugin>`.
448 Read barriers are needed by fewer algorithms than write barriers, and may have a
449 greater performance impact since pointer reads are more frequent than writes.
453 Implementing a collector plugin
454 ===============================
456 User code specifies which GC code generation to use with the ``gc`` function
457 attribute or, equivalently, with the ``setGC`` method of ``Function``.
459 To implement a GC plugin, it is necessary to subclass ``llvm::GCStrategy``,
460 which can be accomplished in a few lines of boilerplate code. LLVM's
461 infrastructure provides access to several important algorithms. For an
462 uncontroversial collector, all that remains may be to compile LLVM's computed
463 stack map to assembly code (using the binary representation expected by the
464 runtime library). This can be accomplished in about 100 lines of code.
466 This is not the appropriate place to implement a garbage collected heap or a
467 garbage collector itself. That code should exist in the language's runtime
468 library. The compiler plugin is responsible for generating code which conforms
469 to the binary interface defined by library, most essentially the :ref:`stack map
472 To subclass ``llvm::GCStrategy`` and register it with the compiler:
476 // lib/MyGC/MyGC.cpp - Example LLVM GC plugin
478 #include "llvm/CodeGen/GCStrategy.h"
479 #include "llvm/CodeGen/GCMetadata.h"
480 #include "llvm/Support/Compiler.h"
482 using namespace llvm;
485 class LLVM_LIBRARY_VISIBILITY MyGC : public GCStrategy {
490 GCRegistry::Add<MyGC>
491 X("mygc", "My bespoke garbage collector.");
494 This boilerplate collector does nothing. More specifically:
496 * ``llvm.gcread`` calls are replaced with the corresponding ``load``
499 * ``llvm.gcwrite`` calls are replaced with the corresponding ``store``
502 * No safe points are added to the code.
504 * The stack map is not compiled into the executable.
506 Using the LLVM makefiles (like the `sample project
507 <http://llvm.org/viewvc/llvm-project/llvm/trunk/projects/sample/>`__), this code
508 can be compiled as a plugin using a simple makefile:
518 include $(LEVEL)/Makefile.common
520 Once the plugin is compiled, code using it may be compiled using ``llc
521 -load=MyGC.so`` (though MyGC.so may have some other platform-specific
527 define void @f() gc "mygc" {
531 $ llvm-as < sample.ll | llc -load=MyGC.so
533 It is also possible to statically link the collector plugin into tools, such as
534 a language-specific compiler front-end.
538 Overview of available features
539 ------------------------------
541 ``GCStrategy`` provides a range of features through which a plugin may do useful
542 work. Some of these are callbacks, some are algorithms that can be enabled,
543 disabled, or customized. This matrix summarizes the supported (and planned)
544 features and correlates them with the collection techniques which typically
547 .. |v| unicode:: 0x2714
550 .. |x| unicode:: 0x2718
553 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
554 | Algorithm | Done | Shadow | refcount | mark- | copying | incremental | threaded | concurrent |
555 | | | stack | | sweep | | | | |
556 +============+======+========+==========+=======+=========+=============+==========+============+
557 | stack map | |v| | | | |x| | |x| | |x| | |x| | |x| |
558 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
559 | initialize | |v| | |x| | |x| | |x| | |x| | |x| | |x| | |x| |
560 | roots | | | | | | | | |
561 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
562 | derived | NO | | | | | | **N**\* | **N**\* |
563 | pointers | | | | | | | | |
564 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
565 | **custom | |v| | | | | | | | |
566 | lowering** | | | | | | | | |
567 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
568 | *gcroot* | |v| | |x| | |x| | | | | | |
569 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
570 | *gcwrite* | |v| | | |x| | | | |x| | | |x| |
571 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
572 | *gcread* | |v| | | | | | | | |x| |
573 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
574 | **safe | | | | | | | | |
575 | points** | | | | | | | | |
576 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
577 | *in | |v| | | | |x| | |x| | |x| | |x| | |x| |
578 | calls* | | | | | | | | |
579 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
580 | *before | |v| | | | | | | |x| | |x| |
581 | calls* | | | | | | | | |
582 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
583 | *for | NO | | | | | | **N** | **N** |
584 | loops* | | | | | | | | |
585 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
586 | *before | |v| | | | | | | |x| | |x| |
587 | escape* | | | | | | | | |
588 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
589 | emit code | NO | | | | | | **N** | **N** |
590 | at safe | | | | | | | | |
591 | points | | | | | | | | |
592 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
593 | **output** | | | | | | | | |
594 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
595 | *assembly* | |v| | | | |x| | |x| | |x| | |x| | |x| |
596 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
597 | *JIT* | NO | | | **?** | **?** | **?** | **?** | **?** |
598 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
599 | *obj* | NO | | | **?** | **?** | **?** | **?** | **?** |
600 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
601 | live | NO | | | **?** | **?** | **?** | **?** | **?** |
602 | analysis | | | | | | | | |
603 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
604 | register | NO | | | **?** | **?** | **?** | **?** | **?** |
605 | map | | | | | | | | |
606 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
607 | \* Derived pointers only pose a hasard to copying collections. |
608 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
609 | **?** denotes a feature which could be utilized if available. |
610 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
612 To be clear, the collection techniques above are defined as:
615 The mutator carefully maintains a linked list of stack roots.
618 The mutator maintains a reference count for each object and frees an object
619 when its count falls to zero.
622 When the heap is exhausted, the collector marks reachable objects starting
623 from the roots, then deallocates unreachable objects in a sweep phase.
626 As reachability analysis proceeds, the collector copies objects from one heap
627 area to another, compacting them in the process. Copying collectors enable
628 highly efficient "bump pointer" allocation and can improve locality of
632 (Including generational collectors.) Incremental collectors generally have all
633 the properties of a copying collector (regardless of whether the mature heap
634 is compacting), but bring the added complexity of requiring write barriers.
637 Denotes a multithreaded mutator; the collector must still stop the mutator
638 ("stop the world") before beginning reachability analysis. Stopping a
639 multithreaded mutator is a complicated problem. It generally requires highly
640 platform specific code in the runtime, and the production of carefully
641 designed machine code at safe points.
644 In this technique, the mutator and the collector run concurrently, with the
645 goal of eliminating pause times. In a *cooperative* collector, the mutator
646 further aids with collection should a pause occur, allowing collection to take
647 advantage of multiprocessor hosts. The "stop the world" problem of threaded
648 collectors is generally still present to a limited extent. Sophisticated
649 marking algorithms are necessary. Read barriers may be necessary.
651 As the matrix indicates, LLVM's garbage collection infrastructure is already
652 suitable for a wide variety of collectors, but does not currently extend to
653 multithreaded programs. This will be added in the future as there is
661 LLVM automatically computes a stack map. One of the most important features
662 of a ``GCStrategy`` is to compile this information into the executable in
663 the binary representation expected by the runtime library.
665 The stack map consists of the location and identity of each GC root in the
666 each function in the module. For each root:
668 * ``RootNum``: The index of the root.
670 * ``StackOffset``: The offset of the object relative to the frame pointer.
672 * ``RootMetadata``: The value passed as the ``%metadata`` parameter to the
673 ``@llvm.gcroot`` intrinsic.
675 Also, for the function as a whole:
677 * ``getFrameSize()``: The overall size of the function's initial stack frame,
678 not accounting for any dynamic allocation.
680 * ``roots_size()``: The count of roots in the function.
682 To access the stack map, use ``GCFunctionMetadata::roots_begin()`` and
683 -``end()`` from the :ref:`GCMetadataPrinter <assembly>`:
687 for (iterator I = begin(), E = end(); I != E; ++I) {
688 GCFunctionInfo *FI = *I;
689 unsigned FrameSize = FI->getFrameSize();
690 size_t RootCount = FI->roots_size();
692 for (GCFunctionInfo::roots_iterator RI = FI->roots_begin(),
693 RE = FI->roots_end();
695 int RootNum = RI->Num;
696 int RootStackOffset = RI->StackOffset;
697 Constant *RootMetadata = RI->Metadata;
701 If the ``llvm.gcroot`` intrinsic is eliminated before code generation by a
702 custom lowering pass, LLVM will compute an empty stack map. This may be useful
703 for collector plugins which implement reference counting or a shadow stack.
707 Initializing roots to null: ``InitRoots``
708 -----------------------------------------
716 When set, LLVM will automatically initialize each root to ``null`` upon entry to
717 the function. This prevents the GC's sweep phase from visiting uninitialized
718 pointers, which will almost certainly cause it to crash. This initialization
719 occurs before custom lowering, so the two may be used together.
721 Since LLVM does not yet compute liveness information, there is no means of
722 distinguishing an uninitialized stack root from an initialized one. Therefore,
723 this feature should be used by all GC plugins. It is enabled by default.
725 Custom lowering of intrinsics: ``CustomRoots``, ``CustomReadBarriers``, and ``CustomWriteBarriers``
726 ---------------------------------------------------------------------------------------------------
728 For GCs which use barriers or unusual treatment of stack roots, these flags
729 allow the collector to perform arbitrary transformations of the LLVM IR:
733 class MyGC : public GCStrategy {
737 CustomReadBarriers = true;
738 CustomWriteBarriers = true;
741 virtual bool initializeCustomLowering(Module &M);
742 virtual bool performCustomLowering(Function &F);
745 If any of these flags are set, then LLVM suppresses its default lowering for the
746 corresponding intrinsics and instead calls ``performCustomLowering``.
748 LLVM's default action for each intrinsic is as follows:
750 * ``llvm.gcroot``: Leave it alone. The code generator must see it or the stack
751 map will not be computed.
753 * ``llvm.gcread``: Substitute a ``load`` instruction.
755 * ``llvm.gcwrite``: Substitute a ``store`` instruction.
757 If ``CustomReadBarriers`` or ``CustomWriteBarriers`` are specified, then
758 ``performCustomLowering`` **must** eliminate the corresponding barriers.
760 ``performCustomLowering`` must comply with the same restrictions as
761 :ref:`FunctionPass::runOnFunction <writing-an-llvm-pass-runOnFunction>`
762 Likewise, ``initializeCustomLowering`` has the same semantics as
763 :ref:`Pass::doInitialization(Module&)
764 <writing-an-llvm-pass-doInitialization-mod>`
766 The following can be used as a template:
770 #include "llvm/Module.h"
771 #include "llvm/IntrinsicInst.h"
773 bool MyGC::initializeCustomLowering(Module &M) {
777 bool MyGC::performCustomLowering(Function &F) {
778 bool MadeChange = false;
780 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
781 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; )
782 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++))
783 if (Function *F = CI->getCalledFunction())
784 switch (F->getIntrinsicID()) {
785 case Intrinsic::gcwrite:
786 // Handle llvm.gcwrite.
787 CI->eraseFromParent();
790 case Intrinsic::gcread:
791 // Handle llvm.gcread.
792 CI->eraseFromParent();
795 case Intrinsic::gcroot:
796 // Handle llvm.gcroot.
797 CI->eraseFromParent();
807 Generating safe points: ``NeededSafePoints``
808 --------------------------------------------
810 LLVM can compute four kinds of safe points:
815 /// PointKind - The type of a collector-safe point.
818 Loop, //< Instr is a loop (backwards branch).
819 Return, //< Instr is a return instruction.
820 PreCall, //< Instr is a call instruction.
821 PostCall //< Instr is the return address of a call.
825 A collector can request any combination of the four by setting the
826 ``NeededSafePoints`` mask:
831 NeededSafePoints = 1 << GC::Loop
837 It can then use the following routines to access safe points.
841 for (iterator I = begin(), E = end(); I != E; ++I) {
842 GCFunctionInfo *MD = *I;
843 size_t PointCount = MD->size();
845 for (GCFunctionInfo::iterator PI = MD->begin(),
846 PE = MD->end(); PI != PE; ++PI) {
847 GC::PointKind PointKind = PI->Kind;
848 unsigned PointNum = PI->Num;
852 Almost every collector requires ``PostCall`` safe points, since these correspond
853 to the moments when the function is suspended during a call to a subroutine.
855 Threaded programs generally require ``Loop`` safe points to guarantee that the
856 application will reach a safe point within a bounded amount of time, even if it
857 is executing a long-running loop which contains no function calls.
859 Threaded collectors may also require ``Return`` and ``PreCall`` safe points to
860 implement "stop the world" techniques using self-modifying code, where it is
861 important that the program not exit the function without reaching a safe point
862 (because only the topmost function has been patched).
866 Emitting assembly code: ``GCMetadataPrinter``
867 ---------------------------------------------
869 LLVM allows a plugin to print arbitrary assembly code before and after the rest
870 of a module's assembly code. At the end of the module, the GC can compile the
871 LLVM stack map into assembly code. (At the beginning, this information is not
874 Since AsmWriter and CodeGen are separate components of LLVM, a separate abstract
875 base class and registry is provided for printing assembly code, the
876 ``GCMetadaPrinter`` and ``GCMetadataPrinterRegistry``. The AsmWriter will look
877 for such a subclass if the ``GCStrategy`` sets ``UsesMetadata``:
885 This separation allows JIT-only clients to be smaller.
887 Note that LLVM does not currently have analogous APIs to support code generation
888 in the JIT, nor using the object writers.
892 // lib/MyGC/MyGCPrinter.cpp - Example LLVM GC printer
894 #include "llvm/CodeGen/GCMetadataPrinter.h"
895 #include "llvm/Support/Compiler.h"
897 using namespace llvm;
900 class LLVM_LIBRARY_VISIBILITY MyGCPrinter : public GCMetadataPrinter {
902 virtual void beginAssembly(std::ostream &OS, AsmPrinter &AP,
903 const TargetAsmInfo &TAI);
905 virtual void finishAssembly(std::ostream &OS, AsmPrinter &AP,
906 const TargetAsmInfo &TAI);
909 GCMetadataPrinterRegistry::Add<MyGCPrinter>
910 X("mygc", "My bespoke garbage collector.");
913 The collector should use ``AsmPrinter`` and ``TargetAsmInfo`` to print portable
914 assembly code to the ``std::ostream``. The collector itself contains the stack
915 map for the entire module, and may access the ``GCFunctionInfo`` using its own
916 ``begin()`` and ``end()`` methods. Here's a realistic example:
920 #include "llvm/CodeGen/AsmPrinter.h"
921 #include "llvm/Function.h"
922 #include "llvm/Target/TargetMachine.h"
923 #include "llvm/DataLayout.h"
924 #include "llvm/Target/TargetAsmInfo.h"
926 void MyGCPrinter::beginAssembly(std::ostream &OS, AsmPrinter &AP,
927 const TargetAsmInfo &TAI) {
931 void MyGCPrinter::finishAssembly(std::ostream &OS, AsmPrinter &AP,
932 const TargetAsmInfo &TAI) {
933 // Set up for emitting addresses.
934 const char *AddressDirective;
936 if (AP.TM.getDataLayout()->getPointerSize() == sizeof(int32_t)) {
937 AddressDirective = TAI.getData32bitsDirective();
940 AddressDirective = TAI.getData64bitsDirective();
944 // Put this in the data section.
945 AP.SwitchToDataSection(TAI.getDataSection());
947 // For each function...
948 for (iterator FI = begin(), FE = end(); FI != FE; ++FI) {
949 GCFunctionInfo &MD = **FI;
951 // Emit this data structure:
954 // int32_t PointCount;
956 // void *SafePointAddress;
957 // int32_t LiveCount;
958 // int32_t LiveOffsets[LiveCount];
959 // } Points[PointCount];
960 // } __gcmap_<FUNCTIONNAME>;
962 // Align to address width.
963 AP.EmitAlignment(AddressAlignLog);
965 // Emit the symbol by which the stack map entry can be found.
967 Symbol += TAI.getGlobalPrefix();
968 Symbol += "__gcmap_";
969 Symbol += MD.getFunction().getName();
970 if (const char *GlobalDirective = TAI.getGlobalDirective())
971 OS << GlobalDirective << Symbol << "\n";
972 OS << TAI.getGlobalPrefix() << Symbol << ":\n";
975 AP.EmitInt32(MD.size());
976 AP.EOL("safe point count");
978 // And each safe point...
979 for (GCFunctionInfo::iterator PI = MD.begin(),
980 PE = MD.end(); PI != PE; ++PI) {
981 // Align to address width.
982 AP.EmitAlignment(AddressAlignLog);
984 // Emit the address of the safe point.
985 OS << AddressDirective
986 << TAI.getPrivateGlobalPrefix() << "label" << PI->Num;
987 AP.EOL("safe point address");
989 // Emit the stack frame size.
990 AP.EmitInt32(MD.getFrameSize());
991 AP.EOL("stack frame size");
993 // Emit the number of live roots in the function.
994 AP.EmitInt32(MD.live_size(PI));
995 AP.EOL("live root count");
997 // And for each live root...
998 for (GCFunctionInfo::live_iterator LI = MD.live_begin(PI),
999 LE = MD.live_end(PI);
1001 // Print its offset within the stack frame.
1002 AP.EmitInt32(LI->StackOffset);
1003 AP.EOL("stack offset");
1014 [Appel89] Runtime Tags Aren't Necessary. Andrew W. Appel. Lisp and Symbolic
1015 Computation 19(7):703-705, July 1989.
1019 [Goldberg91] Tag-free garbage collection for strongly typed programming
1020 languages. Benjamin Goldberg. ACM SIGPLAN PLDI'91.
1024 [Tolmach94] Tag-free garbage collection using explicit type parameters. Andrew
1025 Tolmach. Proceedings of the 1994 ACM conference on LISP and functional
1030 [Henderson2002] `Accurate Garbage Collection in an Uncooperative Environment
1031 <http://citeseer.ist.psu.edu/henderson02accurate.html>`__