Search code examples
compiler-constructionregister-allocation

How to store multiple variables with only a finite amount of registers?


I wrote a simple virtual machine with instructions to manipulate a stack, store stack values into registers, load register values into the stack, move values from register to register and set register values... I'm trying to write a really simple language that compiles to this VM bytecode, I haven't done any of the instructions to jump around from address to address, but I feel the VM has enough to generate bytecode for storing variable values.

The virtual machine has 7 registers: a, b, x, y, z, j, and i. However, if I had 12 variables containing simple integers, how would I store each of them in a register?

I've read up on this before, and a lot of the time people talk about register allocation - I have no idea how to implement that in code. I'm not sure how I would start, and register allocators seem to be pretty complex.

Are there any (really) simple register allocators I can look at, or try to implement? Can anyone dumb down the explanation for me so I can attempt to implement one?

Thanks.


Solution

  • You store variables on the stack (or static storage for globals), not in registers. At least, mostly; an optimizer might chose to keep one or two frequently used variables in registers, but at this point I wouldn't worry about that if I were you.

    Registers are used to hold intermediate results during computations. If the computation needs lots of intermediate values, you can run out of variables in which case you'll need to "spill" some value into a stack-allocated temporary.

    Reordering computations in order to minimize the number of temooraries needed is hard. I'd suggest starting with a simple non-optimal strategy.

    Seven registers isn't many. Why do you choose such a limiting VM design? Perhaps you should rethink.