The Register-Based Virtual Machine

Learn why PyLua's register-based virtual machine is significantly faster than traditional stack-based VMs, and how the bytecode execution engine in src/runtime/lvm.c achieves maximum throughput.

1. Register-Based vs. Stack-Based Architecture

Most bytecode virtual machines (such as the Java Virtual Machine or Python's CPython) are stack-based. When computing an expression like c = a + b, a stack machine must execute four separate instructions:

Stack-Based VM (CPython / JVM):
1. PUSH a       (pushes operand 'a' onto the stack)
2. PUSH b       (pushes operand 'b' onto the stack)
3. ADD          (pops both operands, adds them, pushes result)
4. STORE c      (pops result from stack into variable 'c')
Total: 4 VM dispatch cycles, 4 stack pointer adjustments!

PyLua Register-Based VM:
1. OP_ADD  R(c), R(a), R(b)
Total: 1 VM dispatch cycle! Operands are addressed directly in registers.

By directly addressing local variables and temporary values as virtual registers inside the current stack frame, PyLua reduces instruction dispatch overhead by up to 50%.

2. Sliding Register Window & Call Stacks

In PyLua, virtual "registers" are not hardware CPU registers; they are slots inside the thread's execution stack (an array of TValue). Each active function invocation has a call frame (CallInfo):

Thread Stack (lua_State.stack)
┌──────────────────────────────────────────────┐
│  Caller Frame: R(0), R(1), R(2)...          │
├──────────────────────────────────────────────┤
│  Function Value (LClosure)                  │ ──▶ ci->func
├──────────────────────────────────────────────┤
│  Register Window for current function:       │
│    R(0): Param 1                            │
│    R(1): Param 2                            │
│    R(2): Local variable 'x'                 │
│    R(3): Temporary expression register      │
│    R(4): Temporary expression register      │
├──────────────────────────────────────────────┤
│  Callee Frame (when calling nested func)...  │ ──▶ ci->next
└──────────────────────────────────────────────┘

Register indexing is zero-based and relative to ci->func + 1. When a function executes OP_MOVE 3, 1, it simply copies stack[base + 1] to stack[base + 3].

3. The Main Execution Loop (`luaV_execute`)

The core interpreter loop in src/runtime/lvm.c fetches, decodes, and executes 32-bit instructions. On modern compilers (GCC/Clang), it utilizes computed gotos (direct threading) to jump directly from the end of one opcode handler to the start of the next, avoiding branch prediction penalties from a giant switch statement.

vm_loop_concept.c
/* Conceptual execution loop in lvm.c */
while (1) {
    Instruction i = *(pc++);
    OpCode op = GET_OPCODE(i);
    switch (op) {
        case OP_MOVE: {
            setobjs2s(L, ra, RB(i));
            break;
        }
        case OP_ADD: {
            lua_Number nb, nc;
            if (tonumberns(v2, nb) && tonumberns(v3, nc)) {
                setfltvalue(s2v(ra), luai_numadd(L, nb, nc));
            }
            break;
        }
        case OP_CALL: {
            /* Execute function call */
            break;
        }
    }
}

4. Interactive Live Visual Bytecode & CPU Debugger (--debug)

PyLua includes an integrated x64dbg / OllyDbg-style live visual CPU and bytecode debugger. It allows developers to inspect instruction-level VM execution in real time with graphical disassembly, branching flow arrows, live register tracking, and breakpoints.

Terminal
# Launch any script inside the live CPU/bytecode debugger:
pylua --debug my_script.lua

Debugger Interface Elements

  • Disassembly Table: Displays the function's bytecode instructions with hex addresses (0000), 32-bit machine bytes (e.g. 43 00 80 00), decoded opcode and operands (OP_LOADK R(0), K(1)), and evaluated comments.
  • Visual Jump Arrows: Colored branch lines connect jump instructions (OP_JMP, OP_FORLOOP) directly to destination target addresses with directional arrowheads, highlighting loop and branch structures.
  • Execution Pointer: A bright indicator (▸ PC) highlights the currently paused or active instruction.
  • Virtual Registers Panel: Real-time inspection of R[0] .. R[N] with live type tags (integer, float, string, table) and contents.
  • Constants Pool & Upvalues: Full visibility into string/number constants in K[0] .. K[M] and closure upvalues.
  • Multi-Tab Workspace: Switch between [CPU / Disasm], [Log / Console], [Breakpoints], [Memory / Globals], and [Source Script].

Keyboard & Mouse Controls

ShortcutActionDescription
F5 / SpaceRun / ContinueResumes script execution at full speed until the next breakpoint or pause.
F7Step IntoExecutes exactly one bytecode instruction and pauses at the next.
F8Step OverSteps over function calls or advances one instruction without descending into subroutines.
F2 / Click BPToggle BreakpointSets or clears an instruction breakpoint on the selected PC address.
PPausePauses a running script immediately.
1 .. 5Switch TabsQuickly switch between CPU, Log, Breakpoints, Globals, and Source views.
Mouse WheelScrollSmoothly scrolls through disassembly, registers, console logs, or script source lines.