简体   繁体   English

正确的MIPS代码循环?

[英]Correct MIPS code for loop?

I'm trying to code the MIPS code equivalent of this high level language code: 我正在尝试编写与此高级语言代码等效的MIPS代码:

i = 0;
n = str2; //supplied by user from console
while(i < n) {
    System.out.println(str1); //str1 is supplied by user from console
    i++;
}
System.exit(0);

This is my MIPS code: 这是我的MIPS代码:

.data
str1: .asciiz "Enter the first integer: "
str2: .asciiz "Enter the second integer: "
newline: .asciiz "\n"

.text       # instructions follow this line 
main:       # indicates start of code (first instruction to execute)

    add $s0,$zero, $zero        # $s0 = 0
    add $s1, $zero, str2       # $s1 = 0
    slt $t0, $s0, $s1
    beq $t0, $zero, Exit
    li  $v0, 1           # load appropriate system call code into register $v0;
                        # code for printing integer is 1
    move    $a0, str1    # move integer to be printed into $a0:  $a0 = str1
    syscall 
    addi $s0, $s0, 1      # $s0++

    j loop              #jump back to loop
Exit: nop

I'm trying to print the 1st number the amount of times the value of the 2nd number is. 我正在尝试将第一个数字打印第二个数字的值的次数。 Example: 1st number: 2, 2nd number: 4, so print 2 four times 示例:第一个数字:2,第二个数字:4,因此打印2次四次

Your code is missing a "loop" label. 您的代码缺少“循环”标签。 I'm going to guess that it should go above the first "add". 我猜想它应该超过第一个“添加”。

You should be using the "u" form of addition and subtraction instructions. 您应该使用“ u”形式的加减法指令。 That is, "addu" instead of "add", and "addiu" instead of "addi". 也就是说,用“ addu”代替“ add”,用“ addiu”代替“ addi”。 This is because "add" and "addi" will crash on overflow instead of wrap. 这是因为“ add”和“ addi”将在溢出而不是包装时崩溃。 Java does not crash on integer overflow, and you wanted the MIPS equivalent of the Java code. Java不会在整数溢出时崩溃,因此您需要与Java代码等效的MIPS。

Instead of literally "str1" and "str2", the MIPS code should have the names of the registers into which the user-specified numbers were loaded. MIPS代码应该具有加载用户指定编号的寄存器的名称,而不是字面意义上的“ str1”和“ str2”。

"move $reg1, $reg2" is equivalent to "addu $reg1, $zero, $reg2". “ move $ reg1,$ reg2”等效于“ addu $ reg1,$ zero,$ reg2”。 In fact, the "move" instruction does not actually exist, and is actually implemented as macro for "addu" with register $zero by the assembler. 实际上,“ move”指令实际上并不存在,实际上是由汇编器实现为“ addu”的宏,其寄存器为$零。

Also, are you using an assembler that automatically handles reordering? 另外,您使用的汇编程序会自动处理重新排序吗? I'm curious whether your assembler handles the MIPS delay slot for you, or whether you need to put stuff in the delay slot of branches yourself. 我很好奇您的汇编程序是为您处理MIPS延迟槽,还是需要自己将内容放入分支的延迟槽中。 This can change how you need to code your loop. 这可以更改您对循环进行编码的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM