Search code examples
cassemblygotodispatchvm-implementation

In C ensure that the number of assembly instructions is fixed for multiple sections of code


In a virtual machine I'm writing, I want to be able to dispatch commands in a manner similar to the following pseudo code.

add: reg[memory[pc+1]] =  reg[memory[pc+1]] + reg[memory[pc+2]]; pc += 2; goto done;
sub: reg[memory[pc+1]] =  reg[memory[pc+1]] - reg[memory[pc+2]]; pc += 2; goto done;
cmp: /* Would take more space than simply x = x + y; */ goto done;

for(int pc = 0; memory[pc] != END; pc++) {
    goto currentPositionInMemorySomehow + (memory[pc] * lengthOfInstruction);
    done:
}

Where memory is an array containing the bytecode, and pc a program counter. To do this however requires that each of these positions we jump to has the exact same number of instructions before the next block. Dropping down to assembly is not an option, unless there is a wonderful platform agnostic assembly code, which allows for one to take the same code and compile to Linux, Mac, and Windows. Regardless of the processor each is sitting on top of. Any and all help will be much appreciated.


Solution

  • While I don't know of a way to achieve exactly what you want (and the only compiler I know that allows computed jumps is gcc), I suggest you simply use a switch, which most decent optimizing compilers will transform into either a jump table, or a computed jump, handling instruction alignment correctly in a way appropriate for your platform.