Memory and processor

The processor and the fetch-decode-execute cycle

The conductor

The processor (CPU) is the circuit that executes a program, that is, a sequence of instructions stored in memory. It contains a computing unit (the ALU, which adds, compares, applies logic gates), a few fast registers for its working values, and a control unit that orchestrates everything. A special register, the program counter (PC), holds the address of the next instruction to execute.

The datapath

Simplified diagram of a processor:

   +-----------+       bus        +-----------+
   |  MEMORY   |<--------------- >|   CPU     |
   | (instr. + |                  |           |
   |  data)    |    +-------------+-----------+
   +-----------+    | PC (address of next instr.)
                    | Registers  (working values)
                    | ALU        (compute: + - AND OR comparison)
                    | Control unit (decodes and drives)
                    +-------------------------

(the bus carries addresses and data between memory and the CPU)

The three-step cycle

The processor endlessly repeats the same cycle, called fetch-decode-execute:

1. FETCH   (load)     : read from memory the instruction at the PC address,
                        then advance the PC to the next instruction.
2. DECODE  (decode)   : the control unit interprets the instruction's bits
                        (which operation? on which registers?).
3. EXECUTE (execute)  : the ALU (or memory) performs the requested operation,
                        the result is stored in a register.

   -> then start again with the next FETCH, billions of times per second

It all comes back to the initial building blocks

What is fascinating is that the ALU is nothing more than a large assembly of the gates and adders from the first chapter, and that registers are just rows of flip-flops. An entire processor is, at bottom, nothing but a gigantic stack of AND, OR, NOT gates and flip-flops, paced by a clock.

Classic pitfall

In memory, an instruction and a piece of data are both just sequences of bits: nothing physically distinguishes them. It is the job of the PC and the fetch-decode-execute cycle to know that, at a given moment, an instruction is being read. Mixing the two up, or losing track of the PC, is exactly what makes a badly written program crash.