Skip to content

nand2tetris系列01-实现无限循环汇编程序

  • by

hack computernand2tetris课程实现的一个pseudo-machine,包含了相应指令集和一系列支持的软件。本文介绍使用hack computer实现infinite loop的汇编程序。

infinite loop具体程序如下,参考1

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

程序很简洁,包含1个symbol和2条指令。

  1. 首先,(END)是一个symbol,在汇编中经常见到。在跳转指令(JMP)需要指定下一条执行指令的地址,但是具体的地址并不知道,因此需要借助于symbol:

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)指向的是紧跟在该symbol之后的下一条指令的地址,这里就是@END指令的地址。

  1. 接下来是@END指令

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

@指定A register的值,这里的值是symbol END,根据symbol的解释,实际上这里将A register的值设置为本条指令的地址。
3. 最后是JMP跳转指令,跳转指令就是跳转到下一条指令的地址

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 exe- cute 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总是跳转到A register的地址,由于上一条指令指定了A register的值为@END指令的地址,所以JMP总是会跳转到@END指令,因此实现了无线循环。

nand2tetris提供了可以执行hack computer汇编程序的CPU模拟器,运行程序。

一些说明:
– 在程序加载并执行以后,已经没有symbol了。Symbol (END)被替换为其下一条指令实际的地址,这里@END指令的地址为0,所以(END)被替换为了0
@0总是指定A reigster的值为0,A register的值没有改变
JMP总是跳转到地址为0的指令,进而PC Counter(PC)一直在循环执行地址为0和1的2条指令

Leave a Reply

Your email address will not be published. Required fields are marked *