3 ms·
Yes, the main difference is the instruction set. One common way to design a stack-based instruction set is to refer to the local variables using stack offsets,
by ufo 6y ago
Yes, the main difference is the instruction set.
One common way to design a stack-based instruction set is to refer to the local variables using stack offsets, just as in a register-based instruction set. The operation for reading a local variable makes a copy of the stack slot at the given offset and pushes it into the top of the stack, where it may be used as the input for subsequent operations. For example, to implement "X = X + Y" it might use the following code:
LOAD 0 (pushes the contents of X to the stack)
LOAD 1 (pushes the contents of Y to the stack)
ADD (pops two values and pushes the result)
STORE 0 (pops one value, and stores it into X)
Meanwhile, in a register-based VM the ADD operation manipulates the relevant stack slots directly:
ADD R0 R0 R1 (compute R0 + R1 and store in R0)
> Instruction set is simpler but at the cost of requiring additional operations.
Well put. This is one of the key differences between a stack VM and a register VM. In register VM the instructions are larger, because they need to specify all their arguments. However, a stack VM may need to generate more instructions to fiddle with the top of the stack.
If you want to read more, one good example of a stack-based VM is the one in the Crafting Interpreters book. For a good example of a register based VM my suggestion would be the paper about the implementation of Lua (section 7 in particular).
https://craftinginterpreters.com/local-variables.html https://craftinginterpreters.com/local-variables.html
http://www.jucs.org/jucs_11_7/the_implementation_of_lua http://www.jucs.org/jucs_11_7/the_implementation_of_lua