• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1=====================================
2Garbage Collection Safepoints in LLVM
3=====================================
4
5.. contents::
6   :local:
7   :depth: 2
8
9Status
10=======
11
12This document describes a set of experimental extensions to LLVM. Use
13with caution.  Because the intrinsics have experimental status,
14compatibility across LLVM releases is not guaranteed.
15
16LLVM currently supports an alternate mechanism for conservative
17garbage collection support using the ``gcroot`` intrinsic.  The mechanism
18described here shares little in common with the alternate ``gcroot``
19implementation and it is hoped that this mechanism will eventually
20replace the gc_root mechanism.
21
22Overview
23========
24
25To collect dead objects, garbage collectors must be able to identify
26any references to objects contained within executing code, and,
27depending on the collector, potentially update them.  The collector
28does not need this information at all points in code - that would make
29the problem much harder - but only at well-defined points in the
30execution known as 'safepoints' For most collectors, it is sufficient
31to track at least one copy of each unique pointer value.  However, for
32a collector which wishes to relocate objects directly reachable from
33running code, a higher standard is required.
34
35One additional challenge is that the compiler may compute intermediate
36results ("derived pointers") which point outside of the allocation or
37even into the middle of another allocation.  The eventual use of this
38intermediate value must yield an address within the bounds of the
39allocation, but such "exterior derived pointers" may be visible to the
40collector.  Given this, a garbage collector can not safely rely on the
41runtime value of an address to indicate the object it is associated
42with.  If the garbage collector wishes to move any object, the
43compiler must provide a mapping, for each pointer, to an indication of
44its allocation.
45
46To simplify the interaction between a collector and the compiled code,
47most garbage collectors are organized in terms of three abstractions:
48load barriers, store barriers, and safepoints.
49
50#. A load barrier is a bit of code executed immediately after the
51   machine load instruction, but before any use of the value loaded.
52   Depending on the collector, such a barrier may be needed for all
53   loads, merely loads of a particular type (in the original source
54   language), or none at all.
55
56#. Analogously, a store barrier is a code fragment that runs
57   immediately before the machine store instruction, but after the
58   computation of the value stored.  The most common use of a store
59   barrier is to update a 'card table' in a generational garbage
60   collector.
61
62#. A safepoint is a location at which pointers visible to the compiled
63   code (i.e. currently in registers or on the stack) are allowed to
64   change.  After the safepoint completes, the actual pointer value
65   may differ, but the 'object' (as seen by the source language)
66   pointed to will not.
67
68  Note that the term 'safepoint' is somewhat overloaded.  It refers to
69  both the location at which the machine state is parsable and the
70  coordination protocol involved in bring application threads to a
71  point at which the collector can safely use that information.  The
72  term "statepoint" as used in this document refers exclusively to the
73  former.
74
75This document focuses on the last item - compiler support for
76safepoints in generated code.  We will assume that an outside
77mechanism has decided where to place safepoints.  From our
78perspective, all safepoints will be function calls.  To support
79relocation of objects directly reachable from values in compiled code,
80the collector must be able to:
81
82#. identify every copy of a pointer (including copies introduced by
83   the compiler itself) at the safepoint,
84#. identify which object each pointer relates to, and
85#. potentially update each of those copies.
86
87This document describes the mechanism by which an LLVM based compiler
88can provide this information to a language runtime/collector, and
89ensure that all pointers can be read and updated if desired.  The
90heart of the approach is to construct (or rewrite) the IR in a manner
91where the possible updates performed by the garbage collector are
92explicitly visible in the IR.  Doing so requires that we:
93
94#. create a new SSA value for each potentially relocated pointer, and
95   ensure that no uses of the original (non relocated) value is
96   reachable after the safepoint,
97#. specify the relocation in a way which is opaque to the compiler to
98   ensure that the optimizer can not introduce new uses of an
99   unrelocated value after a statepoint. This prevents the optimizer
100   from performing unsound optimizations.
101#. recording a mapping of live pointers (and the allocation they're
102   associated with) for each statepoint.
103
104At the most abstract level, inserting a safepoint can be thought of as
105replacing a call instruction with a call to a multiple return value
106function which both calls the original target of the call, returns
107it's result, and returns updated values for any live pointers to
108garbage collected objects.
109
110  Note that the task of identifying all live pointers to garbage
111  collected values, transforming the IR to expose a pointer giving the
112  base object for every such live pointer, and inserting all the
113  intrinsics correctly is explicitly out of scope for this document.
114  The recommended approach is to use the :ref:`utility passes
115  <statepoint-utilities>` described below.
116
117This abstract function call is concretely represented by a sequence of
118intrinsic calls known collectively as a "statepoint relocation sequence".
119
120Let's consider a simple call in LLVM IR:
121
122.. code-block:: llvm
123
124  define i8 addrspace(1)* @test1(i8 addrspace(1)* %obj)
125         gc "statepoint-example" {
126    call void ()* @foo()
127    ret i8 addrspace(1)* %obj
128  }
129
130Depending on our language we may need to allow a safepoint during the execution
131of ``foo``. If so, we need to let the collector update local values in the
132current frame.  If we don't, we'll be accessing a potential invalid reference
133once we eventually return from the call.
134
135In this example, we need to relocate the SSA value ``%obj``.  Since we can't
136actually change the value in the SSA value ``%obj``, we need to introduce a new
137SSA value ``%obj.relocated`` which represents the potentially changed value of
138``%obj`` after the safepoint and update any following uses appropriately.  The
139resulting relocation sequence is:
140
141.. code-block:: llvm
142
143  define i8 addrspace(1)* @test1(i8 addrspace(1)* %obj)
144         gc "statepoint-example" {
145    %0 = call token (i64, i32, void ()*, i32, i32, ...)* @llvm.experimental.gc.statepoint.p0f_isVoidf(i64 0, i32 0, void ()* @foo, i32 0, i32 0, i32 0, i32 0, i8 addrspace(1)* %obj)
146    %obj.relocated = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(token %0, i32 7, i32 7)
147    ret i8 addrspace(1)* %obj.relocated
148  }
149
150Ideally, this sequence would have been represented as a M argument, N
151return value function (where M is the number of values being
152relocated + the original call arguments and N is the original return
153value + each relocated value), but LLVM does not easily support such a
154representation.
155
156Instead, the statepoint intrinsic marks the actual site of the
157safepoint or statepoint.  The statepoint returns a token value (which
158exists only at compile time).  To get back the original return value
159of the call, we use the ``gc.result`` intrinsic.  To get the relocation
160of each pointer in turn, we use the ``gc.relocate`` intrinsic with the
161appropriate index.  Note that both the ``gc.relocate`` and ``gc.result`` are
162tied to the statepoint.  The combination forms a "statepoint relocation
163sequence" and represents the entirety of a parseable call or 'statepoint'.
164
165When lowered, this example would generate the following x86 assembly:
166
167.. code-block:: gas
168
169	  .globl	test1
170	  .align	16, 0x90
171	  pushq	%rax
172	  callq	foo
173  .Ltmp1:
174	  movq	(%rsp), %rax  # This load is redundant (oops!)
175	  popq	%rdx
176	  retq
177
178Each of the potentially relocated values has been spilled to the
179stack, and a record of that location has been recorded to the
180:ref:`Stack Map section <stackmap-section>`.  If the garbage collector
181needs to update any of these pointers during the call, it knows
182exactly what to change.
183
184The relevant parts of the StackMap section for our example are:
185
186.. code-block:: gas
187
188  # This describes the call site
189  # Stack Maps: callsite 2882400000
190	  .quad	2882400000
191	  .long	.Ltmp1-test1
192	  .short	0
193  # .. 8 entries skipped ..
194  # This entry describes the spill slot which is directly addressable
195  # off RSP with offset 0.  Given the value was spilled with a pushq,
196  # that makes sense.
197  # Stack Maps:   Loc 8: Direct RSP     [encoding: .byte 2, .byte 8, .short 7, .int 0]
198	  .byte	2
199	  .byte	8
200	  .short	7
201	  .long	0
202
203This example was taken from the tests for the :ref:`RewriteStatepointsForGC` utility pass.  As such, it's full StackMap can be easily examined with the following command.
204
205.. code-block:: bash
206
207  opt -rewrite-statepoints-for-gc test/Transforms/RewriteStatepointsForGC/basics.ll -S | llc -debug-only=stackmaps
208
209Base & Derived Pointers
210^^^^^^^^^^^^^^^^^^^^^^^
211
212A "base pointer" is one which points to the starting address of an allocation
213(object).  A "derived pointer" is one which is offset from a base pointer by
214some amount.  When relocating objects, a garbage collector needs to be able
215to relocate each derived pointer associated with an allocation to the same
216offset from the new address.
217
218"Interior derived pointers" remain within the bounds of the allocation
219they're associated with.  As a result, the base object can be found at
220runtime provided the bounds of allocations are known to the runtime system.
221
222"Exterior derived pointers" are outside the bounds of the associated object;
223they may even fall within *another* allocations address range.  As a result,
224there is no way for a garbage collector to determine which allocation they
225are associated with at runtime and compiler support is needed.
226
227The ``gc.relocate`` intrinsic supports an explicit operand for describing the
228allocation associated with a derived pointer.  This operand is frequently
229referred to as the base operand, but does not strictly speaking have to be
230a base pointer, but it does need to lie within the bounds of the associated
231allocation.  Some collectors may require that the operand be an actual base
232pointer rather than merely an internal derived pointer. Note that during
233lowering both the base and derived pointer operands are required to be live
234over the associated call safepoint even if the base is otherwise unused
235afterwards.
236
237If we extend our previous example to include a pointless derived pointer,
238we get:
239
240.. code-block:: llvm
241
242  define i8 addrspace(1)* @test1(i8 addrspace(1)* %obj)
243         gc "statepoint-example" {
244    %gep = getelementptr i8, i8 addrspace(1)* %obj, i64 20000
245    %token = call token (i64, i32, void ()*, i32, i32, ...)* @llvm.experimental.gc.statepoint.p0f_isVoidf(i64 0, i32 0, void ()* @foo, i32 0, i32 0, i32 0, i32 0, i8 addrspace(1)* %obj, i8 addrspace(1)* %gep)
246    %obj.relocated = call i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(token %token, i32 7, i32 7)
247    %gep.relocated = call i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(token %token, i32 7, i32 8)
248    %p = getelementptr i8, i8 addrspace(1)* %gep, i64 -20000
249    ret i8 addrspace(1)* %p
250  }
251
252Note that in this example %p and %obj.relocate are the same address and we
253could replace one with the other, potentially removing the derived pointer
254from the live set at the safepoint entirely.
255
256.. _gc_transition_args:
257
258GC Transitions
259^^^^^^^^^^^^^^^^^^
260
261As a practical consideration, many garbage-collected systems allow code that is
262collector-aware ("managed code") to call code that is not collector-aware
263("unmanaged code"). It is common that such calls must also be safepoints, since
264it is desirable to allow the collector to run during the execution of
265unmanaged code. Furthermore, it is common that coordinating the transition from
266managed to unmanaged code requires extra code generation at the call site to
267inform the collector of the transition. In order to support these needs, a
268statepoint may be marked as a GC transition, and data that is necessary to
269perform the transition (if any) may be provided as additional arguments to the
270statepoint.
271
272  Note that although in many cases statepoints may be inferred to be GC
273  transitions based on the function symbols involved (e.g. a call from a
274  function with GC strategy "foo" to a function with GC strategy "bar"),
275  indirect calls that are also GC transitions must also be supported. This
276  requirement is the driving force behind the decision to require that GC
277  transitions are explicitly marked.
278
279Let's revisit the sample given above, this time treating the call to ``@foo``
280as a GC transition. Depending on our target, the transition code may need to
281access some extra state in order to inform the collector of the transition.
282Let's assume a hypothetical GC--somewhat unimaginatively named "hypothetical-gc"
283--that requires that a TLS variable must be written to before and after a call
284to unmanaged code. The resulting relocation sequence is:
285
286.. code-block:: llvm
287
288  @flag = thread_local global i32 0, align 4
289
290  define i8 addrspace(1)* @test1(i8 addrspace(1) *%obj)
291         gc "hypothetical-gc" {
292
293    %0 = call token (i64, i32, void ()*, i32, i32, ...)* @llvm.experimental.gc.statepoint.p0f_isVoidf(i64 0, i32 0, void ()* @foo, i32 0, i32 1, i32* @Flag, i32 0, i8 addrspace(1)* %obj)
294    %obj.relocated = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(token %0, i32 7, i32 7)
295    ret i8 addrspace(1)* %obj.relocated
296  }
297
298During lowering, this will result in a instruction selection DAG that looks
299something like:
300
301::
302
303  CALLSEQ_START
304  ...
305  GC_TRANSITION_START (lowered i32 *@Flag), SRCVALUE i32* Flag
306  STATEPOINT
307  GC_TRANSITION_END (lowered i32 *@Flag), SRCVALUE i32 *Flag
308  ...
309  CALLSEQ_END
310
311In order to generate the necessary transition code, the backend for each target
312supported by "hypothetical-gc" must be modified to lower ``GC_TRANSITION_START``
313and ``GC_TRANSITION_END`` nodes appropriately when the "hypothetical-gc"
314strategy is in use for a particular function. Assuming that such lowering has
315been added for X86, the generated assembly would be:
316
317.. code-block:: gas
318
319	  .globl	test1
320	  .align	16, 0x90
321	  pushq	%rax
322	  movl $1, %fs:Flag@TPOFF
323	  callq	foo
324	  movl $0, %fs:Flag@TPOFF
325  .Ltmp1:
326	  movq	(%rsp), %rax  # This load is redundant (oops!)
327	  popq	%rdx
328	  retq
329
330Note that the design as presented above is not fully implemented: in particular,
331strategy-specific lowering is not present, and all GC transitions are emitted as
332as single no-op before and after the call instruction. These no-ops are often
333removed by the backend during dead machine instruction elimination.
334
335
336Intrinsics
337===========
338
339'llvm.experimental.gc.statepoint' Intrinsic
340^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
341
342Syntax:
343"""""""
344
345::
346
347      declare token
348        @llvm.experimental.gc.statepoint(i64 <id>, i32 <num patch bytes>,
349                       func_type <target>,
350                       i64 <#call args>, i64 <flags>,
351                       ... (call parameters),
352                       i64 <# transition args>, ... (transition parameters),
353                       i64 <# deopt args>, ... (deopt parameters),
354                       ... (gc parameters))
355
356Overview:
357"""""""""
358
359The statepoint intrinsic represents a call which is parse-able by the
360runtime.
361
362Operands:
363"""""""""
364
365The 'id' operand is a constant integer that is reported as the ID
366field in the generated stackmap.  LLVM does not interpret this
367parameter in any way and its meaning is up to the statepoint user to
368decide.  Note that LLVM is free to duplicate code containing
369statepoint calls, and this may transform IR that had a unique 'id' per
370lexical call to statepoint to IR that does not.
371
372If 'num patch bytes' is non-zero then the call instruction
373corresponding to the statepoint is not emitted and LLVM emits 'num
374patch bytes' bytes of nops in its place.  LLVM will emit code to
375prepare the function arguments and retrieve the function return value
376in accordance to the calling convention; the former before the nop
377sequence and the latter after the nop sequence.  It is expected that
378the user will patch over the 'num patch bytes' bytes of nops with a
379calling sequence specific to their runtime before executing the
380generated machine code.  There are no guarantees with respect to the
381alignment of the nop sequence.  Unlike :doc:`StackMaps` statepoints do
382not have a concept of shadow bytes.  Note that semantically the
383statepoint still represents a call or invoke to 'target', and the nop
384sequence after patching is expected to represent an operation
385equivalent to a call or invoke to 'target'.
386
387The 'target' operand is the function actually being called.  The
388target can be specified as either a symbolic LLVM function, or as an
389arbitrary Value of appropriate function type.  Note that the function
390type must match the signature of the callee and the types of the 'call
391parameters' arguments.
392
393The '#call args' operand is the number of arguments to the actual
394call.  It must exactly match the number of arguments passed in the
395'call parameters' variable length section.
396
397The 'flags' operand is used to specify extra information about the
398statepoint. This is currently only used to mark certain statepoints
399as GC transitions. This operand is a 64-bit integer with the following
400layout, where bit 0 is the least significant bit:
401
402  +-------+---------------------------------------------------+
403  | Bit # | Usage                                             |
404  +=======+===================================================+
405  |     0 | Set if the statepoint is a GC transition, cleared |
406  |       | otherwise.                                        |
407  +-------+---------------------------------------------------+
408  |  1-63 | Reserved for future use; must be cleared.         |
409  +-------+---------------------------------------------------+
410
411The 'call parameters' arguments are simply the arguments which need to
412be passed to the call target.  They will be lowered according to the
413specified calling convention and otherwise handled like a normal call
414instruction.  The number of arguments must exactly match what is
415specified in '# call args'.  The types must match the signature of
416'target'.
417
418The 'transition parameters' arguments contain an arbitrary list of
419Values which need to be passed to GC transition code. They will be
420lowered and passed as operands to the appropriate GC_TRANSITION nodes
421in the selection DAG. It is assumed that these arguments must be
422available before and after (but not necessarily during) the execution
423of the callee. The '# transition args' field indicates how many operands
424are to be interpreted as 'transition parameters'.
425
426The 'deopt parameters' arguments contain an arbitrary list of Values
427which is meaningful to the runtime.  The runtime may read any of these
428values, but is assumed not to modify them.  If the garbage collector
429might need to modify one of these values, it must also be listed in
430the 'gc pointer' argument list.  The '# deopt args' field indicates
431how many operands are to be interpreted as 'deopt parameters'.
432
433The 'gc parameters' arguments contain every pointer to a garbage
434collector object which potentially needs to be updated by the garbage
435collector.  Note that the argument list must explicitly contain a base
436pointer for every derived pointer listed.  The order of arguments is
437unimportant.  Unlike the other variable length parameter sets, this
438list is not length prefixed.
439
440Semantics:
441""""""""""
442
443A statepoint is assumed to read and write all memory.  As a result,
444memory operations can not be reordered past a statepoint.  It is
445illegal to mark a statepoint as being either 'readonly' or 'readnone'.
446
447Note that legal IR can not perform any memory operation on a 'gc
448pointer' argument of the statepoint in a location statically reachable
449from the statepoint.  Instead, the explicitly relocated value (from a
450``gc.relocate``) must be used.
451
452'llvm.experimental.gc.result' Intrinsic
453^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
454
455Syntax:
456"""""""
457
458::
459
460      declare type*
461        @llvm.experimental.gc.result(token %statepoint_token)
462
463Overview:
464"""""""""
465
466``gc.result`` extracts the result of the original call instruction
467which was replaced by the ``gc.statepoint``.  The ``gc.result``
468intrinsic is actually a family of three intrinsics due to an
469implementation limitation.  Other than the type of the return value,
470the semantics are the same.
471
472Operands:
473"""""""""
474
475The first and only argument is the ``gc.statepoint`` which starts
476the safepoint sequence of which this ``gc.result`` is a part.
477Despite the typing of this as a generic token, *only* the value defined
478by a ``gc.statepoint`` is legal here.
479
480Semantics:
481""""""""""
482
483The ``gc.result`` represents the return value of the call target of
484the ``statepoint``.  The type of the ``gc.result`` must exactly match
485the type of the target.  If the call target returns void, there will
486be no ``gc.result``.
487
488A ``gc.result`` is modeled as a 'readnone' pure function.  It has no
489side effects since it is just a projection of the return value of the
490previous call represented by the ``gc.statepoint``.
491
492'llvm.experimental.gc.relocate' Intrinsic
493^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
494
495Syntax:
496"""""""
497
498::
499
500      declare <pointer type>
501        @llvm.experimental.gc.relocate(token %statepoint_token,
502                                       i32 %base_offset,
503                                       i32 %pointer_offset)
504
505Overview:
506"""""""""
507
508A ``gc.relocate`` returns the potentially relocated value of a pointer
509at the safepoint.
510
511Operands:
512"""""""""
513
514The first argument is the ``gc.statepoint`` which starts the
515safepoint sequence of which this ``gc.relocation`` is a part.
516Despite the typing of this as a generic token, *only* the value defined
517by a ``gc.statepoint`` is legal here.
518
519The second argument is an index into the statepoints list of arguments
520which specifies the allocation for the pointer being relocated.
521This index must land within the 'gc parameter' section of the
522statepoint's argument list.  The associated value must be within the
523object with which the pointer being relocated is associated. The optimizer
524is free to change *which* interior derived pointer is reported, provided that
525it does not replace an actual base pointer with another interior derived
526pointer.  Collectors are allowed to rely on the base pointer operand
527remaining an actual base pointer if so constructed.
528
529The third argument is an index into the statepoint's list of arguments
530which specify the (potentially) derived pointer being relocated.  It
531is legal for this index to be the same as the second argument
532if-and-only-if a base pointer is being relocated. This index must land
533within the 'gc parameter' section of the statepoint's argument list.
534
535Semantics:
536""""""""""
537
538The return value of ``gc.relocate`` is the potentially relocated value
539of the pointer specified by it's arguments.  It is unspecified how the
540value of the returned pointer relates to the argument to the
541``gc.statepoint`` other than that a) it points to the same source
542language object with the same offset, and b) the 'based-on'
543relationship of the newly relocated pointers is a projection of the
544unrelocated pointers.  In particular, the integer value of the pointer
545returned is unspecified.
546
547A ``gc.relocate`` is modeled as a ``readnone`` pure function.  It has no
548side effects since it is just a way to extract information about work
549done during the actual call modeled by the ``gc.statepoint``.
550
551.. _statepoint-stackmap-format:
552
553Stack Map Format
554================
555
556Locations for each pointer value which may need read and/or updated by
557the runtime or collector are provided via the :ref:`Stack Map format
558<stackmap-format>` specified in the PatchPoint documentation.
559
560Each statepoint generates the following Locations:
561
562* Constant which describes the calling convention of the call target. This
563  constant is a valid :ref:`calling convention identifier <callingconv>` for
564  the version of LLVM used to generate the stackmap. No additional compatibility
565  guarantees are made for this constant over what LLVM provides elsewhere w.r.t.
566  these identifiers.
567* Constant which describes the flags passed to the statepoint intrinsic
568* Constant which describes number of following deopt *Locations* (not
569  operands)
570* Variable number of Locations, one for each deopt parameter listed in
571  the IR statepoint (same number as described by previous Constant).  At
572  the moment, only deopt parameters with a bitwidth of 64 bits or less
573  are supported.  Values of a type larger than 64 bits can be specified
574  and reported only if a) the value is constant at the call site, and b)
575  the constant can be represented with less than 64 bits (assuming zero
576  extension to the original bitwidth).
577* Variable number of relocation records, each of which consists of
578  exactly two Locations.  Relocation records are described in detail
579  below.
580
581Each relocation record provides sufficient information for a collector to
582relocate one or more derived pointers.  Each record consists of a pair of
583Locations.  The second element in the record represents the pointer (or
584pointers) which need updated.  The first element in the record provides a
585pointer to the base of the object with which the pointer(s) being relocated is
586associated.  This information is required for handling generalized derived
587pointers since a pointer may be outside the bounds of the original allocation,
588but still needs to be relocated with the allocation.  Additionally:
589
590* It is guaranteed that the base pointer must also appear explicitly as a
591  relocation pair if used after the statepoint.
592* There may be fewer relocation records then gc parameters in the IR
593  statepoint. Each *unique* pair will occur at least once; duplicates
594  are possible.
595* The Locations within each record may either be of pointer size or a
596  multiple of pointer size.  In the later case, the record must be
597  interpreted as describing a sequence of pointers and their corresponding
598  base pointers. If the Location is of size N x sizeof(pointer), then
599  there will be N records of one pointer each contained within the Location.
600  Both Locations in a pair can be assumed to be of the same size.
601
602Note that the Locations used in each section may describe the same
603physical location.  e.g. A stack slot may appear as a deopt location,
604a gc base pointer, and a gc derived pointer.
605
606The LiveOut section of the StkMapRecord will be empty for a statepoint
607record.
608
609Safepoint Semantics & Verification
610==================================
611
612The fundamental correctness property for the compiled code's
613correctness w.r.t. the garbage collector is a dynamic one.  It must be
614the case that there is no dynamic trace such that a operation
615involving a potentially relocated pointer is observably-after a
616safepoint which could relocate it.  'observably-after' is this usage
617means that an outside observer could observe this sequence of events
618in a way which precludes the operation being performed before the
619safepoint.
620
621To understand why this 'observable-after' property is required,
622consider a null comparison performed on the original copy of a
623relocated pointer.  Assuming that control flow follows the safepoint,
624there is no way to observe externally whether the null comparison is
625performed before or after the safepoint.  (Remember, the original
626Value is unmodified by the safepoint.)  The compiler is free to make
627either scheduling choice.
628
629The actual correctness property implemented is slightly stronger than
630this.  We require that there be no *static path* on which a
631potentially relocated pointer is 'observably-after' it may have been
632relocated.  This is slightly stronger than is strictly necessary (and
633thus may disallow some otherwise valid programs), but greatly
634simplifies reasoning about correctness of the compiled code.
635
636By construction, this property will be upheld by the optimizer if
637correctly established in the source IR.  This is a key invariant of
638the design.
639
640The existing IR Verifier pass has been extended to check most of the
641local restrictions on the intrinsics mentioned in their respective
642documentation.  The current implementation in LLVM does not check the
643key relocation invariant, but this is ongoing work on developing such
644a verifier.  Please ask on llvm-dev if you're interested in
645experimenting with the current version.
646
647.. _statepoint-utilities:
648
649Utility Passes for Safepoint Insertion
650======================================
651
652.. _RewriteStatepointsForGC:
653
654RewriteStatepointsForGC
655^^^^^^^^^^^^^^^^^^^^^^^^
656
657The pass RewriteStatepointsForGC transforms a functions IR by replacing a
658``gc.statepoint`` (with an optional ``gc.result``) with a full relocation
659sequence, including all required ``gc.relocates``.  To function, the pass
660requires that the GC strategy specified for the function be able to reliably
661distinguish between GC references and non-GC references in IR it is given.
662
663As an example, given this code:
664
665.. code-block:: llvm
666
667  define i8 addrspace(1)* @test1(i8 addrspace(1)* %obj)
668         gc "statepoint-example" {
669    call token (i64, i32, void ()*, i32, i32, ...)* @llvm.experimental.gc.statepoint.p0f_isVoidf(i64 2882400000, i32 0, void ()* @foo, i32 0, i32 0, i32 0, i32 5, i32 0, i32 -1, i32 0, i32 0, i32 0)
670    ret i8 addrspace(1)* %obj
671  }
672
673The pass would produce this IR:
674
675.. code-block:: llvm
676
677  define i8 addrspace(1)* @test1(i8 addrspace(1)* %obj)
678         gc "statepoint-example" {
679    %0 = call token (i64, i32, void ()*, i32, i32, ...)* @llvm.experimental.gc.statepoint.p0f_isVoidf(i64 2882400000, i32 0, void ()* @foo, i32 0, i32 0, i32 0, i32 5, i32 0, i32 -1, i32 0, i32 0, i32 0, i8 addrspace(1)* %obj)
680    %obj.relocated = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(token %0, i32 12, i32 12)
681    ret i8 addrspace(1)* %obj.relocated
682  }
683
684In the above examples, the addrspace(1) marker on the pointers is the mechanism
685that the ``statepoint-example`` GC strategy uses to distinguish references from
686non references.  Address space 1 is not globally reserved for this purpose.
687
688This pass can be used an utility function by a language frontend that doesn't
689want to manually reason about liveness, base pointers, or relocation when
690constructing IR.  As currently implemented, RewriteStatepointsForGC must be
691run after SSA construction (i.e. mem2ref).
692
693RewriteStatepointsForGC will ensure that appropriate base pointers are listed
694for every relocation created.  It will do so by duplicating code as needed to
695propagate the base pointer associated with each pointer being relocated to
696the appropriate safepoints.  The implementation assumes that the following
697IR constructs produce base pointers: loads from the heap, addresses of global
698variables, function arguments, function return values. Constant pointers (such
699as null) are also assumed to be base pointers.  In practice, this constraint
700can be relaxed to producing interior derived pointers provided the target
701collector can find the associated allocation from an arbitrary interior
702derived pointer.
703
704In practice, RewriteStatepointsForGC can be run much later in the pass
705pipeline, after most optimization is already done.  This helps to improve
706the quality of the generated code when compiled with garbage collection support.
707In the long run, this is the intended usage model.  At this time, a few details
708have yet to be worked out about the semantic model required to guarantee this
709is always correct.  As such, please use with caution and report bugs.
710
711.. _PlaceSafepoints:
712
713PlaceSafepoints
714^^^^^^^^^^^^^^^^
715
716The pass PlaceSafepoints transforms a function's IR by replacing any call or
717invoke instructions with appropriate ``gc.statepoint`` and ``gc.result`` pairs,
718and inserting safepoint polls sufficient to ensure running code checks for a
719safepoint request on a timely manner.  This pass is expected to be run before
720RewriteStatepointsForGC and thus does not produce full relocation sequences.
721
722As an example, given input IR of the following:
723
724.. code-block:: llvm
725
726  define void @test() gc "statepoint-example" {
727    call void @foo()
728    ret void
729  }
730
731  declare void @do_safepoint()
732  define void @gc.safepoint_poll() {
733    call void @do_safepoint()
734    ret void
735  }
736
737
738This pass would produce the following IR:
739
740.. code-block:: llvm
741
742  define void @test() gc "statepoint-example" {
743    %safepoint_token = call token (i64, i32, void ()*, i32, i32, ...)* @llvm.experimental.gc.statepoint.p0f_isVoidf(i64 2882400000, i32 0, void ()* @do_safepoint, i32 0, i32 0, i32 0, i32 0)
744    %safepoint_token1 = call token (i64, i32, void ()*, i32, i32, ...)* @llvm.experimental.gc.statepoint.p0f_isVoidf(i64 2882400000, i32 0, void ()* @foo, i32 0, i32 0, i32 0, i32 0)
745    ret void
746  }
747
748In this case, we've added an (unconditional) entry safepoint poll and converted the call into a ``gc.statepoint``.  Note that despite appearances, the entry poll is not necessarily redundant.  We'd have to know that ``foo`` and ``test`` were not mutually recursive for the poll to be redundant.  In practice, you'd probably want to your poll definition to contain a conditional branch of some form.
749
750
751At the moment, PlaceSafepoints can insert safepoint polls at method entry and
752loop backedges locations.  Extending this to work with return polls would be
753straight forward if desired.
754
755PlaceSafepoints includes a number of optimizations to avoid placing safepoint
756polls at particular sites unless needed to ensure timely execution of a poll
757under normal conditions.  PlaceSafepoints does not attempt to ensure timely
758execution of a poll under worst case conditions such as heavy system paging.
759
760The implementation of a safepoint poll action is specified by looking up a
761function of the name ``gc.safepoint_poll`` in the containing Module.  The body
762of this function is inserted at each poll site desired.  While calls or invokes
763inside this method are transformed to a ``gc.statepoints``, recursive poll
764insertion is not performed.
765
766By default PlaceSafepoints passes in ``0xABCDEF00`` as the statepoint
767ID and ``0`` as the number of patchable bytes to the newly constructed
768``gc.statepoint``.  These values can be configured on a per-callsite
769basis using the attributes ``"statepoint-id"`` and
770``"statepoint-num-patch-bytes"``.  If a call site is marked with a
771``"statepoint-id"`` function attribute and its value is a positive
772integer (represented as a string), then that value is used as the ID
773of the newly constructed ``gc.statepoint``.  If a call site is marked
774with a ``"statepoint-num-patch-bytes"`` function attribute and its
775value is a positive integer, then that value is used as the 'num patch
776bytes' parameter of the newly constructed ``gc.statepoint``.  The
777``"statepoint-id"`` and ``"statepoint-num-patch-bytes"`` attributes
778are not propagated to the ``gc.statepoint`` call or invoke if they
779could be successfully parsed.
780
781If you are scheduling the RewriteStatepointsForGC pass late in the pass order,
782you should probably schedule this pass immediately before it.  The exception
783would be if you need to preserve abstract frame information (e.g. for
784deoptimization or introspection) at safepoints.  In that case, ask on the
785llvm-dev mailing list for suggestions.
786
787
788Supported Architectures
789=======================
790
791Support for statepoint generation requires some code for each backend.
792Today, only X86_64 is supported.
793
794Problem Areas and Active Work
795=============================
796
797#. As the existing users of the late rewriting model have matured, we've found
798   cases where the optimizer breaks the assumption that an SSA value of
799   gc-pointer type actually contains a gc-pointer and vice-versa.  We need to
800   clarify our expectations and propose at least one small IR change.  (Today,
801   the gc-pointer distinction is managed via address spaces.  This turns out
802   not to be quite strong enough.)
803
804#. Support for languages which allow unmanaged pointers to garbage collected
805   objects (i.e. pass a pointer to an object to a C routine) via pinning.
806
807#. Support for garbage collected objects allocated on the stack.  Specifically,
808   allocas are always assumed to be in address space 0 and we need a
809   cast/promotion operator to let rewriting identify them.
810
811#. The current statepoint lowering is known to be somewhat poor.  In the very
812   long term, we'd like to integrate statepoints with the register allocator;
813   in the near term this is unlikely to happen.  We've found the quality of
814   lowering to be relatively unimportant as hot-statepoints are almost always
815   inliner bugs.
816
817#. Concerns have been raised that the statepoint representation results in a
818   large amount of IR being produced for some examples and that this
819   contributes to higher than expected memory usage and compile times.  There's
820   no immediate plans to make changes due to this, but alternate models may be
821   explored in the future.
822
823#. Relocations along exceptional paths are currently broken in ToT.  In
824   particular, there is current no way to represent a rethrow on a path which
825   also has relocations.  See `this llvm-dev discussion
826   <https://groups.google.com/forum/#!topic/llvm-dev/AE417XjgxvI>`_ for more
827   detail.
828
829Bugs and Enhancements
830=====================
831
832Currently known bugs and enhancements under consideration can be
833tracked by performing a `bugzilla search
834<http://llvm.org/bugs/buglist.cgi?cmdtype=runnamed&namedcmd=Statepoint%20Bugs&list_id=64342>`_
835for [Statepoint] in the summary field. When filing new bugs, please
836use this tag so that interested parties see the newly filed bug.  As
837with most LLVM features, design discussions take place on `llvm-dev
838<http://lists.llvm.org/mailman/listinfo/llvm-dev>`_, and patches
839should be sent to `llvm-commits
840<http://lists.llvm.org/mailman/listinfo/llvm-commits>`_ for review.
841
842