为什么我的汇编程序没有将 r1 设置为正确的值?

Why isn't my assembly program setting r1 to the correct value?

我正在LC3机器上写汇编程序

我的汇编程序是一个LC3程序,将R2和R3相乘并将结果存储在R1中。

这是我的源代码(带注释)

;Sets pc to this address at start of program 
.ORIG x3000
;R1 will store the result lets clear it(ANd with 0)
AND R1,R1,x0
;R2 will be multiplied by R3, let's clear both of them 
AND R2,R2,x0
AND R3,R3,x0
;Test case 4 * 3 = 12;
ADD R2,R2,4
ADD R3,R3,3
;Add to increment zone 
LOOP Add R1,R1,R2;
;Decrement the counter, in this case the 3 or R3
ADD R3,R3,x-1
BrP LOOP
HALT
.END

我的测试用例乘以 4 * 3。结果应该是 12,应该存储在 R1 中。然而,当我在我的 LC3 模拟器中 运行 这个程序时,这就是我得到的输出

R3 最后保持正确的值,但 R1 保持 -1...。有人看到我的代码有问题吗?我确保在开始时清除 R1,并继续将 R3 添加到 R1 并将结果存储到 R1,而本例中的计数器 R3 或 3 大于零。

HALT 只是用于停止机器的 TRAP 指令的 "pseudo-instruction"。

你可以这样写:

TRAP x25  ;HALT the machine

但是在这种情况下,您需要记住 TRAP 向量中的位置,在本例中为 x25。所以最好只使用 HALT 来代替。

其他常见的TRAP也有伪指令:INOUT

我假设您想将结果存储在某个地方。你可以这样做:

;Sets pc to this address at start of program 
.ORIG x3000
;R1 will store the result lets clear it(ANd with 0)
AND R1,R1,x0
;R2 will be multiplied by R3, let's clear both of them 
AND R2,R2,x0
AND R3,R3,x0
;Test case 4 * 3 = 12;
ADD R2,R2,4
ADD R3,R3,3
;Add to increment zone 
LOOP Add R1,R1,R2;
;Decrement the counter, in this case the 3 or R3
ADD R3,R3,x-1
BrP LOOP
ST R1, Result         ;STORE R1 at Result
HALT
Result .FILL x0000    ;this will be x000C=12h after execution
.END

--------------------编辑-------------------- --------

关于你的最后一个问题(在评论中):

If HALT stops my program, how will Reslt .FILL x0000 directive run then?

这更多是关于汇编程序如何工作的问题。

答案是因为:组装时间 != 执行时间

指令在组装时被考虑。

事实上,Assembly Time 由两步组成:

  1. 解析符号创建符号table
  2. 使用符号 table.
  3. 将指令转换为 "truly executable/machine code"

这是一种很常见的汇编器实现方式,LC3汇编器也不例外。