GarbageCollection.rst 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028
  1. =====================================
  2. Garbage Collection with LLVM
  3. =====================================
  4. .. contents::
  5. :local:
  6. Abstract
  7. ========
  8. This document covers how to integrate LLVM into a compiler for a language which
  9. supports garbage collection. **Note that LLVM itself does not provide a
  10. garbage collector.** You must provide your own.
  11. Quick Start
  12. ============
  13. First, you should pick a collector strategy. LLVM includes a number of built
  14. in ones, but you can also implement a loadable plugin with a custom definition.
  15. Note that the collector strategy is a description of how LLVM should generate
  16. code such that it interacts with your collector and runtime, not a description
  17. of the collector itself.
  18. Next, mark your generated functions as using your chosen collector strategy.
  19. From c++, you can call:
  20. .. code-block:: c++
  21. F.setGC(<collector description name>);
  22. This will produce IR like the following fragment:
  23. .. code-block:: llvm
  24. define void @foo() gc "<collector description name>" { ... }
  25. When generating LLVM IR for your functions, you will need to:
  26. * Use ``@llvm.gcread`` and/or ``@llvm.gcwrite`` in place of standard load and
  27. store instructions. These intrinsics are used to represent load and store
  28. barriers. If you collector does not require such barriers, you can skip
  29. this step.
  30. * Use the memory allocation routines provided by your garbage collector's
  31. runtime library.
  32. * If your collector requires them, generate type maps according to your
  33. runtime's binary interface. LLVM is not involved in the process. In
  34. particular, the LLVM type system is not suitable for conveying such
  35. information though the compiler.
  36. * Insert any coordination code required for interacting with your collector.
  37. Many collectors require running application code to periodically check a
  38. flag and conditionally call a runtime function. This is often referred to
  39. as a safepoint poll.
  40. You will need to identify roots (i.e. references to heap objects your collector
  41. needs to know about) in your generated IR, so that LLVM can encode them into
  42. your final stack maps. Depending on the collector strategy chosen, this is
  43. accomplished by using either the ``@llvm.gcroot`` intrinsics or an
  44. ``gc.statepoint`` relocation sequence.
  45. Don't forget to create a root for each intermediate value that is generated when
  46. evaluating an expression. In ``h(f(), g())``, the result of ``f()`` could
  47. easily be collected if evaluating ``g()`` triggers a collection.
  48. Finally, you need to link your runtime library with the generated program
  49. executable (for a static compiler) or ensure the appropriate symbols are
  50. available for the runtime linker (for a JIT compiler).
  51. Introduction
  52. ============
  53. What is Garbage Collection?
  54. ---------------------------
  55. Garbage collection is a widely used technique that frees the programmer from
  56. having to know the lifetimes of heap objects, making software easier to produce
  57. and maintain. Many programming languages rely on garbage collection for
  58. automatic memory management. There are two primary forms of garbage collection:
  59. conservative and accurate.
  60. Conservative garbage collection often does not require any special support from
  61. either the language or the compiler: it can handle non-type-safe programming
  62. languages (such as C/C++) and does not require any special information from the
  63. compiler. The `Boehm collector
  64. <http://www.hpl.hp.com/personal/Hans_Boehm/gc/>`__ is an example of a
  65. state-of-the-art conservative collector.
  66. Accurate garbage collection requires the ability to identify all pointers in the
  67. program at run-time (which requires that the source-language be type-safe in
  68. most cases). Identifying pointers at run-time requires compiler support to
  69. locate all places that hold live pointer variables at run-time, including the
  70. :ref:`processor stack and registers <gcroot>`.
  71. Conservative garbage collection is attractive because it does not require any
  72. special compiler support, but it does have problems. In particular, because the
  73. conservative garbage collector cannot *know* that a particular word in the
  74. machine is a pointer, it cannot move live objects in the heap (preventing the
  75. use of compacting and generational GC algorithms) and it can occasionally suffer
  76. from memory leaks due to integer values that happen to point to objects in the
  77. program. In addition, some aggressive compiler transformations can break
  78. conservative garbage collectors (though these seem rare in practice).
  79. Accurate garbage collectors do not suffer from any of these problems, but they
  80. can suffer from degraded scalar optimization of the program. In particular,
  81. because the runtime must be able to identify and update all pointers active in
  82. the program, some optimizations are less effective. In practice, however, the
  83. locality and performance benefits of using aggressive garbage collection
  84. techniques dominates any low-level losses.
  85. This document describes the mechanisms and interfaces provided by LLVM to
  86. support accurate garbage collection.
  87. Goals and non-goals
  88. -------------------
  89. LLVM's intermediate representation provides :ref:`garbage collection intrinsics
  90. <gc_intrinsics>` that offer support for a broad class of collector models. For
  91. instance, the intrinsics permit:
  92. * semi-space collectors
  93. * mark-sweep collectors
  94. * generational collectors
  95. * incremental collectors
  96. * concurrent collectors
  97. * cooperative collectors
  98. * reference counting
  99. We hope that the support built into the LLVM IR is sufficient to support a
  100. broad class of garbage collected languages including Scheme, ML, Java, C#,
  101. Perl, Python, Lua, Ruby, other scripting languages, and more.
  102. Note that LLVM **does not itself provide a garbage collector** --- this should
  103. be part of your language's runtime library. LLVM provides a framework for
  104. describing the garbage collectors requirements to the compiler. In particular,
  105. LLVM provides support for generating stack maps at call sites, polling for a
  106. safepoint, and emitting load and store barriers. You can also extend LLVM -
  107. possibly through a loadable :ref:`code generation plugins <plugin>` - to
  108. generate code and data structures which conforms to the *binary interface*
  109. specified by the *runtime library*. This is similar to the relationship between
  110. LLVM and DWARF debugging info, for example. The difference primarily lies in
  111. the lack of an established standard in the domain of garbage collection --- thus
  112. the need for a flexible extension mechanism.
  113. The aspects of the binary interface with which LLVM's GC support is
  114. concerned are:
  115. * Creation of GC safepoints within code where collection is allowed to execute
  116. safely.
  117. * Computation of the stack map. For each safe point in the code, object
  118. references within the stack frame must be identified so that the collector may
  119. traverse and perhaps update them.
  120. * Write barriers when storing object references to the heap. These are commonly
  121. used to optimize incremental scans in generational collectors.
  122. * Emission of read barriers when loading object references. These are useful
  123. for interoperating with concurrent collectors.
  124. There are additional areas that LLVM does not directly address:
  125. * Registration of global roots with the runtime.
  126. * Registration of stack map entries with the runtime.
  127. * The functions used by the program to allocate memory, trigger a collection,
  128. etc.
  129. * Computation or compilation of type maps, or registration of them with the
  130. runtime. These are used to crawl the heap for object references.
  131. In general, LLVM's support for GC does not include features which can be
  132. adequately addressed with other features of the IR and does not specify a
  133. particular binary interface. On the plus side, this means that you should be
  134. able to integrate LLVM with an existing runtime. On the other hand, it can
  135. have the effect of leaving a lot of work for the developer of a novel
  136. language. We try to mitigate this by providing built in collector strategy
  137. descriptions that can work with many common collector designs and easy
  138. extension points. If you don't already have a specific binary interface
  139. you need to support, we recommend trying to use one of these built in collector
  140. strategies.
  141. .. _gc_intrinsics:
  142. LLVM IR Features
  143. ================
  144. This section describes the garbage collection facilities provided by the
  145. :doc:`LLVM intermediate representation <LangRef>`. The exact behavior of these
  146. IR features is specified by the selected :ref:`GC strategy description
  147. <plugin>`.
  148. Specifying GC code generation: ``gc "..."``
  149. -------------------------------------------
  150. .. code-block:: text
  151. define <returntype> @name(...) gc "name" { ... }
  152. The ``gc`` function attribute is used to specify the desired GC strategy to the
  153. compiler. Its programmatic equivalent is the ``setGC`` method of ``Function``.
  154. Setting ``gc "name"`` on a function triggers a search for a matching subclass
  155. of GCStrategy. Some collector strategies are built in. You can add others
  156. using either the loadable plugin mechanism, or by patching your copy of LLVM.
  157. It is the selected GC strategy which defines the exact nature of the code
  158. generated to support GC. If none is found, the compiler will raise an error.
  159. Specifying the GC style on a per-function basis allows LLVM to link together
  160. programs that use different garbage collection algorithms (or none at all).
  161. .. _gcroot:
  162. Identifying GC roots on the stack
  163. ----------------------------------
  164. LLVM currently supports two different mechanisms for describing references in
  165. compiled code at safepoints. ``llvm.gcroot`` is the older mechanism;
  166. ``gc.statepoint`` has been added more recently. At the moment, you can choose
  167. either implementation (on a per :ref:`GC strategy <plugin>` basis). Longer
  168. term, we will probably either migrate away from ``llvm.gcroot`` entirely, or
  169. substantially merge their implementations. Note that most new development
  170. work is focused on ``gc.statepoint``.
  171. Using ``gc.statepoint``
  172. ^^^^^^^^^^^^^^^^^^^^^^^^
  173. :doc:`This page <Statepoints>` contains detailed documentation for
  174. ``gc.statepoint``.
  175. Using ``llvm.gcwrite``
  176. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  177. .. code-block:: llvm
  178. void @llvm.gcroot(i8** %ptrloc, i8* %metadata)
  179. The ``llvm.gcroot`` intrinsic is used to inform LLVM that a stack variable
  180. references an object on the heap and is to be tracked for garbage collection.
  181. The exact impact on generated code is specified by the Function's selected
  182. :ref:`GC strategy <plugin>`. All calls to ``llvm.gcroot`` **must** reside
  183. inside the first basic block.
  184. The first argument **must** be a value referring to an alloca instruction or a
  185. bitcast of an alloca. The second contains a pointer to metadata that should be
  186. associated with the pointer, and **must** be a constant or global value
  187. address. If your target collector uses tags, use a null pointer for metadata.
  188. A compiler which performs manual SSA construction **must** ensure that SSA
  189. values representing GC references are stored in to the alloca passed to the
  190. respective ``gcroot`` before every call site and reloaded after every call.
  191. A compiler which uses mem2reg to raise imperative code using ``alloca`` into
  192. SSA form need only add a call to ``@llvm.gcroot`` for those variables which
  193. are pointers into the GC heap.
  194. It is also important to mark intermediate values with ``llvm.gcroot``. For
  195. example, consider ``h(f(), g())``. Beware leaking the result of ``f()`` in the
  196. case that ``g()`` triggers a collection. Note, that stack variables must be
  197. initialized and marked with ``llvm.gcroot`` in function's prologue.
  198. The ``%metadata`` argument can be used to avoid requiring heap objects to have
  199. 'isa' pointers or tag bits. [Appel89_, Goldberg91_, Tolmach94_] If specified,
  200. its value will be tracked along with the location of the pointer in the stack
  201. frame.
  202. Consider the following fragment of Java code:
  203. .. code-block:: java
  204. {
  205. Object X; // A null-initialized reference to an object
  206. ...
  207. }
  208. This block (which may be located in the middle of a function or in a loop nest),
  209. could be compiled to this LLVM code:
  210. .. code-block:: llvm
  211. Entry:
  212. ;; In the entry block for the function, allocate the
  213. ;; stack space for X, which is an LLVM pointer.
  214. %X = alloca %Object*
  215. ;; Tell LLVM that the stack space is a stack root.
  216. ;; Java has type-tags on objects, so we pass null as metadata.
  217. %tmp = bitcast %Object** %X to i8**
  218. call void @llvm.gcroot(i8** %tmp, i8* null)
  219. ...
  220. ;; "CodeBlock" is the block corresponding to the start
  221. ;; of the scope above.
  222. CodeBlock:
  223. ;; Java null-initializes pointers.
  224. store %Object* null, %Object** %X
  225. ...
  226. ;; As the pointer goes out of scope, store a null value into
  227. ;; it, to indicate that the value is no longer live.
  228. store %Object* null, %Object** %X
  229. ...
  230. Reading and writing references in the heap
  231. ------------------------------------------
  232. Some collectors need to be informed when the mutator (the program that needs
  233. garbage collection) either reads a pointer from or writes a pointer to a field
  234. of a heap object. The code fragments inserted at these points are called *read
  235. barriers* and *write barriers*, respectively. The amount of code that needs to
  236. be executed is usually quite small and not on the critical path of any
  237. computation, so the overall performance impact of the barrier is tolerable.
  238. Barriers often require access to the *object pointer* rather than the *derived
  239. pointer* (which is a pointer to the field within the object). Accordingly,
  240. these intrinsics take both pointers as separate arguments for completeness. In
  241. this snippet, ``%object`` is the object pointer, and ``%derived`` is the derived
  242. pointer:
  243. .. code-block:: llvm
  244. ;; An array type.
  245. %class.Array = type { %class.Object, i32, [0 x %class.Object*] }
  246. ...
  247. ;; Load the object pointer from a gcroot.
  248. %object = load %class.Array** %object_addr
  249. ;; Compute the derived pointer.
  250. %derived = getelementptr %object, i32 0, i32 2, i32 %n
  251. LLVM does not enforce this relationship between the object and derived pointer
  252. (although a particular :ref:`collector strategy <plugin>` might). However, it
  253. would be an unusual collector that violated it.
  254. The use of these intrinsics is naturally optional if the target GC does not
  255. require the corresponding barrier. The GC strategy used with such a collector
  256. should replace the intrinsic calls with the corresponding ``load`` or
  257. ``store`` instruction if they are used.
  258. One known deficiency with the current design is that the barrier intrinsics do
  259. not include the size or alignment of the underlying operation performed. It is
  260. currently assumed that the operation is of pointer size and the alignment is
  261. assumed to be the target machine's default alignment.
  262. Write barrier: ``llvm.gcwrite``
  263. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  264. .. code-block:: llvm
  265. void @llvm.gcwrite(i8* %value, i8* %object, i8** %derived)
  266. For write barriers, LLVM provides the ``llvm.gcwrite`` intrinsic function. It
  267. has exactly the same semantics as a non-volatile ``store`` to the derived
  268. pointer (the third argument). The exact code generated is specified by the
  269. Function's selected :ref:`GC strategy <plugin>`.
  270. Many important algorithms require write barriers, including generational and
  271. concurrent collectors. Additionally, write barriers could be used to implement
  272. reference counting.
  273. Read barrier: ``llvm.gcread``
  274. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  275. .. code-block:: llvm
  276. i8* @llvm.gcread(i8* %object, i8** %derived)
  277. For read barriers, LLVM provides the ``llvm.gcread`` intrinsic function. It has
  278. exactly the same semantics as a non-volatile ``load`` from the derived pointer
  279. (the second argument). The exact code generated is specified by the Function's
  280. selected :ref:`GC strategy <plugin>`.
  281. Read barriers are needed by fewer algorithms than write barriers, and may have a
  282. greater performance impact since pointer reads are more frequent than writes.
  283. .. _plugin:
  284. .. _builtin-gc-strategies:
  285. Built In GC Strategies
  286. ======================
  287. LLVM includes built in support for several varieties of garbage collectors.
  288. The Shadow Stack GC
  289. ----------------------
  290. To use this collector strategy, mark your functions with:
  291. .. code-block:: c++
  292. F.setGC("shadow-stack");
  293. Unlike many GC algorithms which rely on a cooperative code generator to compile
  294. stack maps, this algorithm carefully maintains a linked list of stack roots
  295. [:ref:`Henderson2002 <henderson02>`]. This so-called "shadow stack" mirrors the
  296. machine stack. Maintaining this data structure is slower than using a stack map
  297. compiled into the executable as constant data, but has a significant portability
  298. advantage because it requires no special support from the target code generator,
  299. and does not require tricky platform-specific code to crawl the machine stack.
  300. The tradeoff for this simplicity and portability is:
  301. * High overhead per function call.
  302. * Not thread-safe.
  303. Still, it's an easy way to get started. After your compiler and runtime are up
  304. and running, writing a :ref:`plugin <plugin>` will allow you to take advantage
  305. of :ref:`more advanced GC features <collector-algos>` of LLVM in order to
  306. improve performance.
  307. The shadow stack doesn't imply a memory allocation algorithm. A semispace
  308. collector or building atop ``malloc`` are great places to start, and can be
  309. implemented with very little code.
  310. When it comes time to collect, however, your runtime needs to traverse the stack
  311. roots, and for this it needs to integrate with the shadow stack. Luckily, doing
  312. so is very simple. (This code is heavily commented to help you understand the
  313. data structure, but there are only 20 lines of meaningful code.)
  314. .. code-block:: c++
  315. /// The map for a single function's stack frame. One of these is
  316. /// compiled as constant data into the executable for each function.
  317. ///
  318. /// Storage of metadata values is elided if the %metadata parameter to
  319. /// @llvm.gcroot is null.
  320. struct FrameMap {
  321. int32_t NumRoots; //< Number of roots in stack frame.
  322. int32_t NumMeta; //< Number of metadata entries. May be < NumRoots.
  323. const void *Meta[0]; //< Metadata for each root.
  324. };
  325. /// A link in the dynamic shadow stack. One of these is embedded in
  326. /// the stack frame of each function on the call stack.
  327. struct StackEntry {
  328. StackEntry *Next; //< Link to next stack entry (the caller's).
  329. const FrameMap *Map; //< Pointer to constant FrameMap.
  330. void *Roots[0]; //< Stack roots (in-place array).
  331. };
  332. /// The head of the singly-linked list of StackEntries. Functions push
  333. /// and pop onto this in their prologue and epilogue.
  334. ///
  335. /// Since there is only a global list, this technique is not threadsafe.
  336. StackEntry *llvm_gc_root_chain;
  337. /// Calls Visitor(root, meta) for each GC root on the stack.
  338. /// root and meta are exactly the values passed to
  339. /// @llvm.gcroot.
  340. ///
  341. /// Visitor could be a function to recursively mark live objects. Or it
  342. /// might copy them to another heap or generation.
  343. ///
  344. /// @param Visitor A function to invoke for every GC root on the stack.
  345. void visitGCRoots(void (*Visitor)(void **Root, const void *Meta)) {
  346. for (StackEntry *R = llvm_gc_root_chain; R; R = R->Next) {
  347. unsigned i = 0;
  348. // For roots [0, NumMeta), the metadata pointer is in the FrameMap.
  349. for (unsigned e = R->Map->NumMeta; i != e; ++i)
  350. Visitor(&R->Roots[i], R->Map->Meta[i]);
  351. // For roots [NumMeta, NumRoots), the metadata pointer is null.
  352. for (unsigned e = R->Map->NumRoots; i != e; ++i)
  353. Visitor(&R->Roots[i], NULL);
  354. }
  355. }
  356. The 'Erlang' and 'Ocaml' GCs
  357. -----------------------------
  358. LLVM ships with two example collectors which leverage the ``gcroot``
  359. mechanisms. To our knowledge, these are not actually used by any language
  360. runtime, but they do provide a reasonable starting point for someone interested
  361. in writing an ``gcroot`` compatible GC plugin. In particular, these are the
  362. only in tree examples of how to produce a custom binary stack map format using
  363. a ``gcroot`` strategy.
  364. As there names imply, the binary format produced is intended to model that
  365. used by the Erlang and OCaml compilers respectively.
  366. .. _statepoint_example_gc:
  367. The Statepoint Example GC
  368. -------------------------
  369. .. code-block:: c++
  370. F.setGC("statepoint-example");
  371. This GC provides an example of how one might use the infrastructure provided
  372. by ``gc.statepoint``. This example GC is compatible with the
  373. :ref:`PlaceSafepoints` and :ref:`RewriteStatepointsForGC` utility passes
  374. which simplify ``gc.statepoint`` sequence insertion. If you need to build a
  375. custom GC strategy around the ``gc.statepoints`` mechanisms, it is recommended
  376. that you use this one as a starting point.
  377. This GC strategy does not support read or write barriers. As a result, these
  378. intrinsics are lowered to normal loads and stores.
  379. The stack map format generated by this GC strategy can be found in the
  380. :ref:`stackmap-section` using a format documented :ref:`here
  381. <statepoint-stackmap-format>`. This format is intended to be the standard
  382. format supported by LLVM going forward.
  383. The CoreCLR GC
  384. -------------------------
  385. .. code-block:: c++
  386. F.setGC("coreclr");
  387. This GC leverages the ``gc.statepoint`` mechanism to support the
  388. `CoreCLR <https://github.com/dotnet/coreclr>`__ runtime.
  389. Support for this GC strategy is a work in progress. This strategy will
  390. differ from
  391. :ref:`statepoint-example GC<statepoint_example_gc>` strategy in
  392. certain aspects like:
  393. * Base-pointers of interior pointers are not explicitly
  394. tracked and reported.
  395. * A different format is used for encoding stack maps.
  396. * Safe-point polls are only needed before loop-back edges
  397. and before tail-calls (not needed at function-entry).
  398. Custom GC Strategies
  399. ====================
  400. If none of the built in GC strategy descriptions met your needs above, you will
  401. need to define a custom GCStrategy and possibly, a custom LLVM pass to perform
  402. lowering. Your best example of where to start defining a custom GCStrategy
  403. would be to look at one of the built in strategies.
  404. You may be able to structure this additional code as a loadable plugin library.
  405. Loadable plugins are sufficient if all you need is to enable a different
  406. combination of built in functionality, but if you need to provide a custom
  407. lowering pass, you will need to build a patched version of LLVM. If you think
  408. you need a patched build, please ask for advice on llvm-dev. There may be an
  409. easy way we can extend the support to make it work for your use case without
  410. requiring a custom build.
  411. Collector Requirements
  412. ----------------------
  413. You should be able to leverage any existing collector library that includes the following elements:
  414. #. A memory allocator which exposes an allocation function your compiled
  415. code can call.
  416. #. A binary format for the stack map. A stack map describes the location
  417. of references at a safepoint and is used by precise collectors to identify
  418. references within a stack frame on the machine stack. Note that collectors
  419. which conservatively scan the stack don't require such a structure.
  420. #. A stack crawler to discover functions on the call stack, and enumerate the
  421. references listed in the stack map for each call site.
  422. #. A mechanism for identifying references in global locations (e.g. global
  423. variables).
  424. #. If you collector requires them, an LLVM IR implementation of your collectors
  425. load and store barriers. Note that since many collectors don't require
  426. barriers at all, LLVM defaults to lowering such barriers to normal loads
  427. and stores unless you arrange otherwise.
  428. Implementing a collector plugin
  429. -------------------------------
  430. User code specifies which GC code generation to use with the ``gc`` function
  431. attribute or, equivalently, with the ``setGC`` method of ``Function``.
  432. To implement a GC plugin, it is necessary to subclass ``llvm::GCStrategy``,
  433. which can be accomplished in a few lines of boilerplate code. LLVM's
  434. infrastructure provides access to several important algorithms. For an
  435. uncontroversial collector, all that remains may be to compile LLVM's computed
  436. stack map to assembly code (using the binary representation expected by the
  437. runtime library). This can be accomplished in about 100 lines of code.
  438. This is not the appropriate place to implement a garbage collected heap or a
  439. garbage collector itself. That code should exist in the language's runtime
  440. library. The compiler plugin is responsible for generating code which conforms
  441. to the binary interface defined by library, most essentially the :ref:`stack map
  442. <stack-map>`.
  443. To subclass ``llvm::GCStrategy`` and register it with the compiler:
  444. .. code-block:: c++
  445. // lib/MyGC/MyGC.cpp - Example LLVM GC plugin
  446. #include "llvm/CodeGen/GCStrategy.h"
  447. #include "llvm/CodeGen/GCMetadata.h"
  448. #include "llvm/Support/Compiler.h"
  449. using namespace llvm;
  450. namespace {
  451. class LLVM_LIBRARY_VISIBILITY MyGC : public GCStrategy {
  452. public:
  453. MyGC() {}
  454. };
  455. GCRegistry::Add<MyGC>
  456. X("mygc", "My bespoke garbage collector.");
  457. }
  458. This boilerplate collector does nothing. More specifically:
  459. * ``llvm.gcread`` calls are replaced with the corresponding ``load``
  460. instruction.
  461. * ``llvm.gcwrite`` calls are replaced with the corresponding ``store``
  462. instruction.
  463. * No safe points are added to the code.
  464. * The stack map is not compiled into the executable.
  465. Using the LLVM makefiles, this code
  466. can be compiled as a plugin using a simple makefile:
  467. .. code-block:: make
  468. # lib/MyGC/Makefile
  469. LEVEL := ../..
  470. LIBRARYNAME = MyGC
  471. LOADABLE_MODULE = 1
  472. include $(LEVEL)/Makefile.common
  473. Once the plugin is compiled, code using it may be compiled using ``llc
  474. -load=MyGC.so`` (though MyGC.so may have some other platform-specific
  475. extension):
  476. ::
  477. $ cat sample.ll
  478. define void @f() gc "mygc" {
  479. entry:
  480. ret void
  481. }
  482. $ llvm-as < sample.ll | llc -load=MyGC.so
  483. It is also possible to statically link the collector plugin into tools, such as
  484. a language-specific compiler front-end.
  485. .. _collector-algos:
  486. Overview of available features
  487. ------------------------------
  488. ``GCStrategy`` provides a range of features through which a plugin may do useful
  489. work. Some of these are callbacks, some are algorithms that can be enabled,
  490. disabled, or customized. This matrix summarizes the supported (and planned)
  491. features and correlates them with the collection techniques which typically
  492. require them.
  493. .. |v| unicode:: 0x2714
  494. :trim:
  495. .. |x| unicode:: 0x2718
  496. :trim:
  497. +------------+------+--------+----------+-------+---------+-------------+----------+------------+
  498. | Algorithm | Done | Shadow | refcount | mark- | copying | incremental | threaded | concurrent |
  499. | | | stack | | sweep | | | | |
  500. +============+======+========+==========+=======+=========+=============+==========+============+
  501. | stack map | |v| | | | |x| | |x| | |x| | |x| | |x| |
  502. +------------+------+--------+----------+-------+---------+-------------+----------+------------+
  503. | initialize | |v| | |x| | |x| | |x| | |x| | |x| | |x| | |x| |
  504. | roots | | | | | | | | |
  505. +------------+------+--------+----------+-------+---------+-------------+----------+------------+
  506. | derived | NO | | | | | | **N**\* | **N**\* |
  507. | pointers | | | | | | | | |
  508. +------------+------+--------+----------+-------+---------+-------------+----------+------------+
  509. | **custom | |v| | | | | | | | |
  510. | lowering** | | | | | | | | |
  511. +------------+------+--------+----------+-------+---------+-------------+----------+------------+
  512. | *gcroot* | |v| | |x| | |x| | | | | | |
  513. +------------+------+--------+----------+-------+---------+-------------+----------+------------+
  514. | *gcwrite* | |v| | | |x| | | | |x| | | |x| |
  515. +------------+------+--------+----------+-------+---------+-------------+----------+------------+
  516. | *gcread* | |v| | | | | | | | |x| |
  517. +------------+------+--------+----------+-------+---------+-------------+----------+------------+
  518. | **safe | | | | | | | | |
  519. | points** | | | | | | | | |
  520. +------------+------+--------+----------+-------+---------+-------------+----------+------------+
  521. | *in | |v| | | | |x| | |x| | |x| | |x| | |x| |
  522. | calls* | | | | | | | | |
  523. +------------+------+--------+----------+-------+---------+-------------+----------+------------+
  524. | *before | |v| | | | | | | |x| | |x| |
  525. | calls* | | | | | | | | |
  526. +------------+------+--------+----------+-------+---------+-------------+----------+------------+
  527. | *for | NO | | | | | | **N** | **N** |
  528. | loops* | | | | | | | | |
  529. +------------+------+--------+----------+-------+---------+-------------+----------+------------+
  530. | *before | |v| | | | | | | |x| | |x| |
  531. | escape* | | | | | | | | |
  532. +------------+------+--------+----------+-------+---------+-------------+----------+------------+
  533. | emit code | NO | | | | | | **N** | **N** |
  534. | at safe | | | | | | | | |
  535. | points | | | | | | | | |
  536. +------------+------+--------+----------+-------+---------+-------------+----------+------------+
  537. | **output** | | | | | | | | |
  538. +------------+------+--------+----------+-------+---------+-------------+----------+------------+
  539. | *assembly* | |v| | | | |x| | |x| | |x| | |x| | |x| |
  540. +------------+------+--------+----------+-------+---------+-------------+----------+------------+
  541. | *JIT* | NO | | | **?** | **?** | **?** | **?** | **?** |
  542. +------------+------+--------+----------+-------+---------+-------------+----------+------------+
  543. | *obj* | NO | | | **?** | **?** | **?** | **?** | **?** |
  544. +------------+------+--------+----------+-------+---------+-------------+----------+------------+
  545. | live | NO | | | **?** | **?** | **?** | **?** | **?** |
  546. | analysis | | | | | | | | |
  547. +------------+------+--------+----------+-------+---------+-------------+----------+------------+
  548. | register | NO | | | **?** | **?** | **?** | **?** | **?** |
  549. | map | | | | | | | | |
  550. +------------+------+--------+----------+-------+---------+-------------+----------+------------+
  551. | \* Derived pointers only pose a hasard to copying collections. |
  552. +------------+------+--------+----------+-------+---------+-------------+----------+------------+
  553. | **?** denotes a feature which could be utilized if available. |
  554. +------------+------+--------+----------+-------+---------+-------------+----------+------------+
  555. To be clear, the collection techniques above are defined as:
  556. Shadow Stack
  557. The mutator carefully maintains a linked list of stack roots.
  558. Reference Counting
  559. The mutator maintains a reference count for each object and frees an object
  560. when its count falls to zero.
  561. Mark-Sweep
  562. When the heap is exhausted, the collector marks reachable objects starting
  563. from the roots, then deallocates unreachable objects in a sweep phase.
  564. Copying
  565. As reachability analysis proceeds, the collector copies objects from one heap
  566. area to another, compacting them in the process. Copying collectors enable
  567. highly efficient "bump pointer" allocation and can improve locality of
  568. reference.
  569. Incremental
  570. (Including generational collectors.) Incremental collectors generally have all
  571. the properties of a copying collector (regardless of whether the mature heap
  572. is compacting), but bring the added complexity of requiring write barriers.
  573. Threaded
  574. Denotes a multithreaded mutator; the collector must still stop the mutator
  575. ("stop the world") before beginning reachability analysis. Stopping a
  576. multithreaded mutator is a complicated problem. It generally requires highly
  577. platform-specific code in the runtime, and the production of carefully
  578. designed machine code at safe points.
  579. Concurrent
  580. In this technique, the mutator and the collector run concurrently, with the
  581. goal of eliminating pause times. In a *cooperative* collector, the mutator
  582. further aids with collection should a pause occur, allowing collection to take
  583. advantage of multiprocessor hosts. The "stop the world" problem of threaded
  584. collectors is generally still present to a limited extent. Sophisticated
  585. marking algorithms are necessary. Read barriers may be necessary.
  586. As the matrix indicates, LLVM's garbage collection infrastructure is already
  587. suitable for a wide variety of collectors, but does not currently extend to
  588. multithreaded programs. This will be added in the future as there is
  589. interest.
  590. .. _stack-map:
  591. Computing stack maps
  592. --------------------
  593. LLVM automatically computes a stack map. One of the most important features
  594. of a ``GCStrategy`` is to compile this information into the executable in
  595. the binary representation expected by the runtime library.
  596. The stack map consists of the location and identity of each GC root in the
  597. each function in the module. For each root:
  598. * ``RootNum``: The index of the root.
  599. * ``StackOffset``: The offset of the object relative to the frame pointer.
  600. * ``RootMetadata``: The value passed as the ``%metadata`` parameter to the
  601. ``@llvm.gcroot`` intrinsic.
  602. Also, for the function as a whole:
  603. * ``getFrameSize()``: The overall size of the function's initial stack frame,
  604. not accounting for any dynamic allocation.
  605. * ``roots_size()``: The count of roots in the function.
  606. To access the stack map, use ``GCFunctionMetadata::roots_begin()`` and
  607. -``end()`` from the :ref:`GCMetadataPrinter <assembly>`:
  608. .. code-block:: c++
  609. for (iterator I = begin(), E = end(); I != E; ++I) {
  610. GCFunctionInfo *FI = *I;
  611. unsigned FrameSize = FI->getFrameSize();
  612. size_t RootCount = FI->roots_size();
  613. for (GCFunctionInfo::roots_iterator RI = FI->roots_begin(),
  614. RE = FI->roots_end();
  615. RI != RE; ++RI) {
  616. int RootNum = RI->Num;
  617. int RootStackOffset = RI->StackOffset;
  618. Constant *RootMetadata = RI->Metadata;
  619. }
  620. }
  621. If the ``llvm.gcroot`` intrinsic is eliminated before code generation by a
  622. custom lowering pass, LLVM will compute an empty stack map. This may be useful
  623. for collector plugins which implement reference counting or a shadow stack.
  624. .. _init-roots:
  625. Initializing roots to null
  626. ---------------------------
  627. It is recommended that frontends initialize roots explicitly to avoid
  628. potentially confusing the optimizer. This prevents the GC from visiting
  629. uninitialized pointers, which will almost certainly cause it to crash.
  630. As a fallback, LLVM will automatically initialize each root to ``null``
  631. upon entry to the function. Support for this mode in code generation is
  632. largely a legacy detail to keep old collector implementations working.
  633. Custom lowering of intrinsics
  634. ------------------------------
  635. For GCs which use barriers or unusual treatment of stack roots, the
  636. implementor is responsibly for providing a custom pass to lower the
  637. intrinsics with the desired semantics. If you have opted in to custom
  638. lowering of a particular intrinsic your pass **must** eliminate all
  639. instances of the corresponding intrinsic in functions which opt in to
  640. your GC. The best example of such a pass is the ShadowStackGC and it's
  641. ShadowStackGCLowering pass.
  642. There is currently no way to register such a custom lowering pass
  643. without building a custom copy of LLVM.
  644. .. _safe-points:
  645. Generating safe points
  646. -----------------------
  647. LLVM provides support for associating stackmaps with the return address of
  648. a call. Any loop or return safepoints required by a given collector design
  649. can be modeled via calls to runtime routines, or potentially patchable call
  650. sequences. Using gcroot, all call instructions are inferred to be possible
  651. safepoints and will thus have an associated stackmap.
  652. .. _assembly:
  653. Emitting assembly code: ``GCMetadataPrinter``
  654. ---------------------------------------------
  655. LLVM allows a plugin to print arbitrary assembly code before and after the rest
  656. of a module's assembly code. At the end of the module, the GC can compile the
  657. LLVM stack map into assembly code. (At the beginning, this information is not
  658. yet computed.)
  659. Since AsmWriter and CodeGen are separate components of LLVM, a separate abstract
  660. base class and registry is provided for printing assembly code, the
  661. ``GCMetadaPrinter`` and ``GCMetadataPrinterRegistry``. The AsmWriter will look
  662. for such a subclass if the ``GCStrategy`` sets ``UsesMetadata``:
  663. .. code-block:: c++
  664. MyGC::MyGC() {
  665. UsesMetadata = true;
  666. }
  667. This separation allows JIT-only clients to be smaller.
  668. Note that LLVM does not currently have analogous APIs to support code generation
  669. in the JIT, nor using the object writers.
  670. .. code-block:: c++
  671. // lib/MyGC/MyGCPrinter.cpp - Example LLVM GC printer
  672. #include "llvm/CodeGen/GCMetadataPrinter.h"
  673. #include "llvm/Support/Compiler.h"
  674. using namespace llvm;
  675. namespace {
  676. class LLVM_LIBRARY_VISIBILITY MyGCPrinter : public GCMetadataPrinter {
  677. public:
  678. virtual void beginAssembly(AsmPrinter &AP);
  679. virtual void finishAssembly(AsmPrinter &AP);
  680. };
  681. GCMetadataPrinterRegistry::Add<MyGCPrinter>
  682. X("mygc", "My bespoke garbage collector.");
  683. }
  684. The collector should use ``AsmPrinter`` to print portable assembly code. The
  685. collector itself contains the stack map for the entire module, and may access
  686. the ``GCFunctionInfo`` using its own ``begin()`` and ``end()`` methods. Here's
  687. a realistic example:
  688. .. code-block:: c++
  689. #include "llvm/CodeGen/AsmPrinter.h"
  690. #include "llvm/IR/Function.h"
  691. #include "llvm/IR/DataLayout.h"
  692. #include "llvm/Target/TargetAsmInfo.h"
  693. #include "llvm/Target/TargetMachine.h"
  694. void MyGCPrinter::beginAssembly(AsmPrinter &AP) {
  695. // Nothing to do.
  696. }
  697. void MyGCPrinter::finishAssembly(AsmPrinter &AP) {
  698. MCStreamer &OS = AP.OutStreamer;
  699. unsigned IntPtrSize = AP.getPointerSize();
  700. // Put this in the data section.
  701. OS.SwitchSection(AP.getObjFileLowering().getDataSection());
  702. // For each function...
  703. for (iterator FI = begin(), FE = end(); FI != FE; ++FI) {
  704. GCFunctionInfo &MD = **FI;
  705. // A compact GC layout. Emit this data structure:
  706. //
  707. // struct {
  708. // int32_t PointCount;
  709. // void *SafePointAddress[PointCount];
  710. // int32_t StackFrameSize; // in words
  711. // int32_t StackArity;
  712. // int32_t LiveCount;
  713. // int32_t LiveOffsets[LiveCount];
  714. // } __gcmap_<FUNCTIONNAME>;
  715. // Align to address width.
  716. AP.EmitAlignment(IntPtrSize == 4 ? 2 : 3);
  717. // Emit PointCount.
  718. OS.AddComment("safe point count");
  719. AP.emitInt32(MD.size());
  720. // And each safe point...
  721. for (GCFunctionInfo::iterator PI = MD.begin(),
  722. PE = MD.end(); PI != PE; ++PI) {
  723. // Emit the address of the safe point.
  724. OS.AddComment("safe point address");
  725. MCSymbol *Label = PI->Label;
  726. AP.EmitLabelPlusOffset(Label/*Hi*/, 0/*Offset*/, 4/*Size*/);
  727. }
  728. // Stack information never change in safe points! Only print info from the
  729. // first call-site.
  730. GCFunctionInfo::iterator PI = MD.begin();
  731. // Emit the stack frame size.
  732. OS.AddComment("stack frame size (in words)");
  733. AP.emitInt32(MD.getFrameSize() / IntPtrSize);
  734. // Emit stack arity, i.e. the number of stacked arguments.
  735. unsigned RegisteredArgs = IntPtrSize == 4 ? 5 : 6;
  736. unsigned StackArity = MD.getFunction().arg_size() > RegisteredArgs ?
  737. MD.getFunction().arg_size() - RegisteredArgs : 0;
  738. OS.AddComment("stack arity");
  739. AP.emitInt32(StackArity);
  740. // Emit the number of live roots in the function.
  741. OS.AddComment("live root count");
  742. AP.emitInt32(MD.live_size(PI));
  743. // And for each live root...
  744. for (GCFunctionInfo::live_iterator LI = MD.live_begin(PI),
  745. LE = MD.live_end(PI);
  746. LI != LE; ++LI) {
  747. // Emit live root's offset within the stack frame.
  748. OS.AddComment("stack index (offset / wordsize)");
  749. AP.emitInt32(LI->StackOffset);
  750. }
  751. }
  752. }
  753. References
  754. ==========
  755. .. _appel89:
  756. [Appel89] Runtime Tags Aren't Necessary. Andrew W. Appel. Lisp and Symbolic
  757. Computation 19(7):703-705, July 1989.
  758. .. _goldberg91:
  759. [Goldberg91] Tag-free garbage collection for strongly typed programming
  760. languages. Benjamin Goldberg. ACM SIGPLAN PLDI'91.
  761. .. _tolmach94:
  762. [Tolmach94] Tag-free garbage collection using explicit type parameters. Andrew
  763. Tolmach. Proceedings of the 1994 ACM conference on LISP and functional
  764. programming.
  765. .. _henderson02:
  766. [Henderson2002] `Accurate Garbage Collection in an Uncooperative Environment
  767. <http://citeseer.ist.psu.edu/henderson02accurate.html>`__