GameBoy color emulator opcodes automation

cemulationgameboyopcodes

I'm writting a GameBoy color emulator in C, just to introduce myself into this world, it is interpreted, nothing of dynamic or static recompilation 😛

Now I'm right in the tedious task of implementing all the CPU opcodes in C code, I have to write all these: http://www.pastraiser.com/cpu/gameboy/gameboy_opcodes.html and I don't want to take them from another emulator.

The question is, is there some way to automate the opcodes writting? Maybe it's a silly question and it will have a silly answer, but I want to work as less as possible. 🙂

Best Answer

I've done this kind of thing before and the way I did it was with macros, but doing it that way you end up with a whole lot of code duplication that overflows the cpu cache and makes things slow. If I were to do it today, I'd get rid of the whole "opcode switch/jumptable" idiom except for obscure/rare opcodes, and write common branchless code for all the normal arithmetic/logical ops using some small lookup tables based on the opcode number. Think something like:

operand1 = regs[operand1_table[opcode]];
operand2 = regs[operand2_table[opcode]];
res[ADD] = operand1+operand2;
res[SUB] = operand1-operand2;
res[OR] = operand1|operand2;
/* ... */
regs[dest_table[opcode]] = res[optype_table[opcode]];

This code is of course over-simplified, but can be expanded to deal with memory operands, etc. Also note that a jump instruction is just an add instruction with the program counter as one of its operands.

For CISC archs like Z80 (or the GB variant thereof) or x86, you're also going to have to deal with condition code flags. However they can be done as a second set of computations like the res[...] = ...; ones above.

Related Topic