Dispatch bytecode with a switch inside a loop
Write the simplest bytecode interpreter in C, a for loop around a switch on the opcode, and see where its single indirect branch limits you.
The baseline bytecode interpreter is a loop that reads an opcode and switches on it. Every other dispatch technique is a variation on this, so it is worth writing once, correctly.
#include <stdint.h>
#include <stdio.h>
enum { OP_PUSH, OP_ADD, OP_PRINT, OP_HALT };
void run(const uint8_t *ip) {
int64_t stack[64], *sp = stack;
for (;;) {
switch (*ip++) {
case OP_PUSH: *sp++ = *ip++; break;
case OP_ADD: sp--; sp[-1] += sp[0]; break;
case OP_PRINT: printf("%lld\n", (long long)sp[-1]); break;
case OP_HALT: return;
default: fprintf(stderr, "bad opcode\n"); return;
}
}
}
int main(void) {
const uint8_t prog[] = { OP_PUSH, 2, OP_PUSH, 3, OP_ADD, OP_PRINT, OP_HALT };
run(prog);
}5The compiler turns the switch into a bounds check plus one indirect jump through a table, shared by every opcode. That is the weakness: the CPU's branch predictor sees a single jump site with a different target each time, so on older cores it mispredicts often. Compilers can duplicate that jump into each handler on their own, but you cannot count on it. The next steps are computed goto and tail calls. Keep the default arm; it is your only defence against a corrupt program, and without it an out-of-range opcode is undefined behaviour in the table lookup. The stack here has no overflow check, so a real VM must add one.