nand2tetris

Nand to Tetris how to compile "pop this 2" into asm


I know how to pop a value from the stack to put it in D

@SP
M=M-1
A=M
D=M

and I know how to select the memory location "this 2"

@2
D=A
THIS
A=A+D

The problem is that I am using D in both steps so obviously just using

M=D will not have the desired outcome. I would neeed a second register to hold some value for later on I guess or am I missing something here?


Solution

  • In these situations, you will have to use memory locations as temporary registers. Note that just as @SP is predefined for you, so are some other temporary memory locations like R0, THIS, THAT, etc.

    So usually it is best to write your programs as as series of isolated code nuggets that do things like "POP into THIS", "ADD THAT to THIS", "MOVE THAT into R15", etc. Include a comment that explains what the nugget does. It will make debugging a lot easier.

    One way to think of it is that the actual HACK instructions are actually microcode, and the larger nuggets are the real machine instructions.

    Later on, should you so desire, you can see if you can merge pairs of these instructions (for example, if the first one ends by storing a value in location X, and the next one immediately loads it again, you can usually omit the load, and sometimes the store as well). However, such cleverness can bite you if you are not careful, so it is best to get something working that is easier to understand, and then try optimizing it.

    Have fun!