wren-lang / wren

The Wren Programming Language. Wren is a small, fast, class-based concurrent scripting language.
http://wren.io
MIT License
6.9k stars 552 forks source link

Why a stack machine instead of a register machine? #82

Closed edsrzf closed 9 years ago

edsrzf commented 9 years ago

Why is Wren's VM a stack machine and not a register machine? The tradeoffs are pretty well known: stack VMs are simpler and usually generate smaller bytecode, while register VMs are a little tougher to generate code for and generate fewer instructions (making them faster in general).

Lua provides a good reference for code generation and interpretation for a register VM.

munificent commented 9 years ago

I've implemented a register-based VM before. I think it's a cool model, but I don't think it would bring much benefit for Wren. It is a bit more difficult to compile, and I'm trying to keep Wren's implementation as simple as possible.

In return for that complexity, you can generate fewer instructions. However, I don't think Wren would be able to take advantage of that. In Lua, a statement like:

a = b + c

Can compile to a single instruction: an ADD with operands from local registers a and b that stores into local register c. Wren doesn't currently have any dedicated instructions for arithmetic. Operators are just regular method calls and can call user-defined procedures.

The calling convention for methods requires all of their parameters to be at the stop of the caller's stack so that they can become bottom of the callee's stack frame window. So, to call + in Wren, we still have to push the arguments on top of the stack. Likewise, the method calling convention places the return value where the first argument was, so we'd have to move it back down to the destination slot after the call.

It may be worth having dedicated instructions for arithmetic that special case the built-in types before falling back to user-defined operator methods (which I assume is what Lua does since they added operator overloading late in the language's development). If that happens, it may be possible to switch to register-based.

But I'm not convinced it would be an actual performance win. A lot of details of the language affect whether a register-based VM is better. For example, assignments are statements in Lua but expressions in Wren, which would make them harder to compile to efficient register-based code.

edsrzf commented 9 years ago

Thank you for the very detailed response!

I might still play with the idea once the language has stabilized a bit. I'll share my results if I do, but won't have any expectation of getting anything merged.

kmarekspartz commented 9 years ago

Perhaps some of that could go into the Q&A page...

munificent commented 9 years ago

Good idea! Done: http://munificent.github.io/wren/qa.html#why-is-the-vm-stack-based-instead-of-register-based