4.4 Bytecode and Virtual Machines

INTERPRETERSTATUS: DEVELOPINGLEVEL: INTERMEDIATEREVIEWED: 2026-11-18

A bytecode virtual machine trades complexity for speed. Instead of walking a tree, the machine executes a flat sequence of instructions. The instructions are simpler and the dispatch loop is tighter.

4.4.1 Motivation

Tree-walking is slow because the interpreter must examine and dispatch on every node. Bytecode is a lower-level intermediate code. You compile the tree to a flat instruction sequence once. The sequence is designed for the machine, not for humans to read.

The instructions are simple: push a value, add two values, jump if false, return from a function. The interpreter becomes a loop that fetches an instruction, increments a program counter, and executes the instruction. The dispatch is tight and the loop is hot.

The trade-off is a compilation step. That step happens once, and the bytecode then runs many times, which spreads its cost.

4.4.2 Instruction set design

A bytecode instruction set is a miniature assembly language. Instructions have an opcode and operands. The operands can be register numbers, constant pool indices, or stack offsets.

Simple operations are single instructions:

GETVAR 1     # push variable 1 onto the stack
LDCONST 5    # push constant 5
ADD          # pop two values, push their sum
SETVAR 1     # pop top of stack, store in variable 1

More complex operations can also be single instructions:

CALL 2       # call function with 2 arguments
RETURN       # return from function
JUMPIFNOT 42 # jump to instruction 42 if top of stack is false

The instruction set is customized to the language. A language with weak typing can include type-coercion instructions. A language with exceptions can include exception-handling instructions.

4.4.3 The operand stack

A stack-based VM maintains a stack of values. Instructions push values, pop them, and perform operations. The stack acts as temporary storage for intermediate results.

Evaluating a + b * c with bytecode:

  1. Push a
  2. Push b
  3. Push c
  4. Multiply (pop two, push result)
  5. Add (pop two, push result)

At the end, the top of stack holds the result. The stack is implicit in the computation. You do not write variable names for temporaries.

The stack must be large enough for the deepest nesting in your program. You must also manage stack depth during compilation. The compiler must make sure that at every instruction, the stack has the right number of values.

4.4.4 A worked example: bytecode for a small R function

Consider this R function:

f <- function(x) x + 1

The body is x + 1. The tree is:

  +
 / \
x   1

R’s compiler turns this tree into four instructions, and compiler::disassemble() prints them:

compiler::disassemble(compiler::cmpfun(f))
list(.Code, list(12L, GETVAR.OP, 1L, LDCONST.OP, 2L, ADD.OP,
    0L, RETURN.OP), list(x + 1, x, 1, structure(c(NA, 1L, 1L,
2L, 2L, 0L, 0L, 0L), class = "expressionsIndex")))

The first inner list is the code. 12L is the bytecode version, and each opcode is followed by its operand, an index into the second list, the constant pool, counting from 0:

GETVAR   1    # look up the symbol x (pool entry 1) and push its value
LDCONST  2    # push the constant 1 (pool entry 2)
ADD      0    # pop two values, push their sum; entry 0, the call x + 1, is kept for error messages and for dispatch on classed operands
RETURN        # return the top of the stack

When the function runs with x = 5:

Stack before:  []
GETVAR 1:      [5]
LDCONST 2:     [5, 1]
ADD 0:         [6]
RETURN:        return 6

GETVAR still looks x up by name in the function’s environment, because R environments are first-class and code can add bindings to them at any time. The bytecode interpreter speeds that up with a per-call cache of bindings in the function’s own frame (USE_BINDING_CACHE in eval.c), but it never turns a variable into a numbered slot, as the JVM does with its local variables.

The bytecode is flat. The VM loops through the instructions, reads each opcode, and dispatches to a handler, with no tree traversal and no recursive eval call for x or 1.

4.4.5 The dispatch loop

The VM’s core is a tight loop:

loop:
  fetch next instruction
  decode the opcode
  jump to handler for this opcode
  handler modifies stack or state
  goto loop

The loop is small enough to stay in the CPU’s instruction cache. Its weak point is the jump to the handler. Written as a switch, every instruction goes through one shared indirect branch, which older branch predictors handled poorly. Threaded code gives each handler its own jump to the next handler, so the predictor can learn which instruction tends to follow which.

Compared with tree-walking, the dispatch is simpler and the instructions sit in one contiguous array instead of in scattered nodes.

GNU R has had a bytecode compiler and stack-based VM since R 2.13.0. Since R 3.4.0 the JIT is enabled by default and compiles most closures to bytecode on their first or second call, though it skips small closures defined inside other functions (R_CheckJIT in eval.c). When R is built with GCC, bcEval in eval.c uses direct threaded code: R_bcEncode replaces each opcode with the address of its handler, a GCC computed-goto label, and each handler ends by jumping straight to the next one (goto *(*pc++).v). The compiler package’s help page notes that, built with gcc, “the internal representation is actually threaded code”.

4.4.6 Constant pools

Instructions reference constants (numbers, strings, function objects) by index. These indices point into a constant pool, a table of values that the code uses. The constant pool is stored with the bytecode. When the interpreter needs a constant, it indexes into this table.

This saves space. Instead of embedding 3.141592653589793 in every instruction that uses pi, you store it once in the constant pool and use the index.

It also saves time. The compiler can share constants: two uses of the same constant point to one pool entry.

4.4.7 Stack vs register machines

Stack-based machines use an implicit operand stack. Register-based machines use named storage locations (registers). An instruction like ADD r1, r2, r3 means “add r2 and r3, store in r1”.

Stack machines need more instructions to describe the same work. You must push operands before you can add. Register machines need fewer instructions but require the compiler to allocate values to registers. This allocation is complex.

Stack machines are simpler to build and understand. Most educational VMs and many production VMs use stacks. The JVM, .NET, Python and R use stack-based bytecode.

Register machines can be faster: they execute fewer instructions, each doing more work, at the price of larger instructions to decode. The Lua VM and BEAM VM (for Erlang and Elixir) use register-based designs, and so does V8’s Ignition, which adds an accumulator register as the implicit input and output of most instructions.

The choice shapes later optimization. A register machine is closer to how hardware works. A stack machine is easier to compile to.

4.4.8 Failure modes

A common mistake is thinking that bytecode is always faster than trees. It is not. Bytecode saves the tree-walk cost, but it does not save the runtime cost of type checks or method dispatch. An R + operator still must check both operands for classes and attributes before it touches the numbers.

Another mistake is assuming bytecode speeds up cold code. The compiler takes time. If code runs once, bytecode is slower than tree-walking because of compilation cost. Bytecode only wins when code is hot enough to amortize compilation.

4.4.9 Bytecode compilation

Compiling a tree to bytecode is a tree walk with a code generator. For each node, emit instructions that leave the result on the stack. R’s compiler also folds constants, compiles only the taken branch of an if whose condition folds to a constant, and inlines calls to base functions such as + and [ as dedicated instructions.

The result is a flat sequence of instructions that a VM interprets. This two-stage pipeline (compile then interpret) is faster than pure tree-walking because the interpretation stage is tighter.

You can watch this in How R Executes Code. R parses to an AST, compiles closures to bytecode, and interprets the bytecode in a stack-based VM. Top-level expressions outside loops remain tree-walked.

Where this appears

  • r-in-rust (rrs) Can add a bytecode VM layer for optimization without replacing the tree-walker.

Where to go next

Back to top