57 points · by jlongster · 14y ago · 29 comments
The punchline is that there are several things you can do to improve your performance: first, a number of more efficient CPS algorithms have been developed over the last 10+ years. I currently use one presented by Danvy in the 2001 paper "A First-Order One-Pass CPS algorithm" linked here: www.brics.dk/RS/01/49/BRICS-RS-01-49.pdf . It's major focus is to distinguish between "serious" and "trivial" expressions, because the serious ones are the only ones that actually require a new continuation to be generated. This saves a lot of administrative redexes that can kill your performance.
Some other CPS-related avenues you may want to look into include "The Essence of Compiling with Continuations" (co-authored by one of my heroes, Amr Sabry) which formalizes A-normal form, an alternative to compiling with continuations that was ground-breaking in pointing out the number of unnecessary redexes introduced by traditional CPS algorithms. There's also a more recent paper by Andrew Kennedy at MS Research called "Compiling with Continuations, Continued" which I admittedly have not gotten a chance to dig into yet. It's stated goal is to revive some of the ideas of the original "Compiling with Continuations" by Andrew Appel.
Of course with the method you present, continuation application isn't your only performance hit. If you're using a trampoline, you're undoubtedly thunkifying the code to delimit the bounces on the trampoline. I also need to do some work in this area, but I'm familiar with at least one paper on doing minimal thunkification from 1993 and linked here: http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.158.... .
I'm a big fan of both CPS+trampolining and the work like ClojureScript that's bringing efficient Lisp programming to the JavaScript arena. I'm hoping to get a chance to look over the work that you've done with Outlet and I'd love to chat with you about it. It sounds like we share quite similar interests.
Thanks for the papers, I'll look at them. I'm worried about spending a lot of time on this, only to realize that the performance hit is simply too large. I want this for debugging, and what I really want to try is to write a web-based byte code VM and compile Outlet to it. But the same concern exists there: can I get it fast enough to run sufficiently?
I'm leaning more towards the CPS route though. First of all, there's tons of research going into it. Secondly, I lose all the benefits of JIT-ed Javascript if I run it in a VM. There's actually a much higher chance that I'll be able to get CPS-ed code running fast than compiled byte code.
I admit that my current implementation is naive, and yes, the trampolines require even more thunks.
I'd love to talk, I'm very interested in this as well. How far has clojure-tco come? What's the performance hit, and how do you return code to the trampoline? I will look at your code soon, and be lurking around #clojure as jlongster.
I noticed that somebody commented about allocation being a big source of slow down. Someone suggested to me that if you have low-level enough access to your implementation, you can reuse the thunk after each invocation. It took me a while to get my head around it, and I'm not even sure it can be done in Clojure TCO. If you can change the contents of a underlying closure data structure, then you only have to allocate one thunk. I suspect that you're taking advantage of JavaScript's closures, so you may not have any more luck with it than me.
If you're interested, one of my next goals now that I'm done with school is to start writing about the algorithms that Clojure TCO uses. I want to write something fairly accessible that describes the Danvy CPS algorithm.
That's amazing!
"Someone suggested to me that if you have low-level enough access to your implementation, you can reuse the thunk after each invocation ..."
Yep, I thought of that when I was looking at the generated js code. I'm think of out of luck as well. However, as I mentioned at the end of my article, I think you should be able to hoist all the functions into top-level forms and pass around an environment. This way, functions are statically allocated once, and the performance hit of passing around environments can't be nearly as great as function allocation.
The Dybvig "Three implementations of scheme" paper presents a really nice VM and Norvig's PAIP book presents a nice simple compiler for Scheme. Those are the two main sources that I've used for my simple compiler.
Edit: Also...
> I lose all the benefits of JIT-ed Javascript if I run it in a VM.
But if you are using CPS, then your JS functions are going to be really small and the JIT won't have much to work with, right? It's not clear to me that the JIT will be more effective working on CPS JS given that you want to have fine-grained continuations for debugging.
I'm not sure how well the JIT works with CPS-ed code. There's a Firefox addon to inspect the JIT which we could use to find out (https://addons.mozilla.org/en-US/firefox/addon/jit-inspector...). It's possible we could optimize loops in a way that is more JIT-friendly.
More research is needed!
Depending on why you want CPS, you can apply the following strategy:
Keep all code in direct style. For each function, designate a special return token CaptureCont that indicates that the continuation should be captured. The source of this token will be callcc. After each function call you check if it returned a token, and if so, extend it with the continuation for the rest of the computation. Then on the main() function of your program, pass the continuation to the appropriate place. This strategy avoids most overhead in the common case: one if instanceof check plus a branch per function call.
For example, take this function:
def foo(x,a):
y = g(x)
return y+a
Transform to: class CaptureCont:
member target # the function that we will pass the continuation to once we finish constructing it
member partialCont # the part of the continuation captured so far
def extend(f):
newCC = new CaptureCont()
newCC.target = target
newCC.partialCont = lambda v: f(partialCont(v))
def invoke():
target(partialCont)
def foo(x):
y = g(x)
if y is CaptureCont:
# now y is the part of the continuation captured so far
# our job is to extend it with our stack frame
# and then return it so that the callee can build it up further
return y.extend(lambda y2: y2+a)
else:
return y+a
Instead of just invoking main(), do this: loop:
v = main()
if v is CaptureCont: v.invoke()
else: exit(v) # well I guess this is not necessary in JS
Eventually the CaptureCont will bubble up to main, and at that point main will invoke it so that the continuation is passed to the right target.Callcc:
def callcc(f):
cc = new CaptureCont()
cc.target = f
cc.partialCont = lambda x: x
return cc
There are various optimizations that can be applied (like eliding the capture code for functions that you statically know don't call callcc and thus will never return CaptureCont), and this approach also (trivially) works for the more general delimited continuations. As described capturing the continuation is O(n) in the size of the stack. You can make it amortized O(1) with some more trickery by lazily rebuilding the stack, but the current approach is already blazingly fast in the case of no continuation capture. I'm really tired now, so there are probably lots of errors in the above description, so tread with caution. I don't know if this approach is new or not, but it probably isn't given that it's a fairly obvious approach to capture the stack. Does anybody know what it's called? Then the OP can find a better description.The reason I want to do CPS is for debugging in the browser. I want to be able to control the stack, so when a breakpoint hits I can pause everything and step through the code. The browser is non-blocking so I need explicit control of the stack.
You're method is neat. My language doesn't support continuations, so I don't need them until I hit the debugging mode. You've made me curious if I can compile out both CPS-ed and non-CPS-ed versions of the code and somehow switch between them.
You might be able to get away with compiling a runtime environment slightly more complex than your simple trampoline loop that does the same thing, building a chain of JavaScript closures to represent continuations without actually CPSing the rest of the program. Continuation calls would then show up on the JavaScript stack and allow you to step through them.
Outlet is a compiler which compiles straight to js, no interpretation.
However, if we do that globally, we're back where we started, right? I mean, the allocation rate of continuation closures will be on the same level as standard CPS.
> Another way if you're willing to take a 2x code explosion hit is to compile each function twice: ...
The idea about compiling functions twice and using a dynamic switch on function entry seems to presume that it can be determined at function call whether a continuation will be captured somewhere within the call and I don't see how you'd do that.
Alternatively, you could introduce a static analysis that identifies functions that provably are not capable of continuation capture and compile only those in direct style. I suppose you could even do the analysis on an expression-level. Of course, Lisp dialects are not particularly amenable to static analysis so it may be hard to get much of a benefit in this way.
However, even if you deal with the code-size issues, I think you are left with a technique for optimizing code for a language that must support continuation capture but you are not left with code that is easy to debug. Every function or block that is compiled in direct style will be impossible to step through or dynamically interrupt.
All criticism aside, thanks for posting the idea! I had never seen a technique like that before.
2) In our CPS-based intermediate representation, we rely heavily on control flow analysis (CFA) to enable many classic compiler optimizations (inlining, untupling, unreachable code elimination, cases where only one member of a datatype is constructed/destructed, etc.).
CPS is a great transformation and makes for a wonderful IR, but you have to pay a decent static analysis cost before you will be able to perform many classic optimizations and get great performance. That said, we've done pretty well (http://manticore.cs.uchicago.edu ), but it's taken years of development. I'd also like to second cjfrisz's pointer to Appel's green book. It's a fabulous introduction to compiling in a CPS-style IR, though you'll find you still have a fairly large performance gap if you don't implement the CFA-based versions of them.
Fascinating stuff.
I had an idea but never got around to implement it. Is to use the new es-harmony generators to pause execution in non-cps-ed version of the code. I'm happy to further elaborate on that if you're interested.
biwascheme> (call-with-current-continuation (lambda (k) (k 12)))
=> 12
It's based on Dybvig's "Three Implementation Models for Scheme" http://www.cs.unm.edu/~williams/cs491/three-imp.pdf