我如何知道在 MIPS 程序中使用哪些寄存器

How do I know which registers to use in a MIPS Program

我一直在努力学习 MIPS 汇编语言,但我很难知道在不同情况下应该使用哪些寄存器。比如我什么时候使用 $v0 、 $a0 或 $t1...

当你不使用任何别人写的代码,包括系统调用,你可以随意使用这些寄存器,前提是$at是保留给汇编程序,并且 $rajal/jalr 隐式使用。

非常不可能不使用任何系统调用或任何其他人编写的代码。
为了让编译器和人类在不查看代码的情况下使用例程,专家之间建立了一个约定。
它被称为应用程序二进制接口 (ABI) 和 MIPS got one too

ABI 规定了寄存器的使用方式。
您必须在以下任何时候尊重 ABI:

  1. 您已经使用了尊重 ABI 的代码。 在这种情况下,ABI 主要提供信息,它会告诉您函数在哪里期待参数以及它使用什么寄存器。
  2. 当您希望与需要 ABI 的代码或工具兼容时。
    当您编写一个稍后将提供给同事的函数时,最好按照 ABI 来编写它。这样他们已经习惯了惯例,他们会发现使用它很自然。
    如果您使用编译器,它肯定会编译符合 ABI 的源代码,因此它会期望任何人工生成的程序集都这样做。

引用 MIPS32 ABI 这些是寄存器的使用:

[=16=] ($zero) always has the value 0.

$at ($AT) temporary generally used by assembler. [Never user it]

.. ($v0–$v1) used for expression evaluations and to hold the integer and pointer type function return values. [$v0 is where integers functions put their return value]

.. ($a0–$a3) used for passing arguments to functions; values are not preserved across function calls. Additional arguments are passed on the stack, as described below. [This is where arguments go]

- ($t0–$t7) temporary registers used for expression evaluation; values are not preserved across function calls.

- ($s0–$s7) saved registers; values are preserved across function calls. [If you use these inside a function, save and restore them]

.. ($t8–$t9) temporary registers used for expression evaluations; values are not preserved across function calls. When calling position independent functions must contain the address of the called function.

- ($kt0–$kt1) used only by the operating system.

($gp) global pointer and context pointer. [Used by the compiler]

($sp) sp stack pointer. [Use this for the stack]

($s8) saved register (like s0-s7). [Save and restore this in functions if modified]

($ra) return address. The return address is the location to which a function should return control. [Set by jal/jalr]