Google Summer of Code 2013/cs648/Anatomy of a Continuation

From QEMU

Continuation

A continuation is a representation of the control state of the program. It contains the call stack of the current thread of execution along with the "stack variables" (in CPC they are stored on the heap) and any return variables.

CPC Continuation Data Structure

struct cpc_continuation contains the continuation stack. It has a length attribute which is the effective length of the stack and a size attribute which is the allocated size of the stack (it must be reallocated if pushing to it would exceed this size.

If ecpc mode is enabled, struct cpc_continuation contains a pointer to the retval of the current function, otherwise this is stored on the stack itself.

The stack contains continuation functions, which are pushed or popped off as execution continues.

Functions

cpc_continuation_push

cpc_continuation_push pushes a function f onto the top of the stack, resizing it if necessary.

cpc_invoke_continuation

cpc_invoke_continuation pops the top function off of the continuation stack and then calls it, with the continuation as its argument. The function is then able to read and write from its stack variables and to its return value on the continuation stack.

cpc_yield

cpc_yield appends the current continuation thread to the end of the ready queue and yields execution to another thread.

cpc_spawn

cpc_prim_spawn takes a new continuation cont and a continuation context context and schedules the continuation to run in the context by appending it to the ready queue, either immediately, if the context is running or, if it is detached, then it schedules it to be appended later.

cpc_continuation_patch

cpc_continuation_patch writes the return value of the returning function on the continuation stack into the stack, either using some pointer magic to calculate the correct alignment into the stack to store the return value or writing it to the pointer specified in the continuation if ecpc mode is enabled.