yeolyi.comSeongyeol's CS

Call and Return

Say we need to add 3 to R0 in two places in a program. Let’s write those instructions just once, in slot 4, and go there with JUMP. When it’s done, it has to go back to slot 2 the first time and slot 3 the second time.

0LDI R0, 1
1JUMP 4
2JUMP 4
3HALT
4ADDI R0, 3
5JUMP 2
R00

Runs from address 0.

Press Next. The returning JUMP 2 has a single fixed address, so it goes back to slot 2 the second time too, and loops without ever reaching HALT.

JUMP can’t come back once it goes, so we end up writing the same instructions again everywhere we use them.

Writing down the return address

We just need to write down the return address somewhere before going. On this machine, let’s write it in R3.

Let’s give CALL 1110 and RET 0011.

InstructionNumberRegister writeMemory writeSubtractKeep ZValue to writeRegister to writeRegister to readALU 2nd valueNext address
LDI01101000ImmediateRd··000(+1)
LOAD10001000MemoryR0··000(+1)
STORE10010100··R0·000(+1)
MOVE00001000RegisterRd··000(+1)
ADD00011001ALURdRdRs000(+1)
SUB00101011ALURdRdRs000(+1)
ADDI01001001ALURdRdImmediate000(+1)
SUBI01011011ALURdRdImmediate000(+1)
JUMP11000000····001(Address)
JZ11010000····010(Address if Z)
HALT11110000····011(Stay)
CALL11101000PC + 1R3··001(Address)
RET00110000··R3·100(R3)

Let’s fix the program from the start with CALL and RET.

0LDI R0, 1
1CALL 4
2CALL 4
3HALT
4ADDI R0, 3
5RET
R00
R30

Runs from address 0.

Press Next. Addresses 4–5 are written only once but run twice, and the program stops with R0 at 7.

The first RET returns to slot 2, and the second to slot 3. Wherever we call from, CALL writes that place into R3.

Attaching it to the machine

Let’s attach these to the machine from the jump post. CALL writes the PC’s +1 output into R3, and RET reads R3 and sends it to the PC’s LOAD. So we added a PC+1 input to the MUX in front of the register’s IN, an R3 input to the MUXes in front of the register numbers to write and read, and a MUX (PC SEL) in front of the PC’s LOAD. JUMP LOGIC turns on PC SEL along with J when the next address is R3.

Change CLK to 1 and back to 0, eight times over. The PC moves 0, 1, 4, 5, 2, 4, 5, 3, and the return addresses 2 and 3 are written into R3 in turn. At the end, R0 is 7.

Wrapping up

CALL writes the return address into R3 before going, and RET comes back to that address. Thanks to this, a group of instructions is written once and called from many places. We now have thirteen instructions. In the next post, let’s gather the instructions we’ve made.

Challenge

R3 holds only one return address. What happens when we run the program below, where the group at address 4 calls another group inside it?

Address 0: LDI R0, 0
Address 1: CALL 4
Address 2: HALT
Address 3: (empty)
Address 4: CALL 7
Address 5: ADDI R0, 1
Address 6: RET
Address 7: ADDI R0, 2
Address 8: RET