NAND2Tetris Note 05 - Hack Assembly Language
The “Hack” computer built during this course has its own instruction set consisting of two instructions: the A-command and the C-command.
Registers
A
-> address. Used to access memory
D
-> General purpose data register
M
-> Psuedo register that actually accesses RAM[A]
A-instruction
Denoted as @<a>
where a
is a positive number, this instruction loads the specified literal into the A
(or address) register. This is encoded as:
0 <value (15 bits)>
C-instruction
The c-command has the format: dest = comp; jmp
, where dest
is the destination (if any), comp
is the computation to be performed and jmp
is a jumpy instruction. This is encoded as the following in a 16-bit instruction:
111 a c1 c2 c3 c4 c5 c6 d1 d2 d3 j1 j2 j3 ^ denotes “C”
a through c6 defines the computation to be performed as inputs to the ALU. There is a table describing every operation allowed here. d1 d2 d3 defines the destination of the computation (or 0 0 0 for null), j1 j2 j3 reperesents a jump instruction (conditional, uncondtional, null etc.)
I/O
I/O is performed by writing/reading from specific memory addresses. Display on the screen is accomplished by writing to 8K 16-bit registers starting at address 16384
. Each bit represents a pixel in a 256x512 matrix stored in row-major form.
For pixel at (row, col): 32*row + col/16 -> word index col % 16 -> bit index within word
The keyboard value is represented by a single 16-bit value at the address 24576
.
Assembly language
R1-R15 are built-in symbols for addresses from 1-15. This helps remove confusion between literals and addresses to some extent when using the A instruction. SCREEN and KBD and I/O base addresses.
Labels
Labels can be specified as (LABEL). This can be used as jump destinations. Example:
// Infinite loop
(END)
@END
0;JMP
Variables
@
Automatically uses an available memory address as long as there is no corresponding label. Allocated from address 16 onward.