← Back to blogCPU architecture

How a Microprocessor Works: Fetch-Decode-Execute Deep Dive

A textbook-grade tour of the microprocessor: von Neumann architecture, buses, microoperations, decoding, ALU execution, branching, memory hierarchy, and pipelining.

DennyDenny
18 min read
Chalkboard feature illustration for “How a Microprocessor Works: Fetch-Decode-Execute Deep Dive”

TL;DR: Fetch, decode, and execute form a useful conceptual model for an instruction processor: choose an instruction address, obtain and interpret the instruction, perform its operation, and establish the next architectural state. A small teaching CPU may expose those phases as separate cycles. Modern processors overlap, split, cache, predict, and reorder the work while preserving the instruction set’s required behavior.

A microprocessor executes instructions defined by its instruction-set architecture (ISA). At the architectural level, each instruction identifies an operation and operands and produces defined changes to registers, memory, flags, or control flow. Fetch-decode-execute is a strong teaching model for that behavior, but it is not a literal three-box description of every implementation.

This guide starts with a transparent multicycle CPU and then distinguishes that model from pipelined, superscalar implementations. The example instruction formats and microoperations are intentionally invented for teaching; they are not claims about x86, Arm, RISC-V, or any specific commercial processor. For a gentler visual introduction, begin with the fetch-decode-execute case study.

Stored-program organization and modern hybrids

John von Neumann’s 1945 First Draft of a Report on the EDVAC was an influential description of a stored-program digital computer. The history involved a broader EDVAC team, so “von Neumann architecture” names the organization rather than assigning sole credit for every underlying idea.

            +-----------------------------+
            |          MEMORY             |
            |  (instructions + data       |
            |   share one address space)  |
            +--------------+--------------+
                           |
                  Address / Data / Control
                           |
            +--------------+--------------+
            |             CPU             |
            |  +------------------------+ |
            |  |    Control Unit (CU)   | |
            |  +------------------------+ |
            |  |  Arithmetic-Logic Unit | |
            |  +------------------------+ |
            |  | Registers / PC / IR    | |
            |  +------------------------+ |
            +-----------------------------+
                           |
                  Input / Output devices

The central stored-program idea is that encoded instructions reside in electronic memory and can be fetched under program control. Instructions and ordinary data may share an address space and representation, enabling programs to be loaded and changed without rewiring the datapath. A machine still runs only software compatible with its ISA, privileges, memory model, and available devices.

Von Neumann vs Harvard

In a Harvard organization, instruction and data accesses use distinct memories or address spaces. That separation can permit an instruction fetch and a data access at the same time, but it also requires explicit rules for loading or modifying code.

Many processors are hybrids. A core may present one architectural address space while using separate L1 instruction and data caches internally. Conversely, some microcontrollers expose distinct program and data spaces even though other resources are shared. The terms describe an interface and organization; they do not determine the number of physical buses or the complete microarchitecture.

What Are the Buses Between the CPU and Memory?

Before tracing an instruction, it helps to separate three logical roles. They may be dedicated wires in a small teaching computer or encoded transactions on a modern on-chip interconnect.

RoleTypical directionPurpose
AddressRequester → memory systemIdentifies a location or resource
Write data / read dataRequester → target / target → requesterCarries the value being transferred
Control and responseBoth directionsEncodes read/write intent, size, validity, readiness, errors, and ordering

Address width, architectural pointer width, physical-address width, and installed memory are related but not identical. A byte-addressed 32-bit virtual address can name 2322^{32} bytes (4 GiB) in one address space, while an implementation may use a different physical-address width. Similarly, an ISA’s register width does not by itself specify the width or throughput of its external memory interface.

Here is one deliberately simple read handshake:

T0:  CPU drives ADDRESS lines, asserts MEM_REQ + RD
T1:  Memory decodes address, places byte on DATA lines, asserts READY
T2:  CPU latches DATA into a register, deasserts MEM_REQ

A write reverses the data direction and carries a write indication. Real protocols can pipeline requests, return responses out of order, split transactions into bursts, and insert variable wait states. Inside a processor, register files, execution units, caches, and interconnects have their own ports and networks rather than one universal “CPU bus.”

If buses feel abstract, build a tiny one yourself. Open the RAM with address control template and watch what happens to the address lines as the controller steps through addresses. Then pair that with the basic RAM memory system to see read and write timing. Memory primitives are documented in the RAM component reference and ROM component reference.

How Does the Fetch Phase Work, Microoperation by Microoperation?

Fetch obtains instruction bytes or words associated with the current program-counter value. A transparent multicycle datapath can express the work as register-transfer microoperations. Our example is word-addressed and uses fixed one-word instructions, so PC + 1 selects the next instruction. Real ISAs define their own alignment and instruction lengths: base 32-bit RISC-V instructions normally advance the byte address by 4, while its compressed extension also defines 16-bit instructions.

Microoperations are written in register-transfer language (RTL). A typical fetch on a simple CPU looks like this:

T0:  MAR <- PC                  ; copy PC to memory-address register
T1:  MDR <- MEM[MAR],  PC <- PC + 1   ; start memory read, increment PC
T2:  IR  <- MDR                 ; latch the instruction

This is one possible three-cycle teaching sequence, not a mandatory CPU protocol. A faster memory or wider datapath could combine steps; a cache miss could add many wait cycles; a pipeline can overlap fetch with older instructions.

A few details that matter:

  • Why this model has an MAR. The memory-address register holds the requested address while the PC is free to advance. Modern designs may represent the same role with request queues, cache tags, and pipeline state rather than one programmer-visible register.
  • Why the PC can increment during T1. A dedicated incrementer can operate concurrently with a memory request. This is datapath concurrency inside one instruction, distinct from instruction-level parallelism among several instructions.
  • How the IR latches. In the teaching circuit, an instruction register captures the fetched word when its load enable is asserted. A modern front end may hold many fetched bytes and decoded operations in buffers instead of one IR.

You can watch this teaching sequence in the sequential instruction executor template. Pause between cycles and inspect the MAR and MDR values. For the program counter itself, see program counters and the 8-bit program-counter component.

Fetch as a state machine

Conceptually, this fetch controller is a small finite-state machine. State registers encode T0, T1, and T2, and combinational logic asserts the required enables in each state. It can be demonstrated with discrete flip-flops, while synthesized hardware may map the state into other available sequential cells. The clock guide explains how those state transitions are timed.

How Does the Decode Phase Generate Control Signals?

Once the instruction word is sitting in the IR, the CPU has 16 bits (or 32, or 64) of binary that means something. The job of decode is to turn that meaning into a set of physical control signals — wires that go HIGH or LOW to route data through the right registers and the right ALU operation.

Instruction format

Instruction encodings assign meaning to bit fields, although variable-length ISAs need not place the same field at a fixed position in every instruction. Our invented fixed-width example uses:

| 15 14 13 12 | 11 10  9  8 |  7  6  5  4 |  3  2  1  0 |
|   OPCODE    |    REG_A    |    REG_B    |    REG_D    |
  • Opcode (4 bits): which operation. With 4 bits we get 16 distinct instructions, which is enough for ADD, SUB, AND, OR, XOR, LD, ST, JMP, BEQ, BNE, NOP, MOV, INC, DEC, NOT, HLT.
  • REG_A, REG_B: source register indexes (4-bit binary index, so 24=162^4 = 16 registers can be addressed).
  • REG_D: destination register index.

Immediate-mode formats sacrifice one register field for an immediate value, e.g.

| 15 14 13 12 | 11 10  9  8 |  7  6  5  4  3  2  1  0 |
|   OPCODE    |    REG_D    |       IMMEDIATE          |

Opcode extraction

In the teaching datapath, the opcode bits feed a 4-to-16 decoder; each output corresponds to one opcode. Additional logic interprets register fields, immediate values, modes, and the current controller state. See decoders and encoders and the decoder component.

Once the decoder has fired, the rest of the control unit is just combinational logic — a giant truth table that maps (opcode, timing_state, flag_bits) to a vector of microoperation enables.

OpcodeMnemonicT2 microopT3 microopT4 microop
0001ADDA_BUS <- REG[REG_A]B_BUS <- REG[REG_B]REG[REG_D] <- ALU_OUT(A+B)
0010SUBA_BUS <- REG[REG_A]B_BUS <- REG[REG_B]REG[REG_D] <- ALU_OUT(A-B)
0011ANDA_BUS <- REG[REG_A]B_BUS <- REG[REG_B]REG[REG_D] <- ALU_OUT(A&B)
1010JMPPC <- IMMEDIATE--
1011BEQ(if Z=1) PC <- IMMEDIATE--

Control implementations lie on a spectrum:

  • Hardwired control. Combinational logic and state produce enables directly. This works well for a small controller and can be synthesized from ordinary logic gates.
  • Microprogrammed control. A control store holds sequences of microinstructions that generate datapath controls. This can make complex or infrequent instruction behavior easier to specify.
  • Hybrid control. A processor can use direct decode for common instructions and invoke microcode or sequenced control for complex cases, assists, or updates. The RISC/CISC label alone does not tell you which implementation it uses.

The control-unit component provides a teaching primitive. For the finite-state-machine foundation, see counters and state machines.

How Does the Execute Phase Actually Compute?

Execute is where work happens. Up to this point, the CPU has only moved bits around. Now it transforms them.

For a typical arithmetic instruction like ADD R3, R1, R2, execute does three things:

  1. Register read. The example register file has two read ports addressed by REG_A and REG_B, so both operands can reach A_BUS and B_BUS. A teaching version can be assembled from small registers and multiplexers; a physical CPU uses a custom or synthesized multiported register structure.
  2. ALU operation. The ALU sees the two operands and the opcode-derived ALU function code. A teaching ADD path may use a ripple-carry adder, while faster structures include carry-lookahead and parallel-prefix approaches. For AND/OR/XOR, bitwise logic produces the candidate result. See how an ALU works and the 8-bit ALU component.
  3. Write-back and optional flag update. On an enabled edge, the example stores the ALU result in REG_D and updates Zero (Z), Carry (C), Sign (S), and Overflow (V). Flags are ISA-specific: some architectures expose a condition-code register, some update flags only for selected instructions, and others use ordinary registers or comparison results instead. See CPU flags and the flags-register component.

The same template that walks fetch and decode also walks execute: open the 4-bit ALU demonstration to see operands flow through, and the 8-bit ALU system for a more realistic datapath.

Why latency varies

In a small multicycle CPU, simple arithmetic may use one execute cycle while a load waits for memory. In a modern processor, fetch and decode can also vary because of instruction-cache misses, variable-length decoding, and front-end redirects. Execution latency depends on the operation and operands; memory latency depends on the cache and memory system; a mispredicted branch redirects and refills useful pipeline work. Queues, speculation, caching, and parallel execution help tolerate these variations without changing the ISA’s visible result.

How Do Conditional Branches Actually Re-aim the PC?

Branches are one way to change control flow. Jumps, calls, returns, exceptions, interrupts, and traps can also replace the next sequential program-counter value. A conditional branch chooses between the fall-through address and a target according to an ISA-defined condition.

The microoperation for BEQ target (branch if equal) is:

T2:  if (Z == 1) PC <- IMMEDIATE
     else        (no-op; PC already incremented during fetch)

In this custom teaching ISA, the target is encoded as an immediate value and BEQ tests Z. The control logic combines the decoded instruction, condition, and controller state to select the PC source and assert its load enable. A real ISA may use PC-relative offsets, compare two registers directly, or define delay slots and alignment rules.

BranchBoolean conditionMnemonic
BEQZ=1Z = 1branch if equal
BNEZ=0Z = 0branch if not equal
BLTS≠VS \ne Vbranch if less than (signed)
BGES=VS = Vbranch if greater or equal
BCSC=1C = 1branch if carry set
BVSV=1V = 1branch if overflow set

The table is illustrative rather than universal, but it shows how Boolean conditions become control decisions. De Morgan’s laws can express equivalent condition logic, while synthesis and the target cell library determine the resulting area and delay. For signed flag arithmetic, two’s complement explains where S and V come from.

A branch is also where the CPU’s predictive circuitry earns its keep. We will get to branch prediction in the modern-extensions section.

What Is the Memory Hierarchy, and Why Does It Have So Many Levels?

Storage technologies trade access latency, capacity, bandwidth, energy, persistence, and cost. A particular processor’s sizes and cycle counts change by generation and operating frequency, so architecture should be reasoned about from the hierarchy rather than one frozen table.

LayerTypical roleCommon implementationImportant distinction
Architectural registersImmediate operands and stateMultiported register files, latches, or flip-flopsNamed by the ISA
L1 instruction/data cachesLowest-latency cached code and dataOn-chip SRAMUsually private to a core or small core group
Mid/last-level cachesCatch misses before external memoryLarger on-chip SRAM structuresOften shared at some level
Main memoryActive program working setsDRAMVolatile; much larger and slower than on-chip cache
Persistent storageFiles and durable dataNAND flash or magnetic mediaAccessed through I/O and the operating system, not as another CPU cache level

Three principles are more durable than exact numbers:

  • Locality makes caching effective. Temporal locality reuses recently accessed blocks; spatial locality accesses nearby addresses.
  • Latency and bandwidth are different. A system can take a long time to return the first requested byte yet sustain a high transfer rate for many consecutive bytes.
  • A miss exposes the next level. Hardware prefetching, multiple outstanding misses, out-of-order execution, and software layout can overlap or avoid some of that cost, but none makes every access equally fast.

For an interactive primer on the storage end of this stack, see RAM vs ROM and the endianness discussion of how multi-byte values sit in memory.

For memory-sensitive workloads, access pattern and cache behavior can dominate performance. For compute-bound, branch-heavy, or I/O-bound workloads, other bottlenecks may dominate. Measure before choosing an optimization.

What Is Pipelining, and How Does It Make Things Faster?

Our teaching machine is multicycle and non-overlapped: one instruction completes its fetch, decode, execute, and write-back steps before the next begins. A true single-cycle CPU is different—it completes the full architectural instruction in one long clock period. Both leave hardware underused during parts of the instruction.

Pipelining lets different instructions occupy different hardware stages at the same time. Pipeline registers separate the stages. In the ideal three-stage example below, an instruction still takes three cycles from fetch through execute, but after filling the pipeline the machine can complete up to one instruction per cycle.

Cycle:        1     2     3     4     5     6
Fetch:       I1    I2    I3    I4    I5    I6
Decode:            I1    I2    I3    I4    I5
Execute:                 I1    I2    I3    I4

For a long stream of independent instructions and perfectly balanced stages, the ideal throughput approaches three times that of the non-overlapped example. Register overhead, stalls, and unequal stage delays reduce the gain. Three hazard classes explain many of those stalls:

  • Structural hazards. Two stages want the same hardware. Solved by duplicating it (e.g. separate adders for PC increment and ALU work).
  • Data hazards. Instruction i+1i+1 needs the result of instruction ii, which is still in the pipeline. Solved with forwarding (route the ALU output back to the input of the next ALU op) or by stalling.
  • Control hazards. A branch decides the next PC at execute, but fetch has already pulled in two wrong instructions. Solved with branch prediction (and pipeline flush on misprediction).

Adding pipeline boundaries can reduce combinational work per stage and permit a shorter period, but each boundary adds clock-to-Q, setup, clocking, power, and control overhead. Deeper pipelines also increase the amount of work discarded after some redirects. There is no universally best depth; it depends on the workload and implementation. For the physical timing behind that tradeoff, see propagation delay and setup, hold, and metastability.

RISC vs CISC: Two Schools of Decode

RISC and CISC describe historical ISA design tendencies, not two implementation laws. Counting mnemonics does not classify a processor reliably, and neither label predicts CPI or performance.

TendencyRISC-oriented examplesCISC-oriented examples
EncodingA small number of regular formats; fixed-width base encodings are commonMore variable formats and operand encodings
Memory operandsLoad/store organization is commonSome arithmetic instructions may access memory directly
Architectural stateOften many general-purpose registersMay include more specialized or implicit operands
ImplementationCan still use speculation, micro-ops, and microcodeCan still pipeline common operations into short internal operations

The boundaries are porous. RISC-V has a regular 32-bit base encoding and an optional 16-bit compressed encoding. Arm has several instruction encodings and rich extensions. x86 uses variable-length architectural instructions, while many implementations decode common instructions into internal operations. Use the labels to discuss ISA tradeoffs—code density, decode work, compatibility, and compiler targeting—not as shorthand for “simple hardware” versus “complex hardware.”

What Modern Extensions Sit on Top of the Basic Pipeline?

The single-issue, in-order, five-stage pipeline is the canonical undergraduate CPU. Real chips are much more aggressive. We will not derive these in detail — each deserves its own post — but here is the layer cake.

Out-of-order execution

If instruction i+1i+1 waits for a result but i+2i+2 is independent, an out-of-order core can schedule the independent work first. Common implementations use renamed registers, issue queues or reservation stations, and an in-order retirement structure so exceptions and architectural state remain precise. The exact structures are microarchitecture-specific.

Superscalar issue

A superscalar CPU can issue or execute more than one operation per cycle when dependencies and resources permit. Front-end width, execution ports, data dependencies, cache misses, branch behavior, and retirement width can each become the bottleneck; advertised width is not guaranteed application throughput.

Branch prediction

A branch predictor estimates direction and target before the branch executes so fetching can continue speculatively. Accuracy varies greatly with code and predictor design. A correct prediction avoids a control redirect, while a wrong one discards younger dependent work and restarts from the resolved path; the penalty is not necessarily identical to the full pipeline depth.

SIMD and vector extensions

Single-Instruction Multiple-Data (SIMD) operates on several packed lanes with one architectural instruction. For example, a 512-bit vector can hold sixteen 32-bit elements, although the supported operations and actual throughput depend on the ISA and implementation. SIMD benefits workloads with regular data parallelism; branching, data layout, memory bandwidth, and tail handling can limit the gain.

SMT (hyperthreading)

Simultaneous multithreading lets instructions from more than one hardware thread share a core’s front end and execution resources. It can fill slots one thread leaves unused, but the threads also compete for caches, queues, bandwidth, and execution units. The benefit depends on whether their resource demands complement or conflict.

Speculation

Processors may speculate past predicted branches and unresolved memory dependencies. Results are prevented from becoming architectural state until it is safe to retire them, but microarchitectural effects can remain. Spectre-class attacks demonstrated that such effects can form side channels; Meltdown exploited a related transient-execution failure to enforce privilege checks early enough. The two families should not be reduced to one mechanism.

How Do You Build All of This for Real (Even at Toy Scale)?

There is a large and valuable space between a block diagram and a production processor. A small simulated CPU can make instruction sequencing, control, and datapath decisions visible. Scaling adds much more than optimization—including physical timing, verification, memory ordering, privilege, exceptions, and I/O—but the teaching model remains a useful foundation.

A reasonable starter project sequence:

  1. Build a 4-bit ALU. Combine adders, logic gates, and a multiplexer to select the operation. Walk through it in how an ALU works and try the 4-bit ALU demonstration template.
  2. Build a register file. Four 4-bit registers wired to a multiplexer for read and a decoder for write.
  3. Build a memory. A small RAM with address control is enough.
  4. Build a program counter. Use a counter with a load enable, sized to your address bus. See the 8-bit program-counter component.
  5. Build a control unit. For a small ISA, derive enables from (opcode, timing_state, flags) and document each state transition.
  6. Wire and verify the system. The sequential instruction executor template is a teaching datapath that you can step one simulated cycle at a time.

For a step-by-step build narrative, our companion post build a CPU from scratch in a simulator walks the wiring decisions in detail.

Putting the Whole Cycle Together

Let’s run ADD R3, R1, R2 on the custom teaching CPU, assuming R1 = 5, R2 = 7, and the instruction is at word address 0x10. The trace lists the intended microoperations so you can audit this datapath one cycle at a time.

Initial state: PC = 0x10,  R1 = 0x05,  R2 = 0x07,  R3 = 0x00,  Z=C=S=V=0
Memory at 0x10: 0001 0001 0010 0011   (opcode, source A, source B, destination)

CYCLE 1 (T0, fetch):
  MAR <- PC                            ; MAR = 0x10
  ADDRESS_BUS <- MAR
  RD <- 1, MEM_REQ <- 1

CYCLE 2 (T1, fetch):
  MDR <- DATA_BUS                      ; MDR = 0x1123
  PC  <- PC + 1                        ; PC  = 0x11

CYCLE 3 (T2, fetch + start decode):
  IR  <- MDR                           ; IR  = 0x1123
  RD <- 0, MEM_REQ <- 0
  (control unit decodes IR[15:12] = 0001 = ADD)

CYCLE 4 (T3, execute step 1):
  A_BUS <- REG[IR[11:8]]               ; A_BUS = R1 = 0x05
  B_BUS <- REG[IR[7:4]]                ; B_BUS = R2 = 0x07

CYCLE 5 (T4, execute step 2):
  ALU_OUT <- A_BUS + B_BUS             ; ALU_OUT = 0x0C
  Z <- (ALU_OUT == 0)                  ; Z = 0
  C <- carry_out                       ; C = 0
  S <- ALU_OUT[MSB]                    ; S = 0
  V <- overflow                        ; V = 0

CYCLE 6 (T5, write-back):
  REG[IR[3:0]] <- ALU_OUT              ; R3 = 0x0C

(go to CYCLE 1 for the next instruction)

Six cycles complete one instruction in this custom controller. A pipelined version could begin younger instructions before the ADD retires, provided it detects and handles hazards. A modern out-of-order core may represent one architectural instruction with several internal operations, so this trace explains architectural intent and a possible implementation—not the exact internal cycles of another processor.

Use the sequential instruction executor template to compare the simulated bus values with the trace. A match validates this model and test case; it does not validate an x86, Arm, or RISC-V implementation. The case study provides a guided walkthrough.

Where the Microprocessor Story Goes Next

You now have the textbook. Beyond it sit topics each large enough to be a post on its own:

  • Caches — set-associative mapping, replacement policy, write-through vs write-back.
  • Virtual memory — page tables, TLBs, translation, protection.
  • Exceptions and interrupts — the asynchronous side of the control unit.
  • Multi-core coherence — MESI, snooping, ring buses, mesh interconnects.
  • Power and clocking — voltage-frequency scaling, clock gating, clock skew.
  • Security and side channels — the cost of speculation.

If you are designing your own CPU as a learning exercise, the build a CPU from scratch post is the natural next read. If you want to follow the instruction stream further into where data lives, RAM vs ROM and endianness are the next two lenses.

Fetch-decode-execute is a compact bridge between software-visible instructions and hardware state changes. Open the sequential instruction executor template, predict each transfer before stepping, and compare the result with your trace. The exercise is successful when every state change has an explicit cause.


Build it next: Open the sequential instruction executor template in DigiSim and step through your first instruction. Then read build a CPU from scratch in a simulator to wire one yourself from scratch.

Primary and Technical References

Apply the concept in a simulator model.