[LLVMdev] Efficient implementation of closures?

Talin viridia at gmail.com
Sat Dec 27 21:53:55 PST 2008


A somewhat random question: I'm wondering if there's any kind of trick 
in LLVM that would allow me to implement closures efficiently.

We can assume that a closure function has a hidden parameter which 
points to its environment, that is, the values of the variables which 
were in scope at the point where the closure function was defined.

The problem comes when mixing closure and non-closure functions, because 
closure functions have a different calling protocol. Suppose I have a 
function pointer. This function pointer can either point to a regular 
function, which does not take the hidden parameter; or it can point to a 
closure function, which does. The problem is that the call site cannot 
support two incompatible calling conventions.

I can think of two solutions to this problem, but both entail 
considerable loss of efficiency: The first solution is to have every 
function, closure or not, have the hidden parameter; For non-closure 
functions the value of the parameter is simply ignored. The downside is 
that now every function has to pay the cost of an extra parameter.

The second solution is that when calling via a pointer, we always call 
with the closure protocol, i.e. we include the hidden parameter. 
However, when taking the address of a non-closure function, we actually 
point to a stub function which strips off the hidden parameter before 
calling the real function. This solution is better in that it means that 
the extra cost is only paid when calling a non-closure function via a 
pointer. However, it means that we essentially pay the cost of 
marshalling the calling arguments twice.

-- Talin




More information about the llvm-dev mailing list