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