How computers work

Languages and runtimes: how program text becomes processor instructions

A processor understands only one thing: a sequence of numeric instructions in its own architecture. Python, JavaScript, C, Java and Rust are ways of writing a program that are convenient for humans, and there is always a translator standing between them and the processor. The translation can happen in advance (a compiler), on the fly while the program runs (an interpreter), or by combining both approaches (JIT). That choice determines how fast a program starts, how fast it runs, and which computers it will run on.

Open in 3D →

Machine code: an instruction is a number

At the very lowest level, a program is bytes in memory. The processor core reads them from the address held in the program counter, the decoder splits the bits into fields, and the core’s blocks do whatever is encoded there. In this site’s teaching core (RISC-V RV64I), every instruction is exactly 32 bits. For example, addi x5, x0, 42 (“put the value x0 + 42 into register x5”) is encoded as the number 0x02A00293: the low 7 bits, 0010011, are the opcode for “arithmetic with a constant,” followed by 5 bits for the destination register number (5), 3 bits of refinement (000 means addition), 5 bits for the source register (0), and 12 bits for the constant (42).

Different architectures have different instruction sets. ARM64 also uses fixed-length 4-byte instructions. x86-64, the descendant of the 16-bit 8086, has instructions anywhere from 1 to 15 bytes long, with prefixes accumulated over 45 years; modern x86 cores internally translate them into simple micro-operations that resemble RISC anyway. A program compiled for x86-64 will not run on ARM64 without translation: they are different languages.

The processor knows nothing about variables, functions, types or objects. It knows registers (32 in RV64, where x0 is always 0; 31 general-purpose ones plus SP/XZR in ARM64; 16 general-purpose ones in x86-64), memory addresses and instructions: add, compare, load 8 bytes, store, jump if not equal. The sign of a number, a “string” type, the bounds of an array all exist only in the programmer’s head and in the code the compiler generated.

A simple example: the very same add instruction works for both signed and unsigned numbers, because two’s complement is designed so that the result bits are identical. Only the comparison and branch instructions differ. Fractional numbers, meanwhile, are handled by a separate unit with separate registers; in modern x86 these are vector registers that can also add 8–16 numbers in a single instruction.

See also: Core blocks: what each part of a processor core does · The processor core: an educational datapath and a modern core

Assembly language, functions and calling conventions

Assembly language is machine code written in words: instead of 0x02A00293 you write addi x5, x0, 42, and instead of jump addresses you use labels like loop:. A program called an assembler translates the text into numbers one to one. The player at the bottom of the site’s screen shows exactly this kind of text next to the instructions being executed.

Writing large programs in assembly is inconvenient, but reading it is useful: it shows what the processor actually does. Here is what a compiler turns the loop “s += a[i] for i from 0 to n” into on RISC-V: lw (load 4 bytes from an address), addw (add to the sum), addi (advance the address by 4), addi (decrement the counter), bnez (if the counter is not zero, jump back to the start). Five instructions per element, and a modern core will complete an iteration in roughly one clock cycle.

So that functions compiled by different compilers can call each other, there are calling conventions (the ABI). In RISC-V, arguments are passed in registers a0–a7, the result is returned in a0, and the return address is kept in ra. On Linux on x86-64, the first six arguments go in RDI, RSI, RDX, RCX, R8 and R9, and the result goes in RAX. If there are more arguments, or there are local arrays, the stack is used: a region of memory that grows downward with every call and shrinks on return.

This is the source of a classic vulnerability, the buffer overflow: if a C program writes more into a local array than it can hold, it may overwrite the return address on the stack, and when the function exits, the processor will “return” wherever the attacker wanted. Countermeasures include stack canaries, a non-executable stack and hardware protection of return addresses (the shadow stack in Intel CET, PAC on ARM).

The compiler: translating everything in advance

A compiler (GCC, Clang, the Rust and Go compilers) translates the whole program before it runs. The work happens in stages. The lexer chops the text into tokens: int, sum, (, …. The parser builds a syntax tree out of them. Semantic analysis checks types, scopes and the rules of the language; this is where errors like “you can’t add a string and a number” appear, before anything is run.

Next, the program is translated into an intermediate representation (IR), such as LLVM IR: it is almost assembly, but for an ideal machine with an unlimited number of registers, where every variable is assigned exactly once (SSA form). This form is convenient for optimization. The optimizer is the largest part of a compiler, consisting of hundreds of passes: compute constants ahead of time (60 * 60 * 24 → 86400), delete dead code, substitute the body of a small function in place of a call to it, hoist unchanging work out of loops, replace division by a constant with a multiplication and a shift.

One of the most powerful optimizations is vectorization. The compiler can rewrite a loop that sums an array so that a single AVX2 instruction adds 8 int values at once, making it several times faster without a single change to the source code. The compiler has time on its side: the user isn’t waiting for anything yet, and a large program may take minutes or hours to compile.

The final stage is code generation for a specific processor: choosing real instructions, allocating variables to the limited number of registers (whatever doesn’t fit spills onto the stack), and ordering instructions so that the core’s pipeline stalls less. Because of this, a compiled program is tied to an architecture: ARM64 and x86-64 require two different builds.

See also: Pipeline: several instructions at once

The interpreter: translating on the fly

An interpreter doesn’t produce machine code for your program. It is itself a compiled executable that reads your program and carries it out action by action. CPython, the standard Python, first turns the text into bytecode: the function return a + b becomes the instructions LOAD_FAST a, LOAD_FAST b, BINARY_OP (+), RETURN_VALUE. The bytecode is cached in .pyc files so that the text doesn’t have to be parsed every time.

Then the interpreter loop runs: read the next bytecode instruction, jump to its handler, execute it, repeat. The BINARY_OP handler doesn’t know in advance what it will be adding: integers, floating-point numbers, strings, lists or objects with an __add__ method. It looks at the types, finds the appropriate operation, checks for overflow, creates a new object for the result and decrements the reference counts of the old objects.

In Python every number is an object on the heap: even a small integer takes up 28 bytes (the reference count, a pointer to the type, the size and the digits themselves). So a single addition, which in C is one add instruction, turns into dozens to hundreds of machine instructions in Python. Hence the 10–100× speed difference on computational loops. On the other hand, the program starts instantly, runs anywhere there is an interpreter, and can be changed on the fly.

Interpreters get faster too. Python 3.11 learned to “specialize” bytecode: if integers are always being added at a particular spot, the instruction is replaced by a fast version, BINARY_OP_ADD_INT, with a quick check. Python 3.13 introduced an experimental JIT compiler and a build without the global interpreter lock (GIL), which lets Python threads truly run on multiple cores. And heavy math in Python has long been done by libraries such as NumPy and PyTorch, written in C, C++ and CUDA: Python merely hands out the commands.

See also: The processor core: an educational datapath and a modern core

Bytecode and virtual machines

Bytecode is machine code for an imaginary processor that is convenient to interpret and easy to port to any architecture. The best-known example is Java. The javac compiler translates a program into .class files containing JVM bytecode, and the very same file runs on Windows, Linux, x86 and ARM; all you need is a Java virtual machine for that platform.

The Java virtual machine is stack-based: instructions take their operands not from registers but from the top of a stack. The addition a + b looks like this: iload_1 (push the first variable onto the stack), iload_2 (the second), iadd (pop two numbers, push their sum), ireturn. Stack code is compact and doesn’t depend on how many registers the real processor has.

The same idea underlies .NET (CIL bytecode), Android (Dalvik and ART, which compile bytecode into machine code ahead of time when an app is installed) and WebAssembly. WebAssembly, which appeared in browsers in 2017, is a compact bytecode into which you can compile C, C++ or Rust and run it in the browser at nearly the speed of “native” code, in the same sandbox as JavaScript.

Bytecode also solves a security problem: before execution, the virtual machine verifies it, checking that there are no jumps into the middle of an instruction and that the types on the stack match. Code that passes verification cannot corrupt the virtual machine’s memory, even if it came from an untrusted source.

See also: Inside the browser: from HTML bytes to pixels on the screen

JIT: compiling while the program runs

A JIT compiler (just-in-time) combines both approaches. The program is first executed by an interpreter, which counts how many times each function has been called and each loop has been run. When a section becomes hot, say after being called thousands of times, the JIT compiles it into machine code and swaps it in: from then on, that section is executed by the processor directly.

The main advantage of a JIT over an ordinary compiler is that it knows how the program actually behaves. If the add function in JavaScript has received only integers a thousand times, the JIT generates code for integers, with a single quick check at the entrance. If the check fails, there is a deoptimization: a return to the interpreter. An ordinary compiler can’t afford this: it must account for every possible case.

The HotSpot JVM has two compilers: the fast C1 and the slower but thorough C2. V8 has four tiers: the Ignition interpreter, the fast Sparkplug and Maglev compilers, and the optimizing TurboFan. Hence “warm-up”: for the first few seconds, a Java server or a JavaScript game runs slower until the hot code has been compiled.

Technically, a JIT does something ordinary programs shouldn’t: it writes machine code into memory and transfers control there. For security reasons, a memory page cannot be both writable and executable at the same time (the W^X rule), so the JIT writes code into a page and then switches its permissions with a system call, or writes through a second mapping of the same frames. Well-warmed JIT code in JavaScript or Java is usually only 1.5–3 times slower than C.

See also: Inside the browser: from HTML bytes to pixels on the screen · The processor core: an educational datapath and a modern core

Memory: the stack, the heap and garbage collection

Every program has two main kinds of memory. The stack is for functions’ local variables: allocating and freeing cost a single instruction (moving the stack pointer), but everything disappears when the function exits. The heap is for data that outlives a call and whose size isn’t known in advance: strings, lists, objects. The question is who frees heap memory, and when.

In C, the programmer does it: malloc allocates, free releases. Forget free and you get a memory leak; free something twice or use it after freeing and you get memory corruption and a vulnerability. About 70% of serious vulnerabilities in large C and C++ programs (according to Microsoft and Google) stem precisely from memory-handling errors. C++ makes life easier with automatic destructors (RAII), while Rust checks ownership rules at compile time: every value has one owner, and the compiler itself inserts the deallocation where the owner goes away, at no runtime cost.

Python and Swift count references: each object has a counter, and when it drops to zero the object is deleted immediately. The downside is overhead on every assignment, plus cycles (A refers to B, B refers to A), which need an additional collector. Java, C#, Go and JavaScript use a tracing garbage collector: periodically it finds all objects reachable from the “roots” (global variables and stacks) and treats everything else as garbage.

Most objects die young (temporary strings, intermediate results), so the heap is divided into generations: the young one is collected often and quickly by copying the few survivors, the old one rarely. Modern collectors (ZGC and Shenandoah in Java, the Go and V8 collectors) run concurrently with the program and pause it for fractions of a millisecond even with heaps of hundreds of gigabytes. The price is extra CPU time and memory: garbage collection typically needs 1.5–3 times more memory than the live data occupies.

See also: DDR5 memory: how a byte is stored

Why there are so many languages, and myths about speed

Languages differ not only in syntax but also in how much work they take on themselves. C gives full control and maximum speed at the price of responsibility for every byte. Rust gives the same speed plus memory safety at the price of a strict compiler. Go and Java take care of memory and threads at the price of a garbage collector. Python and JavaScript give development speed at the price of execution speed.

Myth one: “an interpreted language means a slow one.” A language isn’t interpreted or compiled; implementations are. Python has PyPy with a JIT, and JavaScript has V8, which turns hot code into machine code. Besides, many programs spend most of their time waiting on the network and the disk rather than computing, and there the difference between languages is barely noticeable.

Myth two: “a compiler always produces the fastest code.” A compiler doesn’t know what data will arrive as input, but a JIT does. On the other hand, a compiler doesn’t spend time compiling while the program runs and needs no warm-up. In practice, programs in C, C++ and Rust remain the fastest where every nanosecond counts: OS kernels, browser engines, games, databases, neural network libraries.

No matter how a program is written, at the bottom it is always the same: a stream of machine instructions passes through the core’s decoder, registers and ALU, the very ones you can take apart in the model all the way down to transistors. The teaching program in the player at the bottom of the screen is exactly that machine code, and the Operating system layer shows how a program gets processor time, memory and files from the kernel.

See also: The operating system: who shares out the processor, memory and devices · The processor core: an educational datapath and a modern core

Open in 3D →

All articles

Overviews

Logic: from transistor to arithmetic

Processor

Computer

Servers and data centers

Networks and the internet

Software