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.
57 LLVM's intermediate representation provides :ref:`garbage collection intrinsics
58 <gc_intrinsics>` that offer support for a broad class of collector models. For
59 instance, the intrinsics permit:
61 * semi-space collectors
63 * mark-sweep collectors
65 * generational collectors
69 * incremental collectors
71 * concurrent collectors
73 * cooperative collectors
75 We hope that the primitive support built into the LLVM IR is sufficient to
76 support a broad class of garbage collected languages including Scheme, ML, Java,
77 C#, Perl, Python, Lua, Ruby, other scripting languages, and more.
79 However, LLVM does not itself provide a garbage collector --- this should be
80 part of your language's runtime library. LLVM provides a framework for compile
81 time :ref:`code generation plugins <plugin>`. The role of these plugins is to
82 generate code and data structures which conforms to the *binary interface*
83 specified by the *runtime library*. This is similar to the relationship between
84 LLVM and DWARF debugging info, for example. The difference primarily lies in
85 the lack of an established standard in the domain of garbage collection --- thus
88 The aspects of the binary interface with which LLVM's GC support is
91 * Creation of GC-safe points within code where collection is allowed to execute
94 * Computation of the stack map. For each safe point in the code, object
95 references within the stack frame must be identified so that the collector may
96 traverse and perhaps update them.
98 * Write barriers when storing object references to the heap. These are commonly
99 used to optimize incremental scans in generational collectors.
101 * Emission of read barriers when loading object references. These are useful
102 for interoperating with concurrent collectors.
104 There are additional areas that LLVM does not directly address:
106 * Registration of global roots with the runtime.
108 * Registration of stack map entries with the runtime.
110 * The functions used by the program to allocate memory, trigger a collection,
113 * Computation or compilation of type maps, or registration of them with the
114 runtime. These are used to crawl the heap for object references.
116 In general, LLVM's support for GC does not include features which can be
117 adequately addressed with other features of the IR and does not specify a
118 particular binary interface. On the plus side, this means that you should be
119 able to integrate LLVM with an existing runtime. On the other hand, it leaves a
120 lot of work for the developer of a novel language. However, it's easy to get
121 started quickly and scale up to a more sophisticated implementation as your
129 Using a GC with LLVM implies many things, for example:
131 * Write a runtime library or find an existing one which implements a GC heap.
133 #. Implement a memory allocator.
135 #. Design a binary interface for the stack map, used to identify references
136 within a stack frame on the machine stack.\*
138 #. Implement a stack crawler to discover functions on the call stack.\*
140 #. Implement a registry for global roots.
142 #. Design a binary interface for type maps, used to identify references
145 #. Implement a collection routine bringing together all of the above.
147 * Emit compatible code from your compiler.
149 * Initialization in the main function.
151 * Use the ``gc "..."`` attribute to enable GC code generation (or
154 * Use ``@llvm.gcroot`` to mark stack roots.
156 * Use ``@llvm.gcread`` and/or ``@llvm.gcwrite`` to manipulate GC references,
159 * Allocate memory using the GC allocation routine provided by the runtime
162 * Generate type maps according to your runtime's binary interface.
164 * Write a compiler plugin to interface LLVM with the runtime library.\*
166 * Lower ``@llvm.gcread`` and ``@llvm.gcwrite`` to appropriate code
169 * Compile LLVM's stack map to the binary form expected by the runtime.
171 * Load the plugin into the compiler. Use ``llc -load`` or link the plugin
172 statically with your language's compiler.\*
174 * Link program executables with the runtime.
176 To help with several of these tasks (those indicated with a \*), LLVM includes a
177 highly portable, built-in ShadowStack code generator. It is compiled into
178 ``llc`` and works even with the interpreter and C backends.
180 .. _quickstart-compiler:
185 To turn the shadow stack on for your functions, first call:
189 F.setGC("shadow-stack");
191 for each function your compiler emits. Since the shadow stack is built into
192 LLVM, you do not need to load a plugin.
194 Your compiler must also use ``@llvm.gcroot`` as documented. Don't forget to
195 create a root for each intermediate value that is generated when evaluating an
196 expression. In ``h(f(), g())``, the result of ``f()`` could easily be collected
197 if evaluating ``g()`` triggers a collection.
199 There's no need to use ``@llvm.gcread`` and ``@llvm.gcwrite`` over plain
200 ``load`` and ``store`` for now. You will need them when switching to a more
203 .. _quickstart-runtime:
208 The shadow stack doesn't imply a memory allocation algorithm. A semispace
209 collector or building atop ``malloc`` are great places to start, and can be
210 implemented with very little code.
212 When it comes time to collect, however, your runtime needs to traverse the stack
213 roots, and for this it needs to integrate with the shadow stack. Luckily, doing
214 so is very simple. (This code is heavily commented to help you understand the
215 data structure, but there are only 20 lines of meaningful code.)
219 /// @brief The map for a single function's stack frame. One of these is
220 /// compiled as constant data into the executable for each function.
222 /// Storage of metadata values is elided if the %metadata parameter to
223 /// @llvm.gcroot is null.
225 int32_t NumRoots; //< Number of roots in stack frame.
226 int32_t NumMeta; //< Number of metadata entries. May be < NumRoots.
227 const void *Meta[0]; //< Metadata for each root.
230 /// @brief A link in the dynamic shadow stack. One of these is embedded in
231 /// the stack frame of each function on the call stack.
233 StackEntry *Next; //< Link to next stack entry (the caller's).
234 const FrameMap *Map; //< Pointer to constant FrameMap.
235 void *Roots[0]; //< Stack roots (in-place array).
238 /// @brief The head of the singly-linked list of StackEntries. Functions push
239 /// and pop onto this in their prologue and epilogue.
241 /// Since there is only a global list, this technique is not threadsafe.
242 StackEntry *llvm_gc_root_chain;
244 /// @brief Calls Visitor(root, meta) for each GC root on the stack.
245 /// root and meta are exactly the values passed to
248 /// Visitor could be a function to recursively mark live objects. Or it
249 /// might copy them to another heap or generation.
251 /// @param Visitor A function to invoke for every GC root on the stack.
252 void visitGCRoots(void (*Visitor)(void **Root, const void *Meta)) {
253 for (StackEntry *R = llvm_gc_root_chain; R; R = R->Next) {
256 // For roots [0, NumMeta), the metadata pointer is in the FrameMap.
257 for (unsigned e = R->Map->NumMeta; i != e; ++i)
258 Visitor(&R->Roots[i], R->Map->Meta[i]);
260 // For roots [NumMeta, NumRoots), the metadata pointer is null.
261 for (unsigned e = R->Map->NumRoots; i != e; ++i)
262 Visitor(&R->Roots[i], NULL);
268 About the shadow stack
269 ----------------------
271 Unlike many GC algorithms which rely on a cooperative code generator to compile
272 stack maps, this algorithm carefully maintains a linked list of stack roots
273 [:ref:`Henderson2002 <henderson02>`]. This so-called "shadow stack" mirrors the
274 machine stack. Maintaining this data structure is slower than using a stack map
275 compiled into the executable as constant data, but has a significant portability
276 advantage because it requires no special support from the target code generator,
277 and does not require tricky platform-specific code to crawl the machine stack.
279 The tradeoff for this simplicity and portability is:
281 * High overhead per function call.
285 Still, it's an easy way to get started. After your compiler and runtime are up
286 and running, writing a plugin_ will allow you to take advantage of :ref:`more
287 advanced GC features <collector-algos>` of LLVM in order to improve performance.
294 This section describes the garbage collection facilities provided by the
295 :doc:`LLVM intermediate representation <LangRef>`. The exact behavior of these
296 IR features is specified by the binary interface implemented by a :ref:`code
297 generation plugin <plugin>`, not by this document.
299 These facilities are limited to those strictly necessary; they are not intended
300 to be a complete interface to any garbage collector. A program will need to
301 interface with the GC library using the facilities provided by that program.
305 Specifying GC code generation: ``gc "..."``
306 -------------------------------------------
310 define ty @name(...) gc "name" { ...
312 The ``gc`` function attribute is used to specify the desired GC style to the
313 compiler. Its programmatic equivalent is the ``setGC`` method of ``Function``.
315 Setting ``gc "name"`` on a function triggers a search for a matching code
316 generation plugin "*name*"; it is that plugin which defines the exact nature of
317 the code generated to support GC. If none is found, the compiler will raise an
320 Specifying the GC style on a per-function basis allows LLVM to link together
321 programs that use different garbage collection algorithms (or none at all).
325 Identifying GC roots on the stack: ``llvm.gcroot``
326 --------------------------------------------------
330 void @llvm.gcroot(i8** %ptrloc, i8* %metadata)
332 The ``llvm.gcroot`` intrinsic is used to inform LLVM that a stack variable
333 references an object on the heap and is to be tracked for garbage collection.
334 The exact impact on generated code is specified by a :ref:`compiler plugin
335 <plugin>`. All calls to ``llvm.gcroot`` **must** reside inside the first basic
338 A compiler which uses mem2reg to raise imperative code using ``alloca`` into SSA
339 form need only add a call to ``@llvm.gcroot`` for those variables which a
340 pointers into the GC heap.
342 It is also important to mark intermediate values with ``llvm.gcroot``. For
343 example, consider ``h(f(), g())``. Beware leaking the result of ``f()`` in the
344 case that ``g()`` triggers a collection. Note, that stack variables must be
345 initialized and marked with ``llvm.gcroot`` in function's prologue.
347 The first argument **must** be a value referring to an alloca instruction or a
348 bitcast of an alloca. The second contains a pointer to metadata that should be
349 associated with the pointer, and **must** be a constant or global value
350 address. If your target collector uses tags, use a null pointer for metadata.
352 The ``%metadata`` argument can be used to avoid requiring heap objects to have
353 'isa' pointers or tag bits. [Appel89_, Goldberg91_, Tolmach94_] If specified,
354 its value will be tracked along with the location of the pointer in the stack
357 Consider the following fragment of Java code:
362 Object X; // A null-initialized reference to an object
366 This block (which may be located in the middle of a function or in a loop nest),
367 could be compiled to this LLVM code:
372 ;; In the entry block for the function, allocate the
373 ;; stack space for X, which is an LLVM pointer.
376 ;; Tell LLVM that the stack space is a stack root.
377 ;; Java has type-tags on objects, so we pass null as metadata.
378 %tmp = bitcast %Object** %X to i8**
379 call void @llvm.gcroot(i8** %tmp, i8* null)
382 ;; "CodeBlock" is the block corresponding to the start
383 ;; of the scope above.
385 ;; Java null-initializes pointers.
386 store %Object* null, %Object** %X
390 ;; As the pointer goes out of scope, store a null value into
391 ;; it, to indicate that the value is no longer live.
392 store %Object* null, %Object** %X
397 Reading and writing references in the heap
398 ------------------------------------------
400 Some collectors need to be informed when the mutator (the program that needs
401 garbage collection) either reads a pointer from or writes a pointer to a field
402 of a heap object. The code fragments inserted at these points are called *read
403 barriers* and *write barriers*, respectively. The amount of code that needs to
404 be executed is usually quite small and not on the critical path of any
405 computation, so the overall performance impact of the barrier is tolerable.
407 Barriers often require access to the *object pointer* rather than the *derived
408 pointer* (which is a pointer to the field within the object). Accordingly,
409 these intrinsics take both pointers as separate arguments for completeness. In
410 this snippet, ``%object`` is the object pointer, and ``%derived`` is the derived
416 %class.Array = type { %class.Object, i32, [0 x %class.Object*] }
419 ;; Load the object pointer from a gcroot.
420 %object = load %class.Array** %object_addr
422 ;; Compute the derived pointer.
423 %derived = getelementptr %object, i32 0, i32 2, i32 %n
425 LLVM does not enforce this relationship between the object and derived pointer
426 (although a plugin_ might). However, it would be an unusual collector that
429 The use of these intrinsics is naturally optional if the target GC does require
430 the corresponding barrier. Such a GC plugin will replace the intrinsic calls
431 with the corresponding ``load`` or ``store`` instruction if they are used.
435 Write barrier: ``llvm.gcwrite``
436 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
440 void @llvm.gcwrite(i8* %value, i8* %object, i8** %derived)
442 For write barriers, LLVM provides the ``llvm.gcwrite`` intrinsic function. It
443 has exactly the same semantics as a non-volatile ``store`` to the derived
444 pointer (the third argument). The exact code generated is specified by a
447 Many important algorithms require write barriers, including generational and
448 concurrent collectors. Additionally, write barriers could be used to implement
453 Read barrier: ``llvm.gcread``
454 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
458 i8* @llvm.gcread(i8* %object, i8** %derived)
460 For read barriers, LLVM provides the ``llvm.gcread`` intrinsic function. It has
461 exactly the same semantics as a non-volatile ``load`` from the derived pointer
462 (the second argument). The exact code generated is specified by a compiler
465 Read barriers are needed by fewer algorithms than write barriers, and may have a
466 greater performance impact since pointer reads are more frequent than writes.
470 Implementing a collector plugin
471 ===============================
473 User code specifies which GC code generation to use with the ``gc`` function
474 attribute or, equivalently, with the ``setGC`` method of ``Function``.
476 To implement a GC plugin, it is necessary to subclass ``llvm::GCStrategy``,
477 which can be accomplished in a few lines of boilerplate code. LLVM's
478 infrastructure provides access to several important algorithms. For an
479 uncontroversial collector, all that remains may be to compile LLVM's computed
480 stack map to assembly code (using the binary representation expected by the
481 runtime library). This can be accomplished in about 100 lines of code.
483 This is not the appropriate place to implement a garbage collected heap or a
484 garbage collector itself. That code should exist in the language's runtime
485 library. The compiler plugin is responsible for generating code which conforms
486 to the binary interface defined by library, most essentially the :ref:`stack map
489 To subclass ``llvm::GCStrategy`` and register it with the compiler:
493 // lib/MyGC/MyGC.cpp - Example LLVM GC plugin
495 #include "llvm/CodeGen/GCStrategy.h"
496 #include "llvm/CodeGen/GCMetadata.h"
497 #include "llvm/Support/Compiler.h"
499 using namespace llvm;
502 class LLVM_LIBRARY_VISIBILITY MyGC : public GCStrategy {
507 GCRegistry::Add<MyGC>
508 X("mygc", "My bespoke garbage collector.");
511 This boilerplate collector does nothing. More specifically:
513 * ``llvm.gcread`` calls are replaced with the corresponding ``load``
516 * ``llvm.gcwrite`` calls are replaced with the corresponding ``store``
519 * No safe points are added to the code.
521 * The stack map is not compiled into the executable.
523 Using the LLVM makefiles (like the `sample project
524 <http://llvm.org/viewvc/llvm-project/llvm/trunk/projects/sample/>`__), this code
525 can be compiled as a plugin using a simple makefile:
535 include $(LEVEL)/Makefile.common
537 Once the plugin is compiled, code using it may be compiled using ``llc
538 -load=MyGC.so`` (though MyGC.so may have some other platform-specific
544 define void @f() gc "mygc" {
548 $ llvm-as < sample.ll | llc -load=MyGC.so
550 It is also possible to statically link the collector plugin into tools, such as
551 a language-specific compiler front-end.
555 Overview of available features
556 ------------------------------
558 ``GCStrategy`` provides a range of features through which a plugin may do useful
559 work. Some of these are callbacks, some are algorithms that can be enabled,
560 disabled, or customized. This matrix summarizes the supported (and planned)
561 features and correlates them with the collection techniques which typically
564 .. |v| unicode:: 0x2714
567 .. |x| unicode:: 0x2718
570 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
571 | Algorithm | Done | Shadow | refcount | mark- | copying | incremental | threaded | concurrent |
572 | | | stack | | sweep | | | | |
573 +============+======+========+==========+=======+=========+=============+==========+============+
574 | stack map | |v| | | | |x| | |x| | |x| | |x| | |x| |
575 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
576 | initialize | |v| | |x| | |x| | |x| | |x| | |x| | |x| | |x| |
577 | roots | | | | | | | | |
578 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
579 | derived | NO | | | | | | **N**\* | **N**\* |
580 | pointers | | | | | | | | |
581 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
582 | **custom | |v| | | | | | | | |
583 | lowering** | | | | | | | | |
584 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
585 | *gcroot* | |v| | |x| | |x| | | | | | |
586 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
587 | *gcwrite* | |v| | | |x| | | | |x| | | |x| |
588 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
589 | *gcread* | |v| | | | | | | | |x| |
590 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
591 | **safe | | | | | | | | |
592 | points** | | | | | | | | |
593 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
594 | *in | |v| | | | |x| | |x| | |x| | |x| | |x| |
595 | calls* | | | | | | | | |
596 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
597 | *before | |v| | | | | | | |x| | |x| |
598 | calls* | | | | | | | | |
599 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
600 | *for | NO | | | | | | **N** | **N** |
601 | loops* | | | | | | | | |
602 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
603 | *before | |v| | | | | | | |x| | |x| |
604 | escape* | | | | | | | | |
605 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
606 | emit code | NO | | | | | | **N** | **N** |
607 | at safe | | | | | | | | |
608 | points | | | | | | | | |
609 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
610 | **output** | | | | | | | | |
611 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
612 | *assembly* | |v| | | | |x| | |x| | |x| | |x| | |x| |
613 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
614 | *JIT* | NO | | | **?** | **?** | **?** | **?** | **?** |
615 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
616 | *obj* | NO | | | **?** | **?** | **?** | **?** | **?** |
617 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
618 | live | NO | | | **?** | **?** | **?** | **?** | **?** |
619 | analysis | | | | | | | | |
620 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
621 | register | NO | | | **?** | **?** | **?** | **?** | **?** |
622 | map | | | | | | | | |
623 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
624 | \* Derived pointers only pose a hasard to copying collections. |
625 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
626 | **?** denotes a feature which could be utilized if available. |
627 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
629 To be clear, the collection techniques above are defined as:
632 The mutator carefully maintains a linked list of stack roots.
635 The mutator maintains a reference count for each object and frees an object
636 when its count falls to zero.
639 When the heap is exhausted, the collector marks reachable objects starting
640 from the roots, then deallocates unreachable objects in a sweep phase.
643 As reachability analysis proceeds, the collector copies objects from one heap
644 area to another, compacting them in the process. Copying collectors enable
645 highly efficient "bump pointer" allocation and can improve locality of
649 (Including generational collectors.) Incremental collectors generally have all
650 the properties of a copying collector (regardless of whether the mature heap
651 is compacting), but bring the added complexity of requiring write barriers.
654 Denotes a multithreaded mutator; the collector must still stop the mutator
655 ("stop the world") before beginning reachability analysis. Stopping a
656 multithreaded mutator is a complicated problem. It generally requires highly
657 platform specific code in the runtime, and the production of carefully
658 designed machine code at safe points.
661 In this technique, the mutator and the collector run concurrently, with the
662 goal of eliminating pause times. In a *cooperative* collector, the mutator
663 further aids with collection should a pause occur, allowing collection to take
664 advantage of multiprocessor hosts. The "stop the world" problem of threaded
665 collectors is generally still present to a limited extent. Sophisticated
666 marking algorithms are necessary. Read barriers may be necessary.
668 As the matrix indicates, LLVM's garbage collection infrastructure is already
669 suitable for a wide variety of collectors, but does not currently extend to
670 multithreaded programs. This will be added in the future as there is
678 LLVM automatically computes a stack map. One of the most important features
679 of a ``GCStrategy`` is to compile this information into the executable in
680 the binary representation expected by the runtime library.
682 The stack map consists of the location and identity of each GC root in the
683 each function in the module. For each root:
685 * ``RootNum``: The index of the root.
687 * ``StackOffset``: The offset of the object relative to the frame pointer.
689 * ``RootMetadata``: The value passed as the ``%metadata`` parameter to the
690 ``@llvm.gcroot`` intrinsic.
692 Also, for the function as a whole:
694 * ``getFrameSize()``: The overall size of the function's initial stack frame,
695 not accounting for any dynamic allocation.
697 * ``roots_size()``: The count of roots in the function.
699 To access the stack map, use ``GCFunctionMetadata::roots_begin()`` and
700 -``end()`` from the :ref:`GCMetadataPrinter <assembly>`:
704 for (iterator I = begin(), E = end(); I != E; ++I) {
705 GCFunctionInfo *FI = *I;
706 unsigned FrameSize = FI->getFrameSize();
707 size_t RootCount = FI->roots_size();
709 for (GCFunctionInfo::roots_iterator RI = FI->roots_begin(),
710 RE = FI->roots_end();
712 int RootNum = RI->Num;
713 int RootStackOffset = RI->StackOffset;
714 Constant *RootMetadata = RI->Metadata;
718 If the ``llvm.gcroot`` intrinsic is eliminated before code generation by a
719 custom lowering pass, LLVM will compute an empty stack map. This may be useful
720 for collector plugins which implement reference counting or a shadow stack.
724 Initializing roots to null: ``InitRoots``
725 -----------------------------------------
733 When set, LLVM will automatically initialize each root to ``null`` upon entry to
734 the function. This prevents the GC's sweep phase from visiting uninitialized
735 pointers, which will almost certainly cause it to crash. This initialization
736 occurs before custom lowering, so the two may be used together.
738 Since LLVM does not yet compute liveness information, there is no means of
739 distinguishing an uninitialized stack root from an initialized one. Therefore,
740 this feature should be used by all GC plugins. It is enabled by default.
744 Custom lowering of intrinsics: ``CustomRoots``, ``CustomReadBarriers``, and ``CustomWriteBarriers``
745 ---------------------------------------------------------------------------------------------------
747 For GCs which use barriers or unusual treatment of stack roots, these flags
748 allow the collector to perform arbitrary transformations of the LLVM IR:
752 class MyGC : public GCStrategy {
756 CustomReadBarriers = true;
757 CustomWriteBarriers = true;
760 virtual bool initializeCustomLowering(Module &M);
761 virtual bool performCustomLowering(Function &F);
764 If any of these flags are set, then LLVM suppresses its default lowering for the
765 corresponding intrinsics and instead calls ``performCustomLowering``.
767 LLVM's default action for each intrinsic is as follows:
769 * ``llvm.gcroot``: Leave it alone. The code generator must see it or the stack
770 map will not be computed.
772 * ``llvm.gcread``: Substitute a ``load`` instruction.
774 * ``llvm.gcwrite``: Substitute a ``store`` instruction.
776 If ``CustomReadBarriers`` or ``CustomWriteBarriers`` are specified, then
777 ``performCustomLowering`` **must** eliminate the corresponding barriers.
779 ``performCustomLowering`` must comply with the same restrictions as
780 `FunctionPass::runOnFunction <WritingAnLLVMPass.html#runOnFunction>`__
781 Likewise, ``initializeCustomLowering`` has the same semantics as
782 `Pass::doInitialization(Module&)
783 <WritingAnLLVMPass.html#doInitialization_mod>`__
785 The following can be used as a template:
789 #include "llvm/Module.h"
790 #include "llvm/IntrinsicInst.h"
792 bool MyGC::initializeCustomLowering(Module &M) {
796 bool MyGC::performCustomLowering(Function &F) {
797 bool MadeChange = false;
799 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
800 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; )
801 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++))
802 if (Function *F = CI->getCalledFunction())
803 switch (F->getIntrinsicID()) {
804 case Intrinsic::gcwrite:
805 // Handle llvm.gcwrite.
806 CI->eraseFromParent();
809 case Intrinsic::gcread:
810 // Handle llvm.gcread.
811 CI->eraseFromParent();
814 case Intrinsic::gcroot:
815 // Handle llvm.gcroot.
816 CI->eraseFromParent();
826 Generating safe points: ``NeededSafePoints``
827 --------------------------------------------
829 LLVM can compute four kinds of safe points:
834 /// PointKind - The type of a collector-safe point.
837 Loop, //< Instr is a loop (backwards branch).
838 Return, //< Instr is a return instruction.
839 PreCall, //< Instr is a call instruction.
840 PostCall //< Instr is the return address of a call.
844 A collector can request any combination of the four by setting the
845 ``NeededSafePoints`` mask:
850 NeededSafePoints = 1 << GC::Loop
856 It can then use the following routines to access safe points.
860 for (iterator I = begin(), E = end(); I != E; ++I) {
861 GCFunctionInfo *MD = *I;
862 size_t PointCount = MD->size();
864 for (GCFunctionInfo::iterator PI = MD->begin(),
865 PE = MD->end(); PI != PE; ++PI) {
866 GC::PointKind PointKind = PI->Kind;
867 unsigned PointNum = PI->Num;
871 Almost every collector requires ``PostCall`` safe points, since these correspond
872 to the moments when the function is suspended during a call to a subroutine.
874 Threaded programs generally require ``Loop`` safe points to guarantee that the
875 application will reach a safe point within a bounded amount of time, even if it
876 is executing a long-running loop which contains no function calls.
878 Threaded collectors may also require ``Return`` and ``PreCall`` safe points to
879 implement "stop the world" techniques using self-modifying code, where it is
880 important that the program not exit the function without reaching a safe point
881 (because only the topmost function has been patched).
885 Emitting assembly code: ``GCMetadataPrinter``
886 ---------------------------------------------
888 LLVM allows a plugin to print arbitrary assembly code before and after the rest
889 of a module's assembly code. At the end of the module, the GC can compile the
890 LLVM stack map into assembly code. (At the beginning, this information is not
893 Since AsmWriter and CodeGen are separate components of LLVM, a separate abstract
894 base class and registry is provided for printing assembly code, the
895 ``GCMetadaPrinter`` and ``GCMetadataPrinterRegistry``. The AsmWriter will look
896 for such a subclass if the ``GCStrategy`` sets ``UsesMetadata``:
904 This separation allows JIT-only clients to be smaller.
906 Note that LLVM does not currently have analogous APIs to support code generation
907 in the JIT, nor using the object writers.
911 // lib/MyGC/MyGCPrinter.cpp - Example LLVM GC printer
913 #include "llvm/CodeGen/GCMetadataPrinter.h"
914 #include "llvm/Support/Compiler.h"
916 using namespace llvm;
919 class LLVM_LIBRARY_VISIBILITY MyGCPrinter : public GCMetadataPrinter {
921 virtual void beginAssembly(std::ostream &OS, AsmPrinter &AP,
922 const TargetAsmInfo &TAI);
924 virtual void finishAssembly(std::ostream &OS, AsmPrinter &AP,
925 const TargetAsmInfo &TAI);
928 GCMetadataPrinterRegistry::Add<MyGCPrinter>
929 X("mygc", "My bespoke garbage collector.");
932 The collector should use ``AsmPrinter`` and ``TargetAsmInfo`` to print portable
933 assembly code to the ``std::ostream``. The collector itself contains the stack
934 map for the entire module, and may access the ``GCFunctionInfo`` using its own
935 ``begin()`` and ``end()`` methods. Here's a realistic example:
939 #include "llvm/CodeGen/AsmPrinter.h"
940 #include "llvm/Function.h"
941 #include "llvm/Target/TargetMachine.h"
942 #include "llvm/DataLayout.h"
943 #include "llvm/Target/TargetAsmInfo.h"
945 void MyGCPrinter::beginAssembly(std::ostream &OS, AsmPrinter &AP,
946 const TargetAsmInfo &TAI) {
950 void MyGCPrinter::finishAssembly(std::ostream &OS, AsmPrinter &AP,
951 const TargetAsmInfo &TAI) {
952 // Set up for emitting addresses.
953 const char *AddressDirective;
955 if (AP.TM.getDataLayout()->getPointerSize() == sizeof(int32_t)) {
956 AddressDirective = TAI.getData32bitsDirective();
959 AddressDirective = TAI.getData64bitsDirective();
963 // Put this in the data section.
964 AP.SwitchToDataSection(TAI.getDataSection());
966 // For each function...
967 for (iterator FI = begin(), FE = end(); FI != FE; ++FI) {
968 GCFunctionInfo &MD = **FI;
970 // Emit this data structure:
973 // int32_t PointCount;
975 // void *SafePointAddress;
976 // int32_t LiveCount;
977 // int32_t LiveOffsets[LiveCount];
978 // } Points[PointCount];
979 // } __gcmap_<FUNCTIONNAME>;
981 // Align to address width.
982 AP.EmitAlignment(AddressAlignLog);
984 // Emit the symbol by which the stack map entry can be found.
986 Symbol += TAI.getGlobalPrefix();
987 Symbol += "__gcmap_";
988 Symbol += MD.getFunction().getName();
989 if (const char *GlobalDirective = TAI.getGlobalDirective())
990 OS << GlobalDirective << Symbol << "\n";
991 OS << TAI.getGlobalPrefix() << Symbol << ":\n";
994 AP.EmitInt32(MD.size());
995 AP.EOL("safe point count");
997 // And each safe point...
998 for (GCFunctionInfo::iterator PI = MD.begin(),
999 PE = MD.end(); PI != PE; ++PI) {
1000 // Align to address width.
1001 AP.EmitAlignment(AddressAlignLog);
1003 // Emit the address of the safe point.
1004 OS << AddressDirective
1005 << TAI.getPrivateGlobalPrefix() << "label" << PI->Num;
1006 AP.EOL("safe point address");
1008 // Emit the stack frame size.
1009 AP.EmitInt32(MD.getFrameSize());
1010 AP.EOL("stack frame size");
1012 // Emit the number of live roots in the function.
1013 AP.EmitInt32(MD.live_size(PI));
1014 AP.EOL("live root count");
1016 // And for each live root...
1017 for (GCFunctionInfo::live_iterator LI = MD.live_begin(PI),
1018 LE = MD.live_end(PI);
1020 // Print its offset within the stack frame.
1021 AP.EmitInt32(LI->StackOffset);
1022 AP.EOL("stack offset");
1033 [Appel89] Runtime Tags Aren't Necessary. Andrew W. Appel. Lisp and Symbolic
1034 Computation 19(7):703-705, July 1989.
1038 [Goldberg91] Tag-free garbage collection for strongly typed programming
1039 languages. Benjamin Goldberg. ACM SIGPLAN PLDI'91.
1043 [Tolmach94] Tag-free garbage collection using explicit type parameters. Andrew
1044 Tolmach. Proceedings of the 1994 ACM conference on LISP and functional
1049 [Henderson2002] `Accurate Garbage Collection in an Uncooperative Environment
1050 <http://citeseer.ist.psu.edu/henderson02accurate.html>`__