Back to series
· 13 min read

How Does a CPU Execute an Instruction? Instruction Cycle and Execution Process


1. Why Does a CPU Need an Instruction Cycle?

The CPU (Central Processing Unit) is the core execution component of a computer, responsible for interpreting and executing the machine instructions in a program.

The high-level language programs we write, for example:

int a = 10;
int b = 20;
int c = a + b;

must ultimately go through compilation, assembly, linking, and other processes to be converted into machine instructions that the CPU can recognize.

The CPU does not directly understand high-level language expressions such as a + b. Instead, following the format defined by the processor's instruction set, it reads the opcode, register numbers, immediate values, or memory addresses in a machine instruction and performs the corresponding operation.

For example, a simple addition instruction can be abstracted as:

ADD R1, R2, R3

meaning:

R1 = R2 + R3

When the CPU executes this instruction, it must complete several steps:

  1. Fetch the instruction from memory.
  2. Decode the instruction to determine what operation is to be performed.
  3. Read the operands from the registers.
  4. Use the arithmetic unit to perform the addition.
  5. Write the result back to the destination register.
  6. Update the program counter to prepare for executing the next instruction.

Together, these steps make up the instruction execution process.

The Instruction Cycle is the basic sequence of work a CPU goes through to complete one instruction.

It describes how the CPU fetches instructions from a program and converts them into actual hardware operations.

2. The Core Components of a CPU: Who Executes Instructions?

Before understanding the instruction cycle, you first need to know a few important components inside the CPU.

1. Control Unit (CU)

The Control Unit is responsible for coordinating the work of the various components inside the CPU.

It is mainly responsible for:

  • Determining the location of the next instruction based on the program counter.
  • Reading instructions from memory.
  • Decoding instructions.
  • Generating control signals.
  • Controlling data transfers among the registers, the arithmetic unit, and the datapath.
  • Coordinating the order in which instructions are executed.

You can think of the control unit as the CPU's dispatch center.

It usually does not itself perform arithmetic operations such as addition or subtraction; rather, it decides when to read data, when to perform an operation, and when to write back the result.

2. Arithmetic Unit (ALU)

The ALU (Arithmetic Logic Unit) is responsible for performing arithmetic and logical operations.

Common operations include:

Operation Category Specific Operations
Arithmetic operations Addition, subtraction, multiplication, division
Logical operations AND, OR, XOR, NOT
Comparison operations Greater than, less than, equal to
Shift operations Left shift, logical right shift, arithmetic right shift

For example:

ADD R1, R2, R3

The ALU receives the data in R2 and R3, performs the addition, and produces the result.

A modern CPU has more than one ALU; it may also contain multiple integer execution units, floating-point units, vector units, and specialized execution units.

3. Registers

Registers are very small, very fast storage units inside the CPU.

When executing instructions, the CPU usually gives priority to registers for holding instruction addresses, operands, results, and status information.

Several important registers are as follows:

Register English Name Function
PC Program Counter Holds the address of the next instruction to be fetched
IR Instruction Register Holds the instruction currently being processed
MAR Memory Address Register Holds the memory address to be accessed
MDR Memory Data Register Temporarily holds data read from memory or about to be written
GPR General Purpose Register General-purpose registers that hold operands and results
FLAGS Status Register Holds operation status flags

Different processors may use different register names and organizations. For example, x86-64 uses RIP as the instruction pointer, while ARM64 uses the concept of PC as the program counter, but their specific implementations and visibility differ.

4. Cache

The CPU typically runs much faster than main memory.

If every instruction had to access DRAM directly, the processor would frequently wait for data, reducing execution efficiency.

For this reason, modern CPUs use multi-level caches:

  • L1 Cache: smaller capacity, very fast.
  • L2 Cache: usually larger than L1.
  • L3 Cache: usually shared by multiple cores, with even larger capacity.

Cache is used to store instructions and data that were recently accessed or are likely to be accessed again.

During instruction fetch and data access, the CPU can first search through the cache hierarchy for the target content, reducing the number of accesses to main memory.

5. The CPU's Internal Datapath

The components of a CPU do not work in isolation; they are connected through datapaths.

Datapaths include:

  • Data transfer paths between registers.
  • Data paths between registers and the ALU.
  • Paths between the ALU and the result register.
  • Access paths between the CPU and the cache and memory system.

The control unit generates control signals that determine how data flows along these paths.

For example, an add instruction may involve:

general-purpose register → ALU → destination register

And a load instruction may involve:

address calculation → Cache / memory system → destination register

III. The Five Basic Stages of the Instruction Cycle

The classic instruction execution model usually splits an instruction into five stages:

  1. IF: Instruction Fetch
  2. ID: Instruction Decode
  3. EX: Execute
  4. MEM: Memory Access
  5. WB: Write Back

Not every instruction has to go through all five stages.

For example, a register-to-register add usually does not need to access data memory, whereas a load instruction does.

1. IF: The Fetch Stage

The fetch stage is responsible for reading the next instruction from the instruction storage system.

The core register here is the PC (program counter).

Suppose the current PC holds:

PC = 0x1000

This means the next instruction to be fetched is located at address 0x1000.

The CPU fetches the instruction according to the address specified by the PC, and passes it on to the subsequent decode logic.

The abstract process:

PC → instruction cache / memory system → instruction

Using the classic register model, this can be expressed as:

MAR ← PC
MDR ← Memory[MAR]
IR ← MDR

Meaning:

  • MAR holds the address of the current instruction.
  • The corresponding instruction is read from the storage system.
  • MDR temporarily holds the data that was read.
  • IR holds the current instruction.

Note that this is a classic datapath model intended to aid understanding. Modern CPUs usually implement fetching through mechanisms such as instruction caches, fetch queues, pre-decoding, and instruction prefetching, and there is not necessarily a fully corresponding sequence of separate register transfers.

How is the PC updated?

If the current instruction is 4 bytes long and the program executes in the normal sequential order:

PC = PC + 4

For example:

Old PC: 0x1000
New PC: 0x1004

But not all instructions execute sequentially.

When a jump, branch, function call, or exception occurs, the address of the next instruction may come from some other target address.

2. ID: The Decode Stage

Once fetching is complete, the CPU needs to understand what this instruction means.

This is the decode stage.

A machine instruction usually contains several fields:

  • Opcode: specifies what operation to perform.
  • Source operand information: specifies where the data comes from.
  • Destination operand information: specifies where the result is stored.
  • Addressing mode: specifies how to locate the operands.
  • Immediate: a constant contained directly in the instruction.

For example:

ADD R1, R2, R3

This can be understood abstractly as:

Field Meaning
ADD Perform addition
R2 First source operand
R3 Second source operand
R1 Destination register

The decode stage needs to accomplish the following:

  1. Identify the opcode.
  2. Determine the instruction type.
  3. Parse the source and destination registers.
  4. Identify immediates and the addressing mode.
  5. Generate the control information needed for subsequent execution.

For instructions that need register operands, the CPU also has to read the corresponding data from the register file.

For example:

R2 = 10
R3 = 20

Once decoding and operand reading are complete, the execution unit can obtain:

Operation: ADD
Operand A: 10
Operand B: 20
Destination register: R1

3. EX: The Execute Stage

The execute stage is responsible for actually carrying out the operation specified by the instruction.

For arithmetic and logic instructions, this is usually done by the ALU or another execution unit.

For example:

ADD R1, R2, R3

Assume:

R2 = 10
R3 = 20

The ALU performs:

10 + 20 = 30

Yielding the result:

Result = 30

But the EX stage is not only about arithmetic.

Different types of instructions may perform different operations:

Instruction Type Main Work in EX Stage
ADD Perform addition
SUB Perform subtraction
AND Perform logical AND
CMP Compare operands
LOAD Calculate effective memory address
STORE Calculate effective memory address
BRANCH Determine branch condition or calculate target address

For example, a load instruction:

LOAD R1, [R2 + 8]

Assume:

R2 = 0x2000

Then the execution unit needs to calculate the effective address:

Effective Address = 0x2000 + 8
                  = 0x2008

The subsequent memory access stage then reads the data at that address.

4. MEM: Memory Access Stage

The MEM stage handles instruction access to data memory.

Not every instruction needs memory access.

For example:

ADD R1, R2, R3

It only needs register operands and usually does not need to access data memory.

The following two types of instructions, however, require memory access:

Load instruction (LOAD)

LOAD R1, [0x2000]

Meaning:

R1 = Memory[0x2000]

Based on the effective address, the CPU accesses the data cache or memory system and reads the corresponding data.

Store instruction (STORE)

STORE [0x2000], R1

Meaning:

Memory[0x2000] = R1

The CPU writes the data in the register to the specified memory location.

Note that memory access in modern CPUs may also involve:

  • TLB address translation.
  • L1, L2, and L3 data cache lookup.
  • Cache miss handling.
  • Memory consistency protocols.
  • Store buffer.
  • DRAM access.

Therefore, the MEM stage does not mean that physical memory is directly accessed every time.

5. WB: Write Back Stage

The write back stage saves the execution result to the destination.

For example:

ADD R1, R2, R3

Assume the execution result is:

Result = 30

The write back stage completes:

R1 ← 30

For a load instruction:

LOAD R1, [0x2000]

If the value read is:

Memory[0x2000] = 100

Then write back:

R1 ← 100

Note that:

  • Arithmetic instructions usually write back to registers.
  • Load instructions usually write memory data back to registers.
  • Store instructions usually complete the memory write in the MEM stage and do not necessarily need a traditional WB stage.
  • Branch instructions may mainly update control flow and do not need to write back to ordinary general-purpose registers.

6. Overview of the Five-Stage Instruction Cycle

Below is the classic five-stage execution model:

flowchart TD
    A["IF: Instruction Fetch<br/>Fetch machine instruction"] --> B["ID: Instruction Decode<br/>Parse opcode and operands"]
    B --> C["EX: Execute<br/>Complete calculation or address computation"]
    C --> D["MEM: Memory Access<br/>Read or write data"]
    D --> E["WB: Write Back<br/>Save execution result"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E9E4FA,stroke:#B7A5E0,color:#493B70
    style C fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style D fill:#FFF2D8,stroke:#E8C98A,color:#76551F
    style E fill:#F1EAF8,stroke:#C7B2DF,color:#59446E

This is the classic model that is easy to understand. Real processors may use more pipeline stages, or may merge or split multiple stages.

IV. Looking at the Complete Execution Process Through an ADD Instruction

After understanding the five stages in theory, let us use a concrete example to observe how the CPU executes an instruction.

Assume the initial register state is:

R1 = 0
R2 = 10
R3 = 20
PC = 0x1000

There is an instruction in the program:

```asm ADD R1, R2, R3 ```

It means:

```text R1 = R2 + R3 ```

Step 1: Instruction Fetch

The CPU fetches the instruction according to the PC:

```text PC = 0x1000 Instruction = ADD R1, R2, R3 ```

Assuming the instruction is 4 bytes long, under sequential execution the address of the next instruction is:

```text PC = 0x1004 ```

The PC update here is a conceptual sequential-execution model; a real processor may predict and fetch subsequent instructions ahead of time.

Step 2: Decode

The CPU identifies:

```text Opcode = ADD Source1 = R2 Source2 = R3 Destination = R1 ```

Read the registers:

```text R2 = 10 R3 = 20 ```

Ready to perform the addition.

Step 3: Execute

The ALU completes:

```text 10 + 20 = 30 ```

Producing the result:

```text Result = 30 ```

Step 4: Memory Access

This ADD instruction does not need to read from or write to data memory.

Therefore, in the classic five-stage pipeline, the MEM stage performs no actual data memory access.

Step 5: Write Back

Write the result into the destination register:

```text R1 = 30 ```

Final register state:

Register Before Execution After Execution
R1 0 30
R2 10 10
R3 20 20
PC 0x1000 0x1004 (sequential-execution model)

The complete process:

```mermaid flowchart TD A["Initial state
R2=10, R3=20
PC=0x1000"] --> B["Fetch
Read ADD R1,R2,R3"] B --> C["Decode
Identify ADD and register numbers"] C --> D["Read operands
R2=10, R3=20"] D --> E["ALU executes
10+20=30"] E --> F["Memory stage
No data memory access needed"] F --> G["Write back
R1=30"] G --> H["Prepare next instruction
Sequential address is 0x1004"] style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976 style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976 style C fill:#E9E4FA,stroke:#B7A5E0,color:#493B70 style D fill:#DCEFE5,stroke:#8EBFA5,color:#24563F style E fill:#DCEFE5,stroke:#8EBFA5,color:#24563F style F fill:#FFF2D8,stroke:#E8C98A,color:#76551F style G fill:#F1EAF8,stroke:#C7B2DF,color:#59446E style H fill:#E0F0FE,stroke:#93BCE8,color:#1E4976 ```

This example reveals an important fact:

Executing an instruction is not simply having the ALU perform an operation; it requires the control unit, registers, datapath, and execution units to work together.

V. How Does the Execution Process Differ Between Different Types of Instructions?

The five-stage model is a general description, but the exact execution path is not entirely the same for different instructions.

1. Arithmetic Instructions

For example:

```asm ADD R1, R2, R3 SUB R4, R5, R6 ```

Typical process:

  • IF: instruction fetch.
  • ID: decode and read operands.
  • EX: perform the arithmetic operation.
  • MEM: usually no data memory access is needed.
  • WB: write back to the register.

2. Load Instruction LOAD

For example:

```asm LOAD R1, [R2 + 8] ```

Assume:

```text R2 = 0x2000 Memory[0x2008] = 100 ```

Execution process:

  1. Fetch the instruction and identify it as LOAD.
  2. Read R2.
  3. Compute the effective address 0x2008.
  4. Access the data cache or the memory system.
  5. Write the loaded data 100 into R1.
```mermaid flowchart TD A["Fetch the LOAD instruction"] --> B["Decode<br/>read R2"] B --> C["Compute effective address<br/>0x2000+8=0x2008"] C --> D["Access the data cache"] D --> E{"Cache hit?"} E -->|Yes| F["Obtain the data directly from cache"] E -->|No| G["Fetch from the next-level cache or memory"] G --> H["Data returned"] F --> I["Write back to R1"] H --> I style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976 style B fill:#E9E4FA,stroke:#B7A5E0,color:#493B70 style C fill:#DCEFE5,stroke:#8EBFA5,color:#24563F style D fill:#FFF2D8,stroke:#E8C98A,color:#76551F style E fill:#F1EAF8,stroke:#C7B2DF,color:#59446E style F fill:#DCEFE5,stroke:#8EBFA5,color:#24563F style G fill:#FCE8E8,stroke:#DDA5A5,color:#783D3D style H fill:#E0F0FE,stroke:#93BCE8,color:#1E4976 style I fill:#E9E4FA,stroke:#B7A5E0,color:#493B70 ```

Note: on a Cache Miss, the CPU does not necessarily access DRAM directly; it may first access a lower-level cache.

3. The store instruction STORE

For example:

```asm STORE [R2 + 8], R1 ```

Assume:

```text R2 = 0x2000 R1 = 100 ```

Execution process:

  1. Fetch the instruction.
  2. Decode.
  3. Read R2 and R1.
  4. Compute the effective address 0x2008.
  5. Commit the data 100 to the memory system.

In modern CPUs, a write may first enter the Store Buffer and then be handled by cache coherence and the memory subsystem.

Therefore, an instruction finishing execution and the data finally reaching DRAM are not the same thing.

4. The branch instruction BRANCH

Branch instructions change the execution path of the program.

For example:

```asm BEQ R1, R2, TARGET ```

The meaning is:

```text If R1 == R2, jump to TARGET Otherwise continue with sequential execution ```

The CPU needs to:

  1. Fetch the instruction.
  2. Decode and read the operands.
  3. Evaluate the branch condition.
  4. Determine the target address.
  5. Update the address for subsequent instruction fetches.
```mermaid flowchart TD A["Fetch the branch instruction"] --> B["Decode<br/>read R1, R2"] B --> C["Compare the two operands"] C --> D{"R1 == R2?"} D -->|Yes| E["Select the branch target address"] D -->|No| F["Select the sequential execution address"] E --> G["Update the control flow"] F --> G G --> H["Continue fetching instructions"] style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976 style B fill:#E9E4FA,stroke:#B7A5E0,color:#493B70 style C fill:#DCEFE5,stroke:#8EBFA5,color:#24563F style D fill:#FFF2D8,stroke:#E8C98A,color:#76551F style E fill:#DCEFE5,stroke:#8EBFA5,color:#24563F style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976 style G fill:#F1EAF8,stroke:#C7B2DF,color:#59446E style H fill:#E0F0FE,stroke:#93BCE8,color:#1E4976 ```

Branch instructions are one of the important factors affecting CPU performance, because they may change the instruction stream that has already been prefetched.

6. Why does a CPU need a clock? What is the relationship between instruction execution and clock cycles?

The various components of a CPU need to work together at a certain rhythm.

This rhythm is usually provided by a clock signal.

The clock signal changes periodically at a fixed frequency, and the synchronous logic inside the CPU advances its state on clock edges.

1. Clock frequency

The CPU clock frequency indicates how many clock cycles occur per second.

For example:

3 GHz = approximately 3 billion clock cycles per second

The duration of one clock cycle is:

T=\frac{1}{f}

Where:

  • T: clock period.
  • f: clock frequency.

When the CPU frequency is 3 GHz:

T=\frac{1}{3\times10^9} \approx 0.333\text{ ns}

That is, one clock cycle is approximately 0.333 nanoseconds.

2. The instruction cycle is not equal to the clock cycle

This is a very important concept.

Concept Meaning
Clock cycle The time required for the clock signal to complete one full cycle
Instruction cycle The complete process involved in executing one instruction
CPI The average number of clock cycles consumed per instruction

In a simple non-pipelined model, an instruction may require multiple clock cycles to complete.

For example:

Instruction fetch: 1 cycle
Decode: 1 cycle
Execute: 1 cycle
Memory access: 1 cycle
Write back: 1 cycle

Then this instruction requires in total:

5 clock cycles

But this is only a teaching model and does not mean that all real CPUs use this fixed timing.

Modern processors may use:

  • Multi-stage pipelines.
  • Parallel execution of multiple instructions.
  • Superscalar execution.
  • Out-of-order execution.
  • Dynamic scheduling.
  • Speculative execution.

Therefore, the actual execution cycle of an instruction can vary greatly.

3. CPU performance and CPI

The total number of clock cycles required for a CPU to execute a program can be estimated with the following formula:

CPU\ Cycles=Instruction\ Count\times CPI

The execution time is:

CPU\ Time=\frac{Instruction\ Count\times CPI}{Clock\ Rate}

For example:

Instruction count: 1 billion
Average CPI: 2
CPU frequency: 2 GHz

Then:

CPU\ Time=\frac{10^9\times2}{2\times10^9}=1s

This means that under these idealized assumptions, the program takes about 1 second.

Note that CPI is an average over the course of program execution and does not mean that every instruction consumes exactly the same number of clock cycles.

7. Why don't modern CPUs execute one instruction to completion before executing the next?

If a CPU had to strictly complete all stages of one instruction before starting the next, different hardware components could end up with a lot of idle time.

For example:

  • When the current instruction is in the EX stage, the instruction fetch unit may be idle.
  • When the current instruction is in the MEM stage, the decode unit may be idle.

To improve hardware utilization, modern CPUs introduce pipeline technology.

1. What is an instruction pipeline?

An instruction pipeline splits instruction execution into multiple stages, allowing multiple instructions to be in different stages at the same time.

It is similar to a factory assembly line:

  • The first instruction is being executed.
  • The second instruction is being decoded.
  • The third instruction is being fetched.

Multiple stages can work simultaneously.

Suppose there are three instructions:

ADD R1, R2, R3
SUB R4, R5, R6
AND R7, R8, R9

In an ideal five-stage pipeline, the execution process can be represented as:

flowchart TD
    A["Cycle 1<br/>I1: IF"] --> B["Cycle 2<br/>I1: ID<br/>I2: IF"]
    B --> C["Cycle 3<br/>I1: EX<br/>I2: ID<br/>I3: IF"]
    C --> D["Cycle 4<br/>I1: MEM<br/>I2: EX<br/>I3: ID"]
    D --> E["Cycle 5<br/>I1: WB<br/>I2: MEM<br/>I3: EX"]
    E --> F["Cycle 6<br/>I2: WB<br/>I3: MEM"]
    F --> G["Cycle 7<br/>I3: WB"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E9E4FA,stroke:#B7A5E0,color:#493B70
    style C fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style D fill:#FFF2D8,stroke:#E8C98A,color:#76551F
    style E fill:#F1EAF8,stroke:#C7B2DF,color:#59446E
    style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style G fill:#DCEFE5,stroke:#8EBFA5,color:#24563F

From this process, we can see:

  • The first instruction needs to go through five stages.
  • The second instruction can begin fetching while the first instruction is being decoded.
  • The third instruction can continue entering the pipeline.

Ideally, once the pipeline is filled, one instruction can potentially complete in every clock cycle.

2. What does pipelining improve?

What pipelining mainly improves is instruction throughput.

Two concepts need to be distinguished:

Latency

The time required for a single instruction from start to completion.

Throughput

How many instructions can be completed per unit of time.

In an ideal five-stage pipeline:

  • A single instruction still needs to go through five stages.
  • Once the pipeline is filled, in theory one instruction can complete per cycle.

Therefore, pipelining mainly improves throughput; it does not mean the latency of a single instruction is necessarily reduced.

3. The pipeline is not always smooth

In real programs, instructions have dependencies on one another, and the pipeline may encounter conflicts.

Common pipeline hazards include:

Type Description Typical Cause
Structural hazard Multiple instructions contend for the same hardware resource Insufficient resources
Data hazard The current instruction depends on the result of a previous instruction The data is not yet ready
Control hazard The address of the next instruction is not yet certain Conditional branches, jumps

Data hazard example

ADD R1, R2, R3
SUB R4, R1, R5

The second instruction needs to read R1.

But the first instruction may not yet have written back its result.

This creates a data dependency.

Common solutions include:

  • Data forwarding.
  • Pipeline stall.
  • Instruction scheduling.
  • Register renaming and dynamic scheduling.

Control hazard example

CMP R1, R2
BEQ TARGET

Before the branch condition is determined, the CPU does not necessarily know which instruction should be executed next.