In the assembly post we named a data slot to make a variable.
But assembly is written one instruction per line, so even a single thought like
“put a into b” has to be spelled out as two lines through R0 (LOAD a,
STORE b). Could we just write b = a as we think it, and leave the spelling
out to a program?
A language written close to how people think is a high-level language, and a program that turns a high-level language into assembly is a compiler. C is a language used for programs that work directly with hardware, such as operating systems. In this part we go through C’s features one by one and build a compiler that turns them into the instructions of the hardware we have built so far.
One line of C becomes several lines of assembly, and variables pile up quickly. But memory has only 16 slots, too tight to hold a program and its variables together.
The reason it’s 16 lies in the instructions. An instruction is 8 bits, and the first 4 are the opcode, leaving only 4 bits, 0 to 15, for the address. So let’s widen instructions to 16 bits, two slots of memory, and give the whole second 8 bits to the address. An 8-bit address covers 0 to 255, so memory grows to 256 slots. One slot of memory is 8 bits, or 1 byte.
Let’s see how each of the three instruction layouts changes.
Address
A register and a number
Two registers
The top is the 8-bit instruction and the bottom the 16-bit one. Highlighted fields are wider or new, and dimmed fields are unused.
Addresses and numbers move to the second 8 bits and now range from 0 to 255.
LOAD and STORE always used R0 until now, but the spare room in the first 8 bits
can hold a register, so they can pick any register, as in LOAD R1, 13.
Instructions that use two registers would fit in the first 8 bits, but they still take 16 bits and leave the second 8 empty. If instructions had different lengths, the PC would sometimes move by 1 and sometimes by 2, and you’d have to read the first 8 bits to know where an instruction ends, which makes decoding a hassle. With every instruction at 16 bits, the PC always moves by 2.
Now that instructions are 16 bits, there’s plenty of room for new ones. As we translate C, we’ll run into jobs that are clumsy with today’s instructions, like adding numbers larger than 255, and each time we’ll add the instruction we need to the machine.
In the next post we’ll make variables in C.
A program of seven 16-bit instructions starts at address 0. Which instruction of the program does JUMP 10 point to? Answer with a number.