xref: /openbsd-src/gnu/llvm/llvm/docs/Coroutines.rst (revision d415bd752c734aee168c4ee86ff32e8cc249eb16)
1=====================================
2Coroutines in LLVM
3=====================================
4
5.. contents::
6   :local:
7   :depth: 3
8
9.. warning::
10  This is a work in progress. Compatibility across LLVM releases is not
11  guaranteed.
12
13Introduction
14============
15
16.. _coroutine handle:
17
18LLVM coroutines are functions that have one or more `suspend points`_.
19When a suspend point is reached, the execution of a coroutine is suspended and
20control is returned back to its caller. A suspended coroutine can be resumed
21to continue execution from the last suspend point or it can be destroyed.
22
23In the following example, we call function `f` (which may or may not be a
24coroutine itself) that returns a handle to a suspended coroutine
25(**coroutine handle**) that is used by `main` to resume the coroutine twice and
26then destroy it:
27
28.. code-block:: llvm
29
30  define i32 @main() {
31  entry:
32    %hdl = call i8* @f(i32 4)
33    call void @llvm.coro.resume(i8* %hdl)
34    call void @llvm.coro.resume(i8* %hdl)
35    call void @llvm.coro.destroy(i8* %hdl)
36    ret i32 0
37  }
38
39.. _coroutine frame:
40
41In addition to the function stack frame which exists when a coroutine is
42executing, there is an additional region of storage that contains objects that
43keep the coroutine state when a coroutine is suspended. This region of storage
44is called the **coroutine frame**. It is created when a coroutine is called
45and destroyed when a coroutine either runs to completion or is destroyed
46while suspended.
47
48LLVM currently supports two styles of coroutine lowering. These styles
49support substantially different sets of features, have substantially
50different ABIs, and expect substantially different patterns of frontend
51code generation. However, the styles also have a great deal in common.
52
53In all cases, an LLVM coroutine is initially represented as an ordinary LLVM
54function that has calls to `coroutine intrinsics`_ defining the structure of
55the coroutine. The coroutine function is then, in the most general case,
56rewritten by the coroutine lowering passes to become the "ramp function",
57the initial entrypoint of the coroutine, which executes until a suspend point
58is first reached. The remainder of the original coroutine function is split
59out into some number of "resume functions". Any state which must persist
60across suspensions is stored in the coroutine frame. The resume functions
61must somehow be able to handle either a "normal" resumption, which continues
62the normal execution of the coroutine, or an "abnormal" resumption, which
63must unwind the coroutine without attempting to suspend it.
64
65Switched-Resume Lowering
66------------------------
67
68In LLVM's standard switched-resume lowering, signaled by the use of
69`llvm.coro.id`, the coroutine frame is stored as part of a "coroutine
70object" which represents a handle to a particular invocation of the
71coroutine.  All coroutine objects support a common ABI allowing certain
72features to be used without knowing anything about the coroutine's
73implementation:
74
75- A coroutine object can be queried to see if it has reached completion
76  with `llvm.coro.done`.
77
78- A coroutine object can be resumed normally if it has not already reached
79  completion with `llvm.coro.resume`.
80
81- A coroutine object can be destroyed, invalidating the coroutine object,
82  with `llvm.coro.destroy`.  This must be done separately even if the
83  coroutine has reached completion normally.
84
85- "Promise" storage, which is known to have a certain size and alignment,
86  can be projected out of the coroutine object with `llvm.coro.promise`.
87  The coroutine implementation must have been compiled to define a promise
88  of the same size and alignment.
89
90In general, interacting with a coroutine object in any of these ways while
91it is running has undefined behavior.
92
93The coroutine function is split into three functions, representing three
94different ways that control can enter the coroutine:
95
961. the ramp function that is initially invoked, which takes arbitrary
97   arguments and returns a pointer to the coroutine object;
98
992. a coroutine resume function that is invoked when the coroutine is resumed,
100   which takes a pointer to the coroutine object and returns `void`;
101
1023. a coroutine destroy function that is invoked when the coroutine is
103   destroyed, which takes a pointer to the coroutine object and returns
104   `void`.
105
106Because the resume and destroy functions are shared across all suspend
107points, suspend points must store the index of the active suspend in
108the coroutine object, and the resume/destroy functions must switch over
109that index to get back to the correct point.  Hence the name of this
110lowering.
111
112Pointers to the resume and destroy functions are stored in the coroutine
113object at known offsets which are fixed for all coroutines.  A completed
114coroutine is represented with a null resume function.
115
116There is a somewhat complex protocol of intrinsics for allocating and
117deallocating the coroutine object.  It is complex in order to allow the
118allocation to be elided due to inlining.  This protocol is discussed
119in further detail below.
120
121The frontend may generate code to call the coroutine function directly;
122this will become a call to the ramp function and will return a pointer
123to the coroutine object.  The frontend should always resume or destroy
124the coroutine using the corresponding intrinsics.
125
126Returned-Continuation Lowering
127------------------------------
128
129In returned-continuation lowering, signaled by the use of
130`llvm.coro.id.retcon` or `llvm.coro.id.retcon.once`, some aspects of
131the ABI must be handled more explicitly by the frontend.
132
133In this lowering, every suspend point takes a list of "yielded values"
134which are returned back to the caller along with a function pointer,
135called the continuation function.  The coroutine is resumed by simply
136calling this continuation function pointer.  The original coroutine
137is divided into the ramp function and then an arbitrary number of
138these continuation functions, one for each suspend point.
139
140LLVM actually supports two closely-related returned-continuation
141lowerings:
142
143- In normal returned-continuation lowering, the coroutine may suspend
144  itself multiple times. This means that a continuation function
145  itself returns another continuation pointer, as well as a list of
146  yielded values.
147
148  The coroutine indicates that it has run to completion by returning
149  a null continuation pointer. Any yielded values will be `undef`
150  should be ignored.
151
152- In yield-once returned-continuation lowering, the coroutine must
153  suspend itself exactly once (or throw an exception).  The ramp
154  function returns a continuation function pointer and yielded
155  values, but the continuation function simply returns `void`
156  when the coroutine has run to completion.
157
158The coroutine frame is maintained in a fixed-size buffer that is
159passed to the `coro.id` intrinsic, which guarantees a certain size
160and alignment statically. The same buffer must be passed to the
161continuation function(s). The coroutine will allocate memory if the
162buffer is insufficient, in which case it will need to store at
163least that pointer in the buffer; therefore the buffer must always
164be at least pointer-sized. How the coroutine uses the buffer may
165vary between suspend points.
166
167In addition to the buffer pointer, continuation functions take an
168argument indicating whether the coroutine is being resumed normally
169(zero) or abnormally (non-zero).
170
171LLVM is currently ineffective at statically eliminating allocations
172after fully inlining returned-continuation coroutines into a caller.
173This may be acceptable if LLVM's coroutine support is primarily being
174used for low-level lowering and inlining is expected to be applied
175earlier in the pipeline.
176
177Async Lowering
178--------------
179
180In async-continuation lowering, signaled by the use of `llvm.coro.id.async`,
181handling of control-flow must be handled explicitly by the frontend.
182
183In this lowering, a coroutine is assumed to take the current `async context` as
184one of its arguments (the argument position is determined by
185`llvm.coro.id.async`). It is used to marshal arguments and return values of the
186coroutine. Therefore an async coroutine returns `void`.
187
188.. code-block:: llvm
189
190  define swiftcc void @async_coroutine(i8* %async.ctxt, i8*, i8*) {
191  }
192
193Values live across a suspend point need to be stored in the coroutine frame to
194be available in the continuation function. This frame is stored as a tail to the
195`async context`.
196
197Every suspend point takes an `context projection function` argument which
198describes how-to obtain the continuations `async context` and every suspend
199point has an associated `resume function` denoted by the
200`llvm.coro.async.resume` intrinsic. The coroutine is resumed by calling this
201`resume function` passing the `async context` as the one of its arguments
202argument. The `resume function` can restore its (the caller's) `async context`
203by applying a `context projection function` that is provided by the frontend as
204a parameter to the `llvm.coro.suspend.async` intrinsic.
205
206.. code-block:: c
207
208  // For example:
209  struct async_context {
210    struct async_context *caller_context;
211    ...
212  }
213
214  char *context_projection_function(struct async_context *callee_ctxt) {
215     return callee_ctxt->caller_context;
216  }
217
218.. code-block:: llvm
219
220  %resume_func_ptr = call i8* @llvm.coro.async.resume()
221  call {i8*, i8*, i8*} (i8*, i8*, ...) @llvm.coro.suspend.async(
222                                              i8* %resume_func_ptr,
223                                              i8* %context_projection_function
224
225The frontend should provide a `async function pointer` struct associated with
226each async coroutine by `llvm.coro.id.async`'s argument. The initial size and
227alignment of the `async context` must be provided as arguments to the
228`llvm.coro.id.async` intrinsic. Lowering will update the size entry with the
229coroutine frame  requirements. The frontend is responsible for allocating the
230memory for the `async context` but can use the `async function pointer` struct
231to obtain the required size.
232
233.. code-block:: c
234
235  struct async_function_pointer {
236    uint32_t relative_function_pointer_to_async_impl;
237    uint32_t context_size;
238  }
239
240Lowering will split an async coroutine into a ramp function and one resume
241function per suspend point.
242
243How control-flow is passed between caller, suspension point, and back to
244resume function is left up to the frontend.
245
246The suspend point takes a function and its arguments. The function is intended
247to model the transfer to the callee function. It will be tail called by
248lowering and therefore must have the same signature and calling convention as
249the async coroutine.
250
251.. code-block:: llvm
252
253  call {i8*, i8*, i8*} (i8*, i8*, ...) @llvm.coro.suspend.async(
254                   i8* %resume_func_ptr,
255                   i8* %context_projection_function,
256                   i8* (bitcast void (i8*, i8*, i8*)* to i8*) %suspend_function,
257                   i8* %arg1, i8* %arg2, i8 %arg3)
258
259Coroutines by Example
260=====================
261
262The examples below are all of switched-resume coroutines.
263
264Coroutine Representation
265------------------------
266
267Let's look at an example of an LLVM coroutine with the behavior sketched
268by the following pseudo-code.
269
270.. code-block:: c++
271
272  void *f(int n) {
273     for(;;) {
274       print(n++);
275       <suspend> // returns a coroutine handle on first suspend
276     }
277  }
278
279This coroutine calls some function `print` with value `n` as an argument and
280suspends execution. Every time this coroutine resumes, it calls `print` again with an argument one bigger than the last time. This coroutine never completes by itself and must be destroyed explicitly. If we use this coroutine with
281a `main` shown in the previous section. It will call `print` with values 4, 5
282and 6 after which the coroutine will be destroyed.
283
284The LLVM IR for this coroutine looks like this:
285
286.. code-block:: llvm
287
288  define i8* @f(i32 %n) {
289  entry:
290    %id = call token @llvm.coro.id(i32 0, i8* null, i8* null, i8* null)
291    %size = call i32 @llvm.coro.size.i32()
292    %alloc = call i8* @malloc(i32 %size)
293    %hdl = call noalias i8* @llvm.coro.begin(token %id, i8* %alloc)
294    br label %loop
295  loop:
296    %n.val = phi i32 [ %n, %entry ], [ %inc, %loop ]
297    %inc = add nsw i32 %n.val, 1
298    call void @print(i32 %n.val)
299    %0 = call i8 @llvm.coro.suspend(token none, i1 false)
300    switch i8 %0, label %suspend [i8 0, label %loop
301                                  i8 1, label %cleanup]
302  cleanup:
303    %mem = call i8* @llvm.coro.free(token %id, i8* %hdl)
304    call void @free(i8* %mem)
305    br label %suspend
306  suspend:
307    %unused = call i1 @llvm.coro.end(i8* %hdl, i1 false)
308    ret i8* %hdl
309  }
310
311The `entry` block establishes the coroutine frame. The `coro.size`_ intrinsic is
312lowered to a constant representing the size required for the coroutine frame.
313The `coro.begin`_ intrinsic initializes the coroutine frame and returns the
314coroutine handle. The second parameter of `coro.begin` is given a block of memory
315to be used if the coroutine frame needs to be allocated dynamically.
316The `coro.id`_ intrinsic serves as coroutine identity useful in cases when the
317`coro.begin`_ intrinsic get duplicated by optimization passes such as
318jump-threading.
319
320The `cleanup` block destroys the coroutine frame. The `coro.free`_ intrinsic,
321given the coroutine handle, returns a pointer of the memory block to be freed or
322`null` if the coroutine frame was not allocated dynamically. The `cleanup`
323block is entered when coroutine runs to completion by itself or destroyed via
324call to the `coro.destroy`_ intrinsic.
325
326The `suspend` block contains code to be executed when coroutine runs to
327completion or suspended. The `coro.end`_ intrinsic marks the point where
328a coroutine needs to return control back to the caller if it is not an initial
329invocation of the coroutine.
330
331The `loop` blocks represents the body of the coroutine. The `coro.suspend`_
332intrinsic in combination with the following switch indicates what happens to
333control flow when a coroutine is suspended (default case), resumed (case 0) or
334destroyed (case 1).
335
336Coroutine Transformation
337------------------------
338
339One of the steps of coroutine lowering is building the coroutine frame. The
340def-use chains are analyzed to determine which objects need be kept alive across
341suspend points. In the coroutine shown in the previous section, use of virtual register
342`%inc` is separated from the definition by a suspend point, therefore, it
343cannot reside on the stack frame since the latter goes away once the coroutine
344is suspended and control is returned back to the caller. An i32 slot is
345allocated in the coroutine frame and `%inc` is spilled and reloaded from that
346slot as needed.
347
348We also store addresses of the resume and destroy functions so that the
349`coro.resume` and `coro.destroy` intrinsics can resume and destroy the coroutine
350when its identity cannot be determined statically at compile time. For our
351example, the coroutine frame will be:
352
353.. code-block:: llvm
354
355  %f.frame = type { void (%f.frame*)*, void (%f.frame*)*, i32 }
356
357After resume and destroy parts are outlined, function `f` will contain only the
358code responsible for creation and initialization of the coroutine frame and
359execution of the coroutine until a suspend point is reached:
360
361.. code-block:: llvm
362
363  define i8* @f(i32 %n) {
364  entry:
365    %id = call token @llvm.coro.id(i32 0, i8* null, i8* null, i8* null)
366    %alloc = call noalias i8* @malloc(i32 24)
367    %0 = call noalias i8* @llvm.coro.begin(token %id, i8* %alloc)
368    %frame = bitcast i8* %0 to %f.frame*
369    %1 = getelementptr %f.frame, %f.frame* %frame, i32 0, i32 0
370    store void (%f.frame*)* @f.resume, void (%f.frame*)** %1
371    %2 = getelementptr %f.frame, %f.frame* %frame, i32 0, i32 1
372    store void (%f.frame*)* @f.destroy, void (%f.frame*)** %2
373
374    %inc = add nsw i32 %n, 1
375    %inc.spill.addr = getelementptr inbounds %f.Frame, %f.Frame* %FramePtr, i32 0, i32 2
376    store i32 %inc, i32* %inc.spill.addr
377    call void @print(i32 %n)
378
379    ret i8* %frame
380  }
381
382Outlined resume part of the coroutine will reside in function `f.resume`:
383
384.. code-block:: llvm
385
386  define internal fastcc void @f.resume(%f.frame* %frame.ptr.resume) {
387  entry:
388    %inc.spill.addr = getelementptr %f.frame, %f.frame* %frame.ptr.resume, i64 0, i32 2
389    %inc.spill = load i32, i32* %inc.spill.addr, align 4
390    %inc = add i32 %n.val, 1
391    store i32 %inc, i32* %inc.spill.addr, align 4
392    tail call void @print(i32 %inc)
393    ret void
394  }
395
396Whereas function `f.destroy` will contain the cleanup code for the coroutine:
397
398.. code-block:: llvm
399
400  define internal fastcc void @f.destroy(%f.frame* %frame.ptr.destroy) {
401  entry:
402    %0 = bitcast %f.frame* %frame.ptr.destroy to i8*
403    tail call void @free(i8* %0)
404    ret void
405  }
406
407Avoiding Heap Allocations
408-------------------------
409
410A particular coroutine usage pattern, which is illustrated by the `main`
411function in the overview section, where a coroutine is created, manipulated and
412destroyed by the same calling function, is common for coroutines implementing
413RAII idiom and is suitable for allocation elision optimization which avoid
414dynamic allocation by storing the coroutine frame as a static `alloca` in its
415caller.
416
417In the entry block, we will call `coro.alloc`_ intrinsic that will return `true`
418when dynamic allocation is required, and `false` if dynamic allocation is
419elided.
420
421.. code-block:: llvm
422
423  entry:
424    %id = call token @llvm.coro.id(i32 0, i8* null, i8* null, i8* null)
425    %need.dyn.alloc = call i1 @llvm.coro.alloc(token %id)
426    br i1 %need.dyn.alloc, label %dyn.alloc, label %coro.begin
427  dyn.alloc:
428    %size = call i32 @llvm.coro.size.i32()
429    %alloc = call i8* @CustomAlloc(i32 %size)
430    br label %coro.begin
431  coro.begin:
432    %phi = phi i8* [ null, %entry ], [ %alloc, %dyn.alloc ]
433    %hdl = call noalias i8* @llvm.coro.begin(token %id, i8* %phi)
434
435In the cleanup block, we will make freeing the coroutine frame conditional on
436`coro.free`_ intrinsic. If allocation is elided, `coro.free`_ returns `null`
437thus skipping the deallocation code:
438
439.. code-block:: llvm
440
441  cleanup:
442    %mem = call i8* @llvm.coro.free(token %id, i8* %hdl)
443    %need.dyn.free = icmp ne i8* %mem, null
444    br i1 %need.dyn.free, label %dyn.free, label %if.end
445  dyn.free:
446    call void @CustomFree(i8* %mem)
447    br label %if.end
448  if.end:
449    ...
450
451With allocations and deallocations represented as described as above, after
452coroutine heap allocation elision optimization, the resulting main will be:
453
454.. code-block:: llvm
455
456  define i32 @main() {
457  entry:
458    call void @print(i32 4)
459    call void @print(i32 5)
460    call void @print(i32 6)
461    ret i32 0
462  }
463
464Multiple Suspend Points
465-----------------------
466
467Let's consider the coroutine that has more than one suspend point:
468
469.. code-block:: c++
470
471  void *f(int n) {
472     for(;;) {
473       print(n++);
474       <suspend>
475       print(-n);
476       <suspend>
477     }
478  }
479
480Matching LLVM code would look like (with the rest of the code remaining the same
481as the code in the previous section):
482
483.. code-block:: llvm
484
485  loop:
486    %n.addr = phi i32 [ %n, %entry ], [ %inc, %loop.resume ]
487    call void @print(i32 %n.addr) #4
488    %2 = call i8 @llvm.coro.suspend(token none, i1 false)
489    switch i8 %2, label %suspend [i8 0, label %loop.resume
490                                  i8 1, label %cleanup]
491  loop.resume:
492    %inc = add nsw i32 %n.addr, 1
493    %sub = xor i32 %n.addr, -1
494    call void @print(i32 %sub)
495    %3 = call i8 @llvm.coro.suspend(token none, i1 false)
496    switch i8 %3, label %suspend [i8 0, label %loop
497                                  i8 1, label %cleanup]
498
499In this case, the coroutine frame would include a suspend index that will
500indicate at which suspend point the coroutine needs to resume. The resume
501function will use an index to jump to an appropriate basic block and will look
502as follows:
503
504.. code-block:: llvm
505
506  define internal fastcc void @f.Resume(%f.Frame* %FramePtr) {
507  entry.Resume:
508    %index.addr = getelementptr inbounds %f.Frame, %f.Frame* %FramePtr, i64 0, i32 2
509    %index = load i8, i8* %index.addr, align 1
510    %switch = icmp eq i8 %index, 0
511    %n.addr = getelementptr inbounds %f.Frame, %f.Frame* %FramePtr, i64 0, i32 3
512    %n = load i32, i32* %n.addr, align 4
513    br i1 %switch, label %loop.resume, label %loop
514
515  loop.resume:
516    %sub = xor i32 %n, -1
517    call void @print(i32 %sub)
518    br label %suspend
519  loop:
520    %inc = add nsw i32 %n, 1
521    store i32 %inc, i32* %n.addr, align 4
522    tail call void @print(i32 %inc)
523    br label %suspend
524
525  suspend:
526    %storemerge = phi i8 [ 0, %loop ], [ 1, %loop.resume ]
527    store i8 %storemerge, i8* %index.addr, align 1
528    ret void
529  }
530
531If different cleanup code needs to get executed for different suspend points,
532a similar switch will be in the `f.destroy` function.
533
534.. note ::
535
536  Using suspend index in a coroutine state and having a switch in `f.resume` and
537  `f.destroy` is one of the possible implementation strategies. We explored
538  another option where a distinct `f.resume1`, `f.resume2`, etc. are created for
539  every suspend point, and instead of storing an index, the resume and destroy
540  function pointers are updated at every suspend. Early testing showed that the
541  current approach is easier on the optimizer than the latter so it is a
542  lowering strategy implemented at the moment.
543
544Distinct Save and Suspend
545-------------------------
546
547In the previous example, setting a resume index (or some other state change that
548needs to happen to prepare a coroutine for resumption) happens at the same time as
549a suspension of a coroutine. However, in certain cases, it is necessary to control
550when coroutine is prepared for resumption and when it is suspended.
551
552In the following example, a coroutine represents some activity that is driven
553by completions of asynchronous operations `async_op1` and `async_op2` which get
554a coroutine handle as a parameter and resume the coroutine once async
555operation is finished.
556
557.. code-block:: text
558
559  void g() {
560     for (;;)
561       if (cond()) {
562          async_op1(<coroutine-handle>); // will resume once async_op1 completes
563          <suspend>
564          do_one();
565       }
566       else {
567          async_op2(<coroutine-handle>); // will resume once async_op2 completes
568          <suspend>
569          do_two();
570       }
571     }
572  }
573
574In this case, coroutine should be ready for resumption prior to a call to
575`async_op1` and `async_op2`. The `coro.save`_ intrinsic is used to indicate a
576point when coroutine should be ready for resumption (namely, when a resume index
577should be stored in the coroutine frame, so that it can be resumed at the
578correct resume point):
579
580.. code-block:: llvm
581
582  if.true:
583    %save1 = call token @llvm.coro.save(i8* %hdl)
584    call void @async_op1(i8* %hdl)
585    %suspend1 = call i1 @llvm.coro.suspend(token %save1, i1 false)
586    switch i8 %suspend1, label %suspend [i8 0, label %resume1
587                                         i8 1, label %cleanup]
588  if.false:
589    %save2 = call token @llvm.coro.save(i8* %hdl)
590    call void @async_op2(i8* %hdl)
591    %suspend2 = call i1 @llvm.coro.suspend(token %save2, i1 false)
592    switch i8 %suspend1, label %suspend [i8 0, label %resume2
593                                         i8 1, label %cleanup]
594
595.. _coroutine promise:
596
597Coroutine Promise
598-----------------
599
600A coroutine author or a frontend may designate a distinguished `alloca` that can
601be used to communicate with the coroutine. This distinguished alloca is called
602**coroutine promise** and is provided as the second parameter to the
603`coro.id`_ intrinsic.
604
605The following coroutine designates a 32 bit integer `promise` and uses it to
606store the current value produced by a coroutine.
607
608.. code-block:: llvm
609
610  define i8* @f(i32 %n) {
611  entry:
612    %promise = alloca i32
613    %pv = bitcast i32* %promise to i8*
614    %id = call token @llvm.coro.id(i32 0, i8* %pv, i8* null, i8* null)
615    %need.dyn.alloc = call i1 @llvm.coro.alloc(token %id)
616    br i1 %need.dyn.alloc, label %dyn.alloc, label %coro.begin
617  dyn.alloc:
618    %size = call i32 @llvm.coro.size.i32()
619    %alloc = call i8* @malloc(i32 %size)
620    br label %coro.begin
621  coro.begin:
622    %phi = phi i8* [ null, %entry ], [ %alloc, %dyn.alloc ]
623    %hdl = call noalias i8* @llvm.coro.begin(token %id, i8* %phi)
624    br label %loop
625  loop:
626    %n.val = phi i32 [ %n, %coro.begin ], [ %inc, %loop ]
627    %inc = add nsw i32 %n.val, 1
628    store i32 %n.val, i32* %promise
629    %0 = call i8 @llvm.coro.suspend(token none, i1 false)
630    switch i8 %0, label %suspend [i8 0, label %loop
631                                  i8 1, label %cleanup]
632  cleanup:
633    %mem = call i8* @llvm.coro.free(token %id, i8* %hdl)
634    call void @free(i8* %mem)
635    br label %suspend
636  suspend:
637    %unused = call i1 @llvm.coro.end(i8* %hdl, i1 false)
638    ret i8* %hdl
639  }
640
641A coroutine consumer can rely on the `coro.promise`_ intrinsic to access the
642coroutine promise.
643
644.. code-block:: llvm
645
646  define i32 @main() {
647  entry:
648    %hdl = call i8* @f(i32 4)
649    %promise.addr.raw = call i8* @llvm.coro.promise(i8* %hdl, i32 4, i1 false)
650    %promise.addr = bitcast i8* %promise.addr.raw to i32*
651    %val0 = load i32, i32* %promise.addr
652    call void @print(i32 %val0)
653    call void @llvm.coro.resume(i8* %hdl)
654    %val1 = load i32, i32* %promise.addr
655    call void @print(i32 %val1)
656    call void @llvm.coro.resume(i8* %hdl)
657    %val2 = load i32, i32* %promise.addr
658    call void @print(i32 %val2)
659    call void @llvm.coro.destroy(i8* %hdl)
660    ret i32 0
661  }
662
663After example in this section is compiled, result of the compilation will be:
664
665.. code-block:: llvm
666
667  define i32 @main() {
668  entry:
669    tail call void @print(i32 4)
670    tail call void @print(i32 5)
671    tail call void @print(i32 6)
672    ret i32 0
673  }
674
675.. _final:
676.. _final suspend:
677
678Final Suspend
679-------------
680
681A coroutine author or a frontend may designate a particular suspend to be final,
682by setting the second argument of the `coro.suspend`_ intrinsic to `true`.
683Such a suspend point has two properties:
684
685* it is possible to check whether a suspended coroutine is at the final suspend
686  point via `coro.done`_ intrinsic;
687
688* a resumption of a coroutine stopped at the final suspend point leads to
689  undefined behavior. The only possible action for a coroutine at a final
690  suspend point is destroying it via `coro.destroy`_ intrinsic.
691
692From the user perspective, the final suspend point represents an idea of a
693coroutine reaching the end. From the compiler perspective, it is an optimization
694opportunity for reducing number of resume points (and therefore switch cases) in
695the resume function.
696
697The following is an example of a function that keeps resuming the coroutine
698until the final suspend point is reached after which point the coroutine is
699destroyed:
700
701.. code-block:: llvm
702
703  define i32 @main() {
704  entry:
705    %hdl = call i8* @f(i32 4)
706    br label %while
707  while:
708    call void @llvm.coro.resume(i8* %hdl)
709    %done = call i1 @llvm.coro.done(i8* %hdl)
710    br i1 %done, label %end, label %while
711  end:
712    call void @llvm.coro.destroy(i8* %hdl)
713    ret i32 0
714  }
715
716Usually, final suspend point is a frontend injected suspend point that does not
717correspond to any explicitly authored suspend point of the high level language.
718For example, for a Python generator that has only one suspend point:
719
720.. code-block:: python
721
722  def coroutine(n):
723    for i in range(n):
724      yield i
725
726Python frontend would inject two more suspend points, so that the actual code
727looks like this:
728
729.. code-block:: c
730
731  void* coroutine(int n) {
732    int current_value;
733    <designate current_value to be coroutine promise>
734    <SUSPEND> // injected suspend point, so that the coroutine starts suspended
735    for (int i = 0; i < n; ++i) {
736      current_value = i; <SUSPEND>; // corresponds to "yield i"
737    }
738    <SUSPEND final=true> // injected final suspend point
739  }
740
741and python iterator `__next__` would look like:
742
743.. code-block:: c++
744
745  int __next__(void* hdl) {
746    coro.resume(hdl);
747    if (coro.done(hdl)) throw StopIteration();
748    return *(int*)coro.promise(hdl, 4, false);
749  }
750
751
752Intrinsics
753==========
754
755Coroutine Manipulation Intrinsics
756---------------------------------
757
758Intrinsics described in this section are used to manipulate an existing
759coroutine. They can be used in any function which happen to have a pointer
760to a `coroutine frame`_ or a pointer to a `coroutine promise`_.
761
762.. _coro.destroy:
763
764'llvm.coro.destroy' Intrinsic
765^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
766
767Syntax:
768"""""""
769
770::
771
772      declare void @llvm.coro.destroy(i8* <handle>)
773
774Overview:
775"""""""""
776
777The '``llvm.coro.destroy``' intrinsic destroys a suspended
778switched-resume coroutine.
779
780Arguments:
781""""""""""
782
783The argument is a coroutine handle to a suspended coroutine.
784
785Semantics:
786""""""""""
787
788When possible, the `coro.destroy` intrinsic is replaced with a direct call to
789the coroutine destroy function. Otherwise it is replaced with an indirect call
790based on the function pointer for the destroy function stored in the coroutine
791frame. Destroying a coroutine that is not suspended leads to undefined behavior.
792
793.. _coro.resume:
794
795'llvm.coro.resume' Intrinsic
796^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
797
798::
799
800      declare void @llvm.coro.resume(i8* <handle>)
801
802Overview:
803"""""""""
804
805The '``llvm.coro.resume``' intrinsic resumes a suspended switched-resume coroutine.
806
807Arguments:
808""""""""""
809
810The argument is a handle to a suspended coroutine.
811
812Semantics:
813""""""""""
814
815When possible, the `coro.resume` intrinsic is replaced with a direct call to the
816coroutine resume function. Otherwise it is replaced with an indirect call based
817on the function pointer for the resume function stored in the coroutine frame.
818Resuming a coroutine that is not suspended leads to undefined behavior.
819
820.. _coro.done:
821
822'llvm.coro.done' Intrinsic
823^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
824
825::
826
827      declare i1 @llvm.coro.done(i8* <handle>)
828
829Overview:
830"""""""""
831
832The '``llvm.coro.done``' intrinsic checks whether a suspended
833switched-resume coroutine is at the final suspend point or not.
834
835Arguments:
836""""""""""
837
838The argument is a handle to a suspended coroutine.
839
840Semantics:
841""""""""""
842
843Using this intrinsic on a coroutine that does not have a `final suspend`_ point
844or on a coroutine that is not suspended leads to undefined behavior.
845
846.. _coro.promise:
847
848'llvm.coro.promise' Intrinsic
849^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
850
851::
852
853      declare i8* @llvm.coro.promise(i8* <ptr>, i32 <alignment>, i1 <from>)
854
855Overview:
856"""""""""
857
858The '``llvm.coro.promise``' intrinsic obtains a pointer to a
859`coroutine promise`_ given a switched-resume coroutine handle and vice versa.
860
861Arguments:
862""""""""""
863
864The first argument is a handle to a coroutine if `from` is false. Otherwise,
865it is a pointer to a coroutine promise.
866
867The second argument is an alignment requirements of the promise.
868If a frontend designated `%promise = alloca i32` as a promise, the alignment
869argument to `coro.promise` should be the alignment of `i32` on the target
870platform. If a frontend designated `%promise = alloca i32, align 16` as a
871promise, the alignment argument should be 16.
872This argument only accepts constants.
873
874The third argument is a boolean indicating a direction of the transformation.
875If `from` is true, the intrinsic returns a coroutine handle given a pointer
876to a promise. If `from` is false, the intrinsics return a pointer to a promise
877from a coroutine handle. This argument only accepts constants.
878
879Semantics:
880""""""""""
881
882Using this intrinsic on a coroutine that does not have a coroutine promise
883leads to undefined behavior. It is possible to read and modify coroutine
884promise of the coroutine which is currently executing. The coroutine author and
885a coroutine user are responsible to makes sure there is no data races.
886
887Example:
888""""""""
889
890.. code-block:: llvm
891
892  define i8* @f(i32 %n) {
893  entry:
894    %promise = alloca i32
895    %pv = bitcast i32* %promise to i8*
896    ; the second argument to coro.id points to the coroutine promise.
897    %id = call token @llvm.coro.id(i32 0, i8* %pv, i8* null, i8* null)
898    ...
899    %hdl = call noalias i8* @llvm.coro.begin(token %id, i8* %alloc)
900    ...
901    store i32 42, i32* %promise ; store something into the promise
902    ...
903    ret i8* %hdl
904  }
905
906  define i32 @main() {
907  entry:
908    %hdl = call i8* @f(i32 4) ; starts the coroutine and returns its handle
909    %promise.addr.raw = call i8* @llvm.coro.promise(i8* %hdl, i32 4, i1 false)
910    %promise.addr = bitcast i8* %promise.addr.raw to i32*
911    %val = load i32, i32* %promise.addr ; load a value from the promise
912    call void @print(i32 %val)
913    call void @llvm.coro.destroy(i8* %hdl)
914    ret i32 0
915  }
916
917.. _coroutine intrinsics:
918
919Coroutine Structure Intrinsics
920------------------------------
921Intrinsics described in this section are used within a coroutine to describe
922the coroutine structure. They should not be used outside of a coroutine.
923
924.. _coro.size:
925
926'llvm.coro.size' Intrinsic
927^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
928::
929
930    declare i32 @llvm.coro.size.i32()
931    declare i64 @llvm.coro.size.i64()
932
933Overview:
934"""""""""
935
936The '``llvm.coro.size``' intrinsic returns the number of bytes
937required to store a `coroutine frame`_.  This is only supported for
938switched-resume coroutines.
939
940Arguments:
941""""""""""
942
943None
944
945Semantics:
946""""""""""
947
948The `coro.size` intrinsic is lowered to a constant representing the size of
949the coroutine frame.
950
951.. _coro.align:
952
953'llvm.coro.align' Intrinsic
954^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
955::
956
957    declare i32 @llvm.coro.align.i32()
958    declare i64 @llvm.coro.align.i64()
959
960Overview:
961"""""""""
962
963The '``llvm.coro.align``' intrinsic returns the alignment of a `coroutine frame`_.
964This is only supported for switched-resume coroutines.
965
966Arguments:
967""""""""""
968
969None
970
971Semantics:
972""""""""""
973
974The `coro.align` intrinsic is lowered to a constant representing the alignment of
975the coroutine frame.
976
977.. _coro.begin:
978
979'llvm.coro.begin' Intrinsic
980^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
981::
982
983  declare i8* @llvm.coro.begin(token <id>, i8* <mem>)
984
985Overview:
986"""""""""
987
988The '``llvm.coro.begin``' intrinsic returns an address of the coroutine frame.
989
990Arguments:
991""""""""""
992
993The first argument is a token returned by a call to '``llvm.coro.id``'
994identifying the coroutine.
995
996The second argument is a pointer to a block of memory where coroutine frame
997will be stored if it is allocated dynamically.  This pointer is ignored
998for returned-continuation coroutines.
999
1000Semantics:
1001""""""""""
1002
1003Depending on the alignment requirements of the objects in the coroutine frame
1004and/or on the codegen compactness reasons the pointer returned from `coro.begin`
1005may be at offset to the `%mem` argument. (This could be beneficial if
1006instructions that express relative access to data can be more compactly encoded
1007with small positive and negative offsets).
1008
1009A frontend should emit exactly one `coro.begin` intrinsic per coroutine.
1010
1011.. _coro.free:
1012
1013'llvm.coro.free' Intrinsic
1014^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1015::
1016
1017  declare i8* @llvm.coro.free(token %id, i8* <frame>)
1018
1019Overview:
1020"""""""""
1021
1022The '``llvm.coro.free``' intrinsic returns a pointer to a block of memory where
1023coroutine frame is stored or `null` if this instance of a coroutine did not use
1024dynamically allocated memory for its coroutine frame.  This intrinsic is not
1025supported for returned-continuation coroutines.
1026
1027Arguments:
1028""""""""""
1029
1030The first argument is a token returned by a call to '``llvm.coro.id``'
1031identifying the coroutine.
1032
1033The second argument is a pointer to the coroutine frame. This should be the same
1034pointer that was returned by prior `coro.begin` call.
1035
1036Example (custom deallocation function):
1037"""""""""""""""""""""""""""""""""""""""
1038
1039.. code-block:: llvm
1040
1041  cleanup:
1042    %mem = call i8* @llvm.coro.free(token %id, i8* %frame)
1043    %mem_not_null = icmp ne i8* %mem, null
1044    br i1 %mem_not_null, label %if.then, label %if.end
1045  if.then:
1046    call void @CustomFree(i8* %mem)
1047    br label %if.end
1048  if.end:
1049    ret void
1050
1051Example (standard deallocation functions):
1052""""""""""""""""""""""""""""""""""""""""""
1053
1054.. code-block:: llvm
1055
1056  cleanup:
1057    %mem = call i8* @llvm.coro.free(token %id, i8* %frame)
1058    call void @free(i8* %mem)
1059    ret void
1060
1061.. _coro.alloc:
1062
1063'llvm.coro.alloc' Intrinsic
1064^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1065::
1066
1067  declare i1 @llvm.coro.alloc(token <id>)
1068
1069Overview:
1070"""""""""
1071
1072The '``llvm.coro.alloc``' intrinsic returns `true` if dynamic allocation is
1073required to obtain a memory for the coroutine frame and `false` otherwise.
1074This is not supported for returned-continuation coroutines.
1075
1076Arguments:
1077""""""""""
1078
1079The first argument is a token returned by a call to '``llvm.coro.id``'
1080identifying the coroutine.
1081
1082Semantics:
1083""""""""""
1084
1085A frontend should emit at most one `coro.alloc` intrinsic per coroutine.
1086The intrinsic is used to suppress dynamic allocation of the coroutine frame
1087when possible.
1088
1089Example:
1090""""""""
1091
1092.. code-block:: llvm
1093
1094  entry:
1095    %id = call token @llvm.coro.id(i32 0, i8* null, i8* null, i8* null)
1096    %dyn.alloc.required = call i1 @llvm.coro.alloc(token %id)
1097    br i1 %dyn.alloc.required, label %coro.alloc, label %coro.begin
1098
1099  coro.alloc:
1100    %frame.size = call i32 @llvm.coro.size()
1101    %alloc = call i8* @MyAlloc(i32 %frame.size)
1102    br label %coro.begin
1103
1104  coro.begin:
1105    %phi = phi i8* [ null, %entry ], [ %alloc, %coro.alloc ]
1106    %frame = call i8* @llvm.coro.begin(token %id, i8* %phi)
1107
1108.. _coro.noop:
1109
1110'llvm.coro.noop' Intrinsic
1111^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1112::
1113
1114  declare i8* @llvm.coro.noop()
1115
1116Overview:
1117"""""""""
1118
1119The '``llvm.coro.noop``' intrinsic returns an address of the coroutine frame of
1120a coroutine that does nothing when resumed or destroyed.
1121
1122Arguments:
1123""""""""""
1124
1125None
1126
1127Semantics:
1128""""""""""
1129
1130This intrinsic is lowered to refer to a private constant coroutine frame. The
1131resume and destroy handlers for this frame are empty functions that do nothing.
1132Note that in different translation units llvm.coro.noop may return different pointers.
1133
1134.. _coro.frame:
1135
1136'llvm.coro.frame' Intrinsic
1137^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1138::
1139
1140  declare i8* @llvm.coro.frame()
1141
1142Overview:
1143"""""""""
1144
1145The '``llvm.coro.frame``' intrinsic returns an address of the coroutine frame of
1146the enclosing coroutine.
1147
1148Arguments:
1149""""""""""
1150
1151None
1152
1153Semantics:
1154""""""""""
1155
1156This intrinsic is lowered to refer to the `coro.begin`_ instruction. This is
1157a frontend convenience intrinsic that makes it easier to refer to the
1158coroutine frame.
1159
1160.. _coro.id:
1161
1162'llvm.coro.id' Intrinsic
1163^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1164::
1165
1166  declare token @llvm.coro.id(i32 <align>, i8* <promise>, i8* <coroaddr>,
1167                                                          i8* <fnaddrs>)
1168
1169Overview:
1170"""""""""
1171
1172The '``llvm.coro.id``' intrinsic returns a token identifying a
1173switched-resume coroutine.
1174
1175Arguments:
1176""""""""""
1177
1178The first argument provides information on the alignment of the memory returned
1179by the allocation function and given to `coro.begin` by the first argument. If
1180this argument is 0, the memory is assumed to be aligned to 2 * sizeof(i8*).
1181This argument only accepts constants.
1182
1183The second argument, if not `null`, designates a particular alloca instruction
1184to be a `coroutine promise`_.
1185
1186The third argument is `null` coming out of the frontend. The CoroEarly pass sets
1187this argument to point to the function this coro.id belongs to.
1188
1189The fourth argument is `null` before coroutine is split, and later is replaced
1190to point to a private global constant array containing function pointers to
1191outlined resume and destroy parts of the coroutine.
1192
1193
1194Semantics:
1195""""""""""
1196
1197The purpose of this intrinsic is to tie together `coro.id`, `coro.alloc` and
1198`coro.begin` belonging to the same coroutine to prevent optimization passes from
1199duplicating any of these instructions unless entire body of the coroutine is
1200duplicated.
1201
1202A frontend should emit exactly one `coro.id` intrinsic per coroutine.
1203
1204A frontend should emit function attribute `presplitcoroutine` for the coroutine.
1205
1206.. _coro.id.async:
1207
1208'llvm.coro.id.async' Intrinsic
1209^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1210::
1211
1212  declare token @llvm.coro.id.async(i32 <context size>, i32 <align>,
1213                                    i8* <context arg>,
1214                                    i8* <async function pointer>)
1215
1216Overview:
1217"""""""""
1218
1219The '``llvm.coro.id.async``' intrinsic returns a token identifying an async coroutine.
1220
1221Arguments:
1222""""""""""
1223
1224The first argument provides the initial size of the `async context` as required
1225from the frontend. Lowering will add to this size the size required by the frame
1226storage and store that value to the `async function pointer`.
1227
1228The second argument, is the alignment guarantee of the memory of the
1229`async context`. The frontend guarantees that the memory will be aligned by this
1230value.
1231
1232The third argument is the `async context` argument in the current coroutine.
1233
1234The fourth argument is the address of the `async function pointer` struct.
1235Lowering will update the context size requirement in this struct by adding the
1236coroutine frame size requirement to the initial size requirement as specified by
1237the first argument of this intrinsic.
1238
1239
1240Semantics:
1241""""""""""
1242
1243A frontend should emit exactly one `coro.id.async` intrinsic per coroutine.
1244
1245A frontend should emit function attribute `presplitcoroutine` for the coroutine.
1246
1247.. _coro.id.retcon:
1248
1249'llvm.coro.id.retcon' Intrinsic
1250^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1251::
1252
1253  declare token @llvm.coro.id.retcon(i32 <size>, i32 <align>, i8* <buffer>,
1254                                     i8* <continuation prototype>,
1255                                     i8* <alloc>, i8* <dealloc>)
1256
1257Overview:
1258"""""""""
1259
1260The '``llvm.coro.id.retcon``' intrinsic returns a token identifying a
1261multiple-suspend returned-continuation coroutine.
1262
1263The 'result-type sequence' of the coroutine is defined as follows:
1264
1265- if the return type of the coroutine function is ``void``, it is the
1266  empty sequence;
1267
1268- if the return type of the coroutine function is a ``struct``, it is the
1269  element types of that ``struct`` in order;
1270
1271- otherwise, it is just the return type of the coroutine function.
1272
1273The first element of the result-type sequence must be a pointer type;
1274continuation functions will be coerced to this type.  The rest of
1275the sequence are the 'yield types', and any suspends in the coroutine
1276must take arguments of these types.
1277
1278Arguments:
1279""""""""""
1280
1281The first and second arguments are the expected size and alignment of
1282the buffer provided as the third argument.  They must be constant.
1283
1284The fourth argument must be a reference to a global function, called
1285the 'continuation prototype function'.  The type, calling convention,
1286and attributes of any continuation functions will be taken from this
1287declaration.  The return type of the prototype function must match the
1288return type of the current function.  The first parameter type must be
1289a pointer type.  The second parameter type must be an integer type;
1290it will be used only as a boolean flag.
1291
1292The fifth argument must be a reference to a global function that will
1293be used to allocate memory.  It may not fail, either by returning null
1294or throwing an exception.  It must take an integer and return a pointer.
1295
1296The sixth argument must be a reference to a global function that will
1297be used to deallocate memory.  It must take a pointer and return ``void``.
1298
1299Semantics:
1300""""""""""
1301
1302A frontend should emit function attribute `presplitcoroutine` for the coroutine.
1303
1304'llvm.coro.id.retcon.once' Intrinsic
1305^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1306::
1307
1308  declare token @llvm.coro.id.retcon.once(i32 <size>, i32 <align>, i8* <buffer>,
1309                                          i8* <prototype>,
1310                                          i8* <alloc>, i8* <dealloc>)
1311
1312Overview:
1313"""""""""
1314
1315The '``llvm.coro.id.retcon.once``' intrinsic returns a token identifying a
1316unique-suspend returned-continuation coroutine.
1317
1318Arguments:
1319""""""""""
1320
1321As for ``llvm.core.id.retcon``, except that the return type of the
1322continuation prototype must be `void` instead of matching the
1323coroutine's return type.
1324
1325Semantics:
1326""""""""""
1327
1328A frontend should emit function attribute `presplitcoroutine` for the coroutine.
1329
1330.. _coro.end:
1331
1332'llvm.coro.end' Intrinsic
1333^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1334::
1335
1336  declare i1 @llvm.coro.end(i8* <handle>, i1 <unwind>)
1337
1338Overview:
1339"""""""""
1340
1341The '``llvm.coro.end``' marks the point where execution of the resume part of
1342the coroutine should end and control should return to the caller.
1343
1344
1345Arguments:
1346""""""""""
1347
1348The first argument should refer to the coroutine handle of the enclosing
1349coroutine. A frontend is allowed to supply null as the first parameter, in this
1350case `coro-early` pass will replace the null with an appropriate coroutine
1351handle value.
1352
1353The second argument should be `true` if this coro.end is in the block that is
1354part of the unwind sequence leaving the coroutine body due to an exception and
1355`false` otherwise.
1356
1357Semantics:
1358""""""""""
1359The purpose of this intrinsic is to allow frontends to mark the cleanup and
1360other code that is only relevant during the initial invocation of the coroutine
1361and should not be present in resume and destroy parts.
1362
1363In returned-continuation lowering, ``llvm.coro.end`` fully destroys the
1364coroutine frame.  If the second argument is `false`, it also returns from
1365the coroutine with a null continuation pointer, and the next instruction
1366will be unreachable.  If the second argument is `true`, it falls through
1367so that the following logic can resume unwinding.  In a yield-once
1368coroutine, reaching a non-unwind ``llvm.coro.end`` without having first
1369reached a ``llvm.coro.suspend.retcon`` has undefined behavior.
1370
1371The remainder of this section describes the behavior under switched-resume
1372lowering.
1373
1374This intrinsic is lowered when a coroutine is split into
1375the start, resume and destroy parts. In the start part, it is a no-op,
1376in resume and destroy parts, it is replaced with `ret void` instruction and
1377the rest of the block containing `coro.end` instruction is discarded.
1378In landing pads it is replaced with an appropriate instruction to unwind to
1379caller. The handling of coro.end differs depending on whether the target is
1380using landingpad or WinEH exception model.
1381
1382For landingpad based exception model, it is expected that frontend uses the
1383`coro.end`_ intrinsic as follows:
1384
1385.. code-block:: llvm
1386
1387    ehcleanup:
1388      %InResumePart = call i1 @llvm.coro.end(i8* null, i1 true)
1389      br i1 %InResumePart, label %eh.resume, label %cleanup.cont
1390
1391    cleanup.cont:
1392      ; rest of the cleanup
1393
1394    eh.resume:
1395      %exn = load i8*, i8** %exn.slot, align 8
1396      %sel = load i32, i32* %ehselector.slot, align 4
1397      %lpad.val = insertvalue { i8*, i32 } undef, i8* %exn, 0
1398      %lpad.val29 = insertvalue { i8*, i32 } %lpad.val, i32 %sel, 1
1399      resume { i8*, i32 } %lpad.val29
1400
1401The `CoroSpit` pass replaces `coro.end` with ``True`` in the resume functions,
1402thus leading to immediate unwind to the caller, whereas in start function it
1403is replaced with ``False``, thus allowing to proceed to the rest of the cleanup
1404code that is only needed during initial invocation of the coroutine.
1405
1406For Windows Exception handling model, a frontend should attach a funclet bundle
1407referring to an enclosing cleanuppad as follows:
1408
1409.. code-block:: llvm
1410
1411    ehcleanup:
1412      %tok = cleanuppad within none []
1413      %unused = call i1 @llvm.coro.end(i8* null, i1 true) [ "funclet"(token %tok) ]
1414      cleanupret from %tok unwind label %RestOfTheCleanup
1415
1416The `CoroSplit` pass, if the funclet bundle is present, will insert
1417``cleanupret from %tok unwind to caller`` before
1418the `coro.end`_ intrinsic and will remove the rest of the block.
1419
1420In the unwind path (when the argument is `true`), `coro.end` will mark the coroutine
1421as done, making it undefined behavior to resume the coroutine again and causing
1422`llvm.coro.done` to return `true`.  This is not necessary in the normal path because
1423the coroutine will already be marked as done by the final suspend.
1424
1425The following table summarizes the handling of `coro.end`_ intrinsic.
1426
1427+--------------------------+------------------------+---------------------------------+
1428|                          | In Start Function      | In Resume/Destroy Functions     |
1429+--------------------------+------------------------+---------------------------------+
1430|unwind=false              | nothing                |``ret void``                     |
1431+------------+-------------+------------------------+---------------------------------+
1432|            | WinEH       | mark coroutine as done || ``cleanupret unwind to caller``|
1433|            |             |                        || mark coroutine done            |
1434|unwind=true +-------------+------------------------+---------------------------------+
1435|            | Landingpad  | mark coroutine as done | mark coroutine done             |
1436+------------+-------------+------------------------+---------------------------------+
1437
1438
1439'llvm.coro.end.async' Intrinsic
1440^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1441::
1442
1443  declare i1 @llvm.coro.end.async(i8* <handle>, i1 <unwind>, ...)
1444
1445Overview:
1446"""""""""
1447
1448The '``llvm.coro.end.async``' marks the point where execution of the resume part
1449of the coroutine should end and control should return to the caller. As part of
1450its variable tail arguments this instruction allows to specify a function and
1451the function's arguments that are to be tail called as the last action before
1452returning.
1453
1454
1455Arguments:
1456""""""""""
1457
1458The first argument should refer to the coroutine handle of the enclosing
1459coroutine. A frontend is allowed to supply null as the first parameter, in this
1460case `coro-early` pass will replace the null with an appropriate coroutine
1461handle value.
1462
1463The second argument should be `true` if this coro.end is in the block that is
1464part of the unwind sequence leaving the coroutine body due to an exception and
1465`false` otherwise.
1466
1467The third argument if present should specify a function to be called.
1468
1469If the third argument is present, the remaining arguments are the arguments to
1470the function call.
1471
1472.. code-block:: llvm
1473
1474  call i1 (i8*, i1, ...) @llvm.coro.end.async(
1475                           i8* %hdl, i1 0,
1476                           void (i8*, %async.task*, %async.actor*)* @must_tail_call_return,
1477                           i8* %ctxt, %async.task* %task, %async.actor* %actor)
1478  unreachable
1479
1480.. _coro.suspend:
1481.. _suspend points:
1482
1483'llvm.coro.suspend' Intrinsic
1484^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1485::
1486
1487  declare i8 @llvm.coro.suspend(token <save>, i1 <final>)
1488
1489Overview:
1490"""""""""
1491
1492The '``llvm.coro.suspend``' marks the point where execution of a
1493switched-resume coroutine is suspended and control is returned back
1494to the caller.  Conditional branches consuming the result of this
1495intrinsic lead to basic blocks where coroutine should proceed when
1496suspended (-1), resumed (0) or destroyed (1).
1497
1498Arguments:
1499""""""""""
1500
1501The first argument refers to a token of `coro.save` intrinsic that marks the
1502point when coroutine state is prepared for suspension. If `none` token is passed,
1503the intrinsic behaves as if there were a `coro.save` immediately preceding
1504the `coro.suspend` intrinsic.
1505
1506The second argument indicates whether this suspension point is `final`_.
1507The second argument only accepts constants. If more than one suspend point is
1508designated as final, the resume and destroy branches should lead to the same
1509basic blocks.
1510
1511Example (normal suspend point):
1512"""""""""""""""""""""""""""""""
1513
1514.. code-block:: llvm
1515
1516    %0 = call i8 @llvm.coro.suspend(token none, i1 false)
1517    switch i8 %0, label %suspend [i8 0, label %resume
1518                                  i8 1, label %cleanup]
1519
1520Example (final suspend point):
1521""""""""""""""""""""""""""""""
1522
1523.. code-block:: llvm
1524
1525  while.end:
1526    %s.final = call i8 @llvm.coro.suspend(token none, i1 true)
1527    switch i8 %s.final, label %suspend [i8 0, label %trap
1528                                        i8 1, label %cleanup]
1529  trap:
1530    call void @llvm.trap()
1531    unreachable
1532
1533Semantics:
1534""""""""""
1535
1536If a coroutine that was suspended at the suspend point marked by this intrinsic
1537is resumed via `coro.resume`_ the control will transfer to the basic block
1538of the 0-case. If it is resumed via `coro.destroy`_, it will proceed to the
1539basic block indicated by the 1-case. To suspend, coroutine proceed to the
1540default label.
1541
1542If suspend intrinsic is marked as final, it can consider the `true` branch
1543unreachable and can perform optimizations that can take advantage of that fact.
1544
1545.. _coro.save:
1546
1547'llvm.coro.save' Intrinsic
1548^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1549::
1550
1551  declare token @llvm.coro.save(i8* <handle>)
1552
1553Overview:
1554"""""""""
1555
1556The '``llvm.coro.save``' marks the point where a coroutine need to update its
1557state to prepare for resumption to be considered suspended (and thus eligible
1558for resumption). It is illegal to merge two '``llvm.coro.save``' calls unless their
1559'``llvm.coro.suspend``' users are also merged. So '``llvm.coro.save``' is currently
1560tagged with the `no_merge` function attribute.
1561
1562Arguments:
1563""""""""""
1564
1565The first argument points to a coroutine handle of the enclosing coroutine.
1566
1567Semantics:
1568""""""""""
1569
1570Whatever coroutine state changes are required to enable resumption of
1571the coroutine from the corresponding suspend point should be done at the point
1572of `coro.save` intrinsic.
1573
1574Example:
1575""""""""
1576
1577Separate save and suspend points are necessary when a coroutine is used to
1578represent an asynchronous control flow driven by callbacks representing
1579completions of asynchronous operations.
1580
1581In such a case, a coroutine should be ready for resumption prior to a call to
1582`async_op` function that may trigger resumption of a coroutine from the same or
1583a different thread possibly prior to `async_op` call returning control back
1584to the coroutine:
1585
1586.. code-block:: llvm
1587
1588    %save1 = call token @llvm.coro.save(i8* %hdl)
1589    call void @async_op1(i8* %hdl)
1590    %suspend1 = call i1 @llvm.coro.suspend(token %save1, i1 false)
1591    switch i8 %suspend1, label %suspend [i8 0, label %resume1
1592                                         i8 1, label %cleanup]
1593
1594.. _coro.suspend.async:
1595
1596'llvm.coro.suspend.async' Intrinsic
1597^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1598::
1599
1600  declare {i8*, i8*, i8*} @llvm.coro.suspend.async(
1601                             i8* <resume function>,
1602                             i8* <context projection function>,
1603                             ... <function to call>
1604                             ... <arguments to function>)
1605
1606Overview:
1607"""""""""
1608
1609The '``llvm.coro.suspend.async``' intrinsic marks the point where
1610execution of a async coroutine is suspended and control is passed to a callee.
1611
1612Arguments:
1613""""""""""
1614
1615The first argument should be the result of the `llvm.coro.async.resume` intrinsic.
1616Lowering will replace this intrinsic with the resume function for this suspend
1617point.
1618
1619The second argument is the `context projection function`. It should describe
1620how-to restore the `async context` in the continuation function from the first
1621argument of the continuation function. Its type is `i8* (i8*)`.
1622
1623The third argument is the function that models transfer to the callee at the
1624suspend point. It should take 3 arguments. Lowering will `musttail` call this
1625function.
1626
1627The fourth to six argument are the arguments for the third argument.
1628
1629Semantics:
1630""""""""""
1631
1632The result of the intrinsic are mapped to the arguments of the resume function.
1633Execution is suspended at this intrinsic and resumed when the resume function is
1634called.
1635
1636.. _coro.prepare.async:
1637
1638'llvm.coro.prepare.async' Intrinsic
1639^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1640::
1641
1642  declare i8* @llvm.coro.prepare.async(i8* <coroutine function>)
1643
1644Overview:
1645"""""""""
1646
1647The '``llvm.coro.prepare.async``' intrinsic is used to block inlining of the
1648async coroutine until after coroutine splitting.
1649
1650Arguments:
1651""""""""""
1652
1653The first argument should be an async coroutine of type `void (i8*, i8*, i8*)`.
1654Lowering will replace this intrinsic with its coroutine function argument.
1655
1656.. _coro.suspend.retcon:
1657
1658'llvm.coro.suspend.retcon' Intrinsic
1659^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1660::
1661
1662  declare i1 @llvm.coro.suspend.retcon(...)
1663
1664Overview:
1665"""""""""
1666
1667The '``llvm.coro.suspend.retcon``' intrinsic marks the point where
1668execution of a returned-continuation coroutine is suspended and control
1669is returned back to the caller.
1670
1671`llvm.coro.suspend.retcon`` does not support separate save points;
1672they are not useful when the continuation function is not locally
1673accessible.  That would be a more appropriate feature for a ``passcon``
1674lowering that is not yet implemented.
1675
1676Arguments:
1677""""""""""
1678
1679The types of the arguments must exactly match the yielded-types sequence
1680of the coroutine.  They will be turned into return values from the ramp
1681and continuation functions, along with the next continuation function.
1682
1683Semantics:
1684""""""""""
1685
1686The result of the intrinsic indicates whether the coroutine should resume
1687abnormally (non-zero).
1688
1689In a normal coroutine, it is undefined behavior if the coroutine executes
1690a call to ``llvm.coro.suspend.retcon`` after resuming abnormally.
1691
1692In a yield-once coroutine, it is undefined behavior if the coroutine
1693executes a call to ``llvm.coro.suspend.retcon`` after resuming in any way.
1694
1695Coroutine Transformation Passes
1696===============================
1697CoroEarly
1698---------
1699The pass CoroEarly lowers coroutine intrinsics that hide the details of the
1700structure of the coroutine frame, but, otherwise not needed to be preserved to
1701help later coroutine passes. This pass lowers `coro.frame`_, `coro.done`_,
1702and `coro.promise`_ intrinsics.
1703
1704.. _CoroSplit:
1705
1706CoroSplit
1707---------
1708The pass CoroSplit buides coroutine frame and outlines resume and destroy parts
1709into separate functions.
1710
1711CoroElide
1712---------
1713The pass CoroElide examines if the inlined coroutine is eligible for heap
1714allocation elision optimization. If so, it replaces
1715`coro.begin` intrinsic with an address of a coroutine frame placed on its caller
1716and replaces `coro.alloc` and `coro.free` intrinsics with `false` and `null`
1717respectively to remove the deallocation code.
1718This pass also replaces `coro.resume` and `coro.destroy` intrinsics with direct
1719calls to resume and destroy functions for a particular coroutine where possible.
1720
1721CoroCleanup
1722-----------
1723This pass runs late to lower all coroutine related intrinsics not replaced by
1724earlier passes.
1725
1726Areas Requiring Attention
1727=========================
1728#. When coro.suspend returns -1, the coroutine is suspended, and it's possible
1729   that the coroutine has already been destroyed (hence the frame has been freed).
1730   We cannot access anything on the frame on the suspend path.
1731   However there is nothing that prevents the compiler from moving instructions
1732   along that path (e.g. LICM), which can lead to use-after-free. At the moment
1733   we disabled LICM for loops that have coro.suspend, but the general problem still
1734   exists and requires a general solution.
1735
1736#. Take advantage of the lifetime intrinsics for the data that goes into the
1737   coroutine frame. Leave lifetime intrinsics as is for the data that stays in
1738   allocas.
1739
1740#. The CoroElide optimization pass relies on coroutine ramp function to be
1741   inlined. It would be beneficial to split the ramp function further to
1742   increase the chance that it will get inlined into its caller.
1743
1744#. Design a convention that would make it possible to apply coroutine heap
1745   elision optimization across ABI boundaries.
1746
1747#. Cannot handle coroutines with `inalloca` parameters (used in x86 on Windows).
1748
1749#. Alignment is ignored by coro.begin and coro.free intrinsics.
1750
1751#. Make required changes to make sure that coroutine optimizations work with
1752   LTO.
1753
1754#. More tests, more tests, more tests
1755