davidbrenner / nand2tetris

Implementation of a general purpose computer and OS built from first principles.
18 stars 10 forks source link

Can't understand your asm #1

Closed bitslooper closed 8 years ago

bitslooper commented 8 years ago

Sorry for disturbing you. I am studying this course by myself,but I have a somthing trouble in chapter 4 fill.asm. Like : (END) @R0 M=M+1 D=M Can you explain this asm file in detial?

davidbrenner commented 8 years ago

So, here's a fairly detailed response. In general, when learning assembly, I find it best to start by clearly commenting next to each line what it is doing. Then, once you understand every line, place that in the context of what the actual goal of the program/procedure is.

In the hack language, @ is a command to store the specified value into register A.

A is an address and data register, D is a a data register, M is a memory location, R0 is the first input to the program, (END) is a label.

This code snippet: (END)

This is a label that associates END with the address of this line of code. This is useful so you can branch to this address.

@R0 stores the program input address, R0, into A. For the purposes of this program, it is being used as the screen location counter. A is the address used for accessing the memory data stored at that address. The command in the hack language to access the data at address A from memory is M.

M=M+1 increments the value of the data at address A, which is the screen location counter.

D=M assigns that value, M, to register D.

@KBD

Stores the value of the keyboard IO address into register A

D=D-A

Subtract D from A, storing the result to D. In the bigger picture, this is setting up the comparison of the screen location counter to the address of the keyboard. This is probably the trickiest part of the program. It's checking to see if the screen location counter should be reset. As noted in the book, "The symbols SCREEN and KBD are predefined to refer to RAM addresses 16384 (0x4000) and 24576 (0x6000), respectively, which are the base addresses of the screen and keyboard memory maps."

@SCREENLOOP

Load the address of the label SCREENLOOP into A.

D;JNE

If D !=0, jump to the address in A (which is SCREENLOOP, which would mean to loop again).

@LOOP

Load the address of the label loop into A

D;JEQ

If D==0, jump to the address in A (which is loop, so start over at the beginning of the screen).

To put it all into context, this part is incrementing the screen location counter, checking if the screen is full and the counter should be reset, then jumping to the proper label based on that.

One final note: You'll get much more out of the nand2tetris if you only use existing solutions for comparison AFTER you have implemented a solution. There should be enough in the book chapters for you to figure out a solution without having to look at someone else's.

bitslooper commented 8 years ago

Wow! So clearly! Thank you !