yeolyi.comSeongyeol's CS

Moving Data

For now, the machine only does LDI, putting the number written in an instruction into a register. But there are only four registers, R0~R3, so they can hold at most four values, and anything beyond that has to be kept in memory. So every time we compute, we need to bring values from memory into registers, and write the results back to memory.

Moving instructions

Let’s start with instructions that go between memory and registers.

Addr is a memory address. Using all of the last 4 bits for the address leaves no room to write a register, so both always use R0.

But LOAD always brings the value into R0, so loading the next value overwrites the previous one. Before that, we need to be able to move R0’s value to another register.

Rd is the receiving register (destination), and Rs is the giving register (source). LDI is written in the same form, LDI Rd, Imm, where Imm is the immediate from machine code.

Let’s number the three new jobs too. LOAD and STORE write a memory address in the last 4 bits, so they go in kind 10 as 1000 and 1001. MOVE writes two registers in the last 4 bits, so it goes in kind 00 as 0000.

Job
Address
Memory
010
120
20
30
Registers
R00
R10
R20
R30

  1. LOAD 1 is written. Press the button to run it. The 20 in slot 1 goes into R0.
  2. Change the bits to 1001 0010 and run STORE 2. R0’s value is written into slot 2.
  3. With 0000 01 00, that is MOVE R1, R0, move R0’s value into R1.

Example: clearing memory slots

Let’s use all four instructions together. This program moves the numbers in memory slots 0 and 1 into R1 and R2, then clears those slots to 0. LOAD only brings values into R0, so we MOVE each one out after loading it, and to clear a slot we put 0 into R0 with LDI and write it with STORE.

0LOAD 0
1MOVE R1, R0
2LOAD 1
3MOVE R2, R0
4LDI R0, 0
5STORE 0
6STORE 1
Memory
010
120
20
30
Registers
R00
R10
R20
R30

Runs from address 0.

Press Next to run one line at a time. The highlighted cells are the ones that just changed.

Wrapping up

We’ve decided how to write the instructions, but the machine from machine code doesn’t look at the job number, so it does LDI whatever we write. In the next post, let’s make the machine do different jobs depending on the job number.

Challenge

We want to swap the values in memory slots 5 and 6. We can use only LOAD, STORE, LDI, and MOVE, and we're free to use registers R0–R3 and other memory slots. What is the minimum number of instructions? Answer with a number.