Coroutine LLVM IR Intrinsics

I have trouble working with the new coroutines intrinsics. For example, I cannot get the example in the official docs to work [1].

What is the intended way of compiling the example to a binary?

Both the following C file and the corresponding manually written LLVM IR produce fatal errors in the toolchain.

=== C ===

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>

void f(int n) {
__builtin_coro_id(32, 0, 0, 0);
size_t size = __builtin_coro_size();
alloc = malloc(size);
int8_t* hdl = __builtin_coro_begin(alloc);
for(;:wink: {
printf(“n: %d\n”, n++);
int8_t cleanup = __builtin_coro_suspend(0);
switch (cleanup) {
case 0: continue;
case 1: goto CLEANUP;
default: goto SUSPEND;
__builtin_coro_end(hdl, 0);
return hdl;

int main() {
void* hdl = f(4);
return 0;

=== LLVM IR (v7) ===

define i32 @main() {
%hdl = call i8* @f(i32 4)
call void @llvm.coro.resume(i8* %hdl)
call void @llvm.coro.resume(i8* %hdl)
call void @llvm.coro.destroy(i8* %hdl)
ret i32 0

define i8* @f(i32 %n) {
%id = call token 0, i8* null, i8* null, i8* null)
%size = call i32 @llvm.coro.size.i32()
%alloc = call i8* @malloc(i32 %size)
%hdl = call noalias i8* @llvm.coro.begin(token %id, i8* %alloc)
br label %loop
%n.val = phi i32 [ %n, %entry ], [ %inc, %loop ]
%inc = mul nsw i32 %n.val, %n.val
call void @print(i32 %n.val)
%0 = call i8 @llvm.coro.suspend(token none, i1 false)
switch i8 %0, label %suspend [i8 0, label %loop i8 1, label %cleanup]
%mem = call i8* %id, i8* %hdl)
br label %suspend
%unused = call i1 @llvm.coro.end(i8* %hdl, i1 false)
ret i8* %hdl

declare i8*, i8*)
declare i32 @llvm.coro.size.i32()
declare i8 @llvm.coro.suspend(token, i1)
declare void @llvm.coro.resume(i8*)
declare void @llvm.coro.destroy(i8*)

declare token, i8*, i8*, i8*)
declare i1 @llvm.coro.alloc(token)
declare i8* @llvm.coro.begin(token, i8*)
declare i1 @llvm.coro.end(i8*, i1)

declare noalias i8* @malloc(i32)
declare void @print(i32)
declare void @free(i8*)

I compiled the former with clang -fcoroutines-ts gen.c, whereas the latter was transformed with opt -enable-coroutines -S gen_manual.ll -coro-early -coro-split -o opt.ll followed by an llc -filetype=obj.

In both cases, I used the most recent LLVM 7.0 release, but got fatal errors, e.g., “error in backend: Cannot select: intrinsic %llvm.coro.begin”.

Is there a complete end-to-end example that illustrates the compilation of a small coroutine example written in LLVM IR to a binary?

Many thanks in advance!

  • Alex