kuniga.me > NP-Incompleteness > Executing Instructions

Executing Instructions

02 Dec 2026

AI-generated image of a CPU

In this post we’ll do a deep dive into how the CPU executes instructions. We’ll first look at a single CPU and then consider multi-core execution. We’ll assume an OS using the Linux kernel and CPUs using the x86-64 instruction set, so we can think of AMD and Intel processors but we’ll not go into specific details of either.

Table of Contents

  1. Loading the binary
  2. Instruction Address Translation
  3. Page Caching
  4. Instruction Fetching
  5. Execution
    1. Fetching
    2. Decoding
    3. Dispatching
    4. Scheduler
  6. Related Topics
    1. JIT Compilation
    2. Multiple Processes, Shared Binaries
    3. Multiple Cores
  7. Conclusion
  8. Related Posts

Loading the binary

Let’s start from userland, when we run ./my_binary in the terminal. We covered this process briefly in ELF: Executable and Linkable Format but we’ll cover it here in more detail.

The shell will fork a child process that then runs:

execve("./my_binary", argv, envp);

This is a syscall which will replace the instructions from the current process with those of the ELF file identified by ./my_binary. First, it switches execution to kernel space. The kernel assigns an entirely new virtual address space to this process, so it also gets a new page table (the mapping from virtual to physical addresses).

TLB. Recall that the TLB is a cache the CPU maintains for the page table. It maps the virtual address of a page to its physical page address. Note that the granularity of the TLB entry is a page, not an individual address. If you have a given virtual address, you can find the page by truncating to the page size (e.g. 4KB), mapping it to the physical page address, and then adding back the remainder (offset).

The TLB must be updated to support this new address space. We’ll not cover the TLB in detail here but it supports a tag, PCID, which changes whenever we change the virtual address space, such as when running execve(). This prevents the CPU from looking up outdated entries in the TLB, and it doesn’t have to spend time clearing up the entries from the old address space.

The kernel also needs to update registers like the program counter and CR3, which points to the physical address of the start of the page table.

One might wonder why we go through this trouble of forking, creating a new virtual address space and then immediately replacing it instead of starting a fresh one with the right instructions. One reason is that the parent process can configure the child first (redirect stdout, set up pipes, etc.), but it seems largely due to legacy reasons. In fact, the paper A fork() in the road argues that:

(…) fork was a clever hack for machines and programs of the 1970s that has long outlived its usefulness and is now a liability.

Anyway, as part of the loading process, the kernel also needs to reserve virtual memory space for the binary’s instructions. It doesn’t need to load all the instructions into memory but it knows how much it needs to reserve by looking at the ELF headers.

Things are more complicated for dynamically linked libraries, but we covered this process in detail in Shared Libraries so we’ll skip it here.

So at this point we have a process ready to run, with registers like the PC set up.

Instruction Address Translation

The CPU will need to fetch the instruction to be executed, whose address is in the PC register. But the PC stores the virtual address of the instruction. So the first thing it needs to do is to translate that to the physical address. It will truncate the address in the PC to get the virtual page address and then look it up in the TLB. If it finds the physical page address there, it can compute the instruction address.

Let’s suppose the address is not in the TLB. The CPU will need to walk the page table. Recall that the page table is an n-ary tree and that the CPU navigates the page table on its own (without talking to the kernel), and it can do that because the “links” stored in the page table are physical addresses that need no translation. The CPU knows where the page table starts because it’s stored in the CR3 register. If it finds the right mapping, it writes it back to the TLB, possibly evicting some existing entry.

If the entry doesn’t exist, it doesn’t necessarily mean it’s not in memory (see Multiple Processes, Shared Binaries), but to simplify it for now, let’s assume it’s not. Recall that the kernel doesn’t load the entire binary into memory, so in that case its virtual address is unmapped, and we’ll run into a page fault. The next section covers this flow.

Page Caching

When the CPU raises a page fault exception, it transfers control back to the kernel (meaning: the CPU starts executing kernel code).

The kernel knows how to map virtual address range maps to offsets in the ELF file. Each region in the ELF is mapped to a different virtual address range, so if we know that the start of the range is x and the offset of the region is y, we can do the math to find the offset from the virtual address.

The kernel reads a page of data into memory, map the virtual address to the physical address and adds the mapping to the process’s page table. After this, control passes back to the user process. The CPU caches this new mapping in the TLB and resumes.

Note that these are file-backed memory pages, aka file caches, so if there’s not enough memory available, the kernel might need to evict another page. When it does so, it also needs to evict it from the page table and ask the CPU to evict it from the TLB, because the next time this page is brought back to memory, it will likely map to a different physical address.

Instruction Fetching

Now that it has the physical address, it looks in the L1i cache to see if it finds the instruction there. Let’s take a closer look because this is very neat.

One thing we might ask ourselves is, “Why not index L1i by virtual addresses so we don’t need to do a TLB lookup?” The problem with this is that L1i might cache the same virtual address from different processes, which, of course, maps to different instructions. But we could add the PCID as part of the cache key, no? Turns out this is one viable alternative, and is known as a Virtually Indexed, Virtually Tagged (VIVT) cache! The downside of this is maintaining consistency when virtual address mappings change, a PCID gets recycled, or two processes share instructions (e.g. from shared libraries).

Associativity. Recall that CPU caches might use associativity. The idea is to have m cache lines but group them in sets. We can use k bits of the address to determine one of the 2^k sets. If we have one set per cache line (2^k = m, aka directed-mapped), then the address uniquely identifies the cache line. The problem is that if we’re unlucky and hot addresses map to the same cache line, there will be thrashing.

On the other side of the spectrum, if we have a single set (full associativity), we can handle collisions fairly, but then the CPU needs to scan the entries in this set to find the right one. This is similar to the trade-off with hash tables when deciding the number of buckets.

CPUs do something clever: since pages are typically 4KB, the least significant 12 bits of the virtual and physical addresses are the same. So they use some of these 12 bits to identify the set. This allows the CPU to look up the set using the virtual address while looking up the TLB in parallel.

If we get a cache miss at the L1i level, we look for it at the L2 and L3 layers. If we get a cache miss on L3, we finally need to fall back to memory. The CPU will read it from the physical address it has at hand. Note that we cannot have a page fault at this point. The page must be in memory because otherwise the physical address lookup would have failed. That’s why it’s important for the kernel to evict the TLB once it evicts a page cache.

If the CPU fetches an instruction from L3 or memory, it repopulates L1 and L2. The policy on when we write to L3 varies, but one such policy only writes to L3 after evition from L2. Note that the granularity of caching for L1 is a cache line. So if a cache line is 64 bytes, it will not just cache the instruction being requested. It will round the (physical) address down to the nearest 64-byte boundary and cache a block of 64 bytes worth of instructions. Note that this can be wasteful because it can store instructions that are behind the current one which will likely not be executed. When it needs to determine whether an instruction is cached, it also rounds down to the nearest 64-byte boundary to look for its cache line.

Finally, it’s possible that the instruction at the end of the cache might be cut off, so it might require two cache lines to cache it.

Execution

We’ll not go into details on how a CPU core executes instructions but in general it uses pipelining and parallelism, so at any given clock cycle it can process multiple instructions.

The details vary between CPU types, but the general stages we’ll study are: fetch, decode, dispatch, schedule, execute and retire.

Fetching

This consists of the Instruction Fetching we described above. We add that the CPU doesn’t fetch one instruction at a time; it fetches them in bytes. For example, a CPU might be able to fetch 32 bytes / cycle. Note that a cache line can be larger than that, for example 64 bytes, so it might take multiple cycles to read the cache line. It adds those bytes to a queue before the next stage.

Decoding

This consists of translating the x86 opcodes into even lower-level instructions. AMD calls them macro ops, and Intel calls them micro ops. AMD will later split these macro ops into micro ops. Intel might also further split their micro ops into smaller ops.

So, despite the confusing terminology, conceptually, they generate instructions that can represent multiple operations. We’ll discuss the rationale for this a bit later. To simplify the discussion, we’ll adopt the macro op terminology from AMD henceforth.

As they’re decoded, they’re added to another queue to be consumed by the next step.

Dispatching

The dispatcher has several functions. First, it maps the registers in the macro ops to physical registers. A modern CPU has hundreds of physical registers per core. This is similar to what the compiler does, except that the registers from the x86 ISA are actually virtual from the perspective of the CPU! So the compiler doesn’t know or doesn’t use the knowledge of how many physical registers the CPU has.

As part of this register mapping, the dispatcher also determines the dependencies between instructions. So, for example, if we have the instructions:

A: MOV RAX, 5
B: ADD RBX, RAX
C: MOV RAX, 7

It will map RAX to one of the physical registers, say P42, and keep the mapping in a table (the Register Rename Map). When it processes B, it will find RAX in the table. Similar to a compiler, it can determine when the current register’s lifetime ends. For example, if instruction C is MOV RAX, 7, it can remap RAX to a different register.

The dispatcher also assigns the macro opcodes to schedulers for them to be executed. Dependent instructions do not need to be processed by the same scheduler, but each scheduler has the dependency information. So if B is assigned to scheduler 1, it will wait until A is done.

Instructions that are independent can be executed out of order by the schedulers. However, the CPU must guarantee they’re emitted in order. The way it implements this is through a retire queue. If instructions x, x+1, … x+n are processed in a batch by the dispatcher, it will add them in this order to the retire queue, initially as “Waiting”. As the scheduler finishes processing them, it will mark them as “Completed”.

However, the instruction in position p cannot retire until all instructions in positions < p have retired.

Scheduler

There’s a staging area for each scheduler where macro ops are waiting. It can hold dozens of instructions at a time, until their dependencies are satisfied and an execution unit is available.

Once a macro op is selected, the scheduler converts it into micro ops and executes them in execution units such as the ALU (Arithmetic Logic Unit), FPU (Floating Point Unit), AGU (Address Generation Unit), etc., and removes the op from the staging area.

The execution unit will write results to a register, and some of the instructions waiting will become ready, and it will be marked as completed in the dispatcher’s retire queue.

JIT Compilation

JIT stands for Just-In-Time Compilation. We can use Java’s HotSpot JVM implementation as an example because it’s probably the most popular JIT compiler. Typically, Java code is interpreted, so the CPU runs instructions from the interpreter that itself runs the user code.

This level of interaction can add overhead, so for hot paths Java might JIT compile the code. The way it works at a high level is that Java requests a chunk of memory, compiles a user’s function into machine code and writes it to the page, then marks the page executable.

The interpreter can then copy data to registers and perform a low-level jmp to the address of the compiled instructions. It also saves the caller address on the stack, so when the function returns it goes back to the interpreter. The VM might decide to JIT code that a previously JITed function calls, in which case it needs to update the address of the jmp call in the JITed code, i.e., rewrite it.

We need to worry about concurrent access and cache consistency though. For concurrent access, we need to make sure there’s not another thread reading that instruction while we are rewriting it. For caache coherence, the instruction must be evicted from L1i, L2, L3.

One way the CPU could transparently evict this from L1i is to check whether an address is cached in L1i whenever it handles an instruction that writes to that address in memory.

Multiple Processes, Shared Binaries

When multiple processes run the same binary file (identified by the inode), the OS is smart about not loading copies of the same binary multiple times for each process.

It maintains a data structure called the page cache, indexed by inode + file offset, which maps to the address of the corresponding physical page. So, during a page fault, the process will compute the offset from the ELF it needs and will check if the corresponding page is loaded into memory, likely by another process.

In that case, it doesn’t need to read from disk - it just needs to map the corresponding virtual address to the physical address in the page cache, and add the mapping to the process’s page table.

Dynamically linked libraries are also independent files so if different binaries dynamically link to the same library, they benefit as well. Since statically linked libraries become part of the binary, it would not apply. This is one benefit of dynamic linking, but there are tradeoffs as we’ve covered in another post.

This not only saves memory by sharing the instructions in memory but also makes page faults faster since it doesn’t need to read from disk.

Multiple Cores

From the perspective of a given CPU core, execution is largely independent. Each core has its own set of registers pointing to instructions in memory and it’s independently executing them.

In terms of caching, each core has dedicated L1 and L2 caches, but shares L3 and RAM. But even for L1 and L2 we need to be aware of other cores because of cache coherence: if the data cached by core A is modified in memory by core B, we need to invalidate the cached data. We talked more about this in our post on CPU Cache (see Concurrency). However, for the particular case of instruction caching, L1i, we usually do not need to worry about mutations in memory. Even if JIT is involved, as we saw in JIT Compilation, the CPU handles the L1i coherence.

Conclusion

In this post, we investigated how exactly instructions go from an ELF file to being executed by the CPU. It hadn’t dawned on me that the x86 ISA is still an abstracted language, albeit pretty low-level, despite being something you can send to the CPU.

It was especially interesting to learn more about JIT and to reflect on how multiple cores execute instructions in parallel: it’s simpler than it sounds!

I knew that when multiple processes used the same binary, they shared the code in memory but I did not know the details. It makes a lot more sense to me now!

In Von Neumann Architecture, we mentioned that it supports mixing instructions and data, but that it has some downsides, so the Harvard architecture separates them. Modern CPUs are a mix of both, known as modified Harvard architecture: in memory, they allow mixing instructions and data, which allows features like JIT, but in caches we separate data and instructions (e.g. L1d and L1i).

In Function Objects in C++, we dug a little into how functions are translated into machine code and talked about the PC register.

In Notes on JavaScript Interpreters, we talked about another interpreter, Chrome’s V8, which also relies on JIT for performance.

In our review of the book Getting Started with LLVM Core Libraries, we covered a few related topics: the compilation process, including register allocation, which is analogous to what the CPU does, and LLVM’s support for JIT.