Published on

nand2tetris Series 01 - Implementing an Infinite Loop in Assembly

Authors
  • avatar
    Name
    Morphy Chan
    Twitter

The hack computer is a pseudo-machine implemented in the nand2tetris course, complete with its own instruction set and supporting software. This post demonstrates how to implement an infinite loop in hack computer assembly.

The infinite loop program is as follows, referenced from 1.

(END)
    @END
    0;JMP // Unconditional jump

The program is concise, consisting of 1 symbol and 2 instructions.

  1. First, (END) is a symbol, commonly seen in assembly. Jump instructions (JMP) need to specify the address of the next instruction to execute, but the exact address isn't known beforehand, so we use symbols:

Label symbols: These user-defined symbols, which serve to label destinations of goto commands, are declared by the pseudo-command ''(Xxx)''. This directive defines the symbol Xxx to refer to the instruction memory location holding the next command in the program.

(END) refers to the address of the instruction immediately following the symbol — in this case, the address of the @END instruction.

  1. Next is the @END instruction:

The A-instruction is used to set the A register to a 15-bit value... @value: Where value is either a non-negative decimal number or a symbol referring to such number

@ sets the value of the A register. Here the value is the symbol END, which, based on the symbol definition above, sets the A register to the address of this instruction itself.

  1. Finally, the JMP instruction jumps to the next instruction address:

The jump field of the C-instruction tells the computer what to do next. There are two possibilities: The computer should either fetch and execute the next instruction in the program, which is the default, or it should fetch and execute an instruction located elsewhere in the program. In the latter case, we assume that the A register has been previously set to the address to which we have to jump.

JMP always jumps to the address stored in the A register. Since the previous instruction set the A register to the address of @END, JMP always jumps back to @END, thus creating an infinite loop.

nand2tetris provides a CPU emulator that can execute hack computer assembly programs. Here's the program running:

infinite_loop

Figure 1: Infinite loop in nand2tetris

A few notes:

  • After the program is loaded and executed, there are no more symbols. The symbol (END) is replaced with the actual address of its next instruction — here, the address of @END is 0, so (END) is replaced with 0
  • @0 always sets the A register to 0; the A register value remains unchanged
  • JMP always jumps to the instruction at address 0, so the Program Counter (PC) continuously cycles through the instructions at addresses 0 and 1

Footnotes

  1. chapter 4