Why do MIPS subroutines return by jr
while x86 return by using ret
?
Why isn't there any ret
instruction in MIPS?
Alternatively, why doesn't x86 use jr
?
In x86, the call instruction puts the return address in memory on the stack. In MIPS, the call instruction (jal
) puts the return address into a register.
In x86, the ret instruction removes the return address from the stack and branches to it. The MIPS philosophy doesn't combine separate steps into a single instruction. This simplifies the instruction set considerably. Removing a value from the stack and performing a branch are separate operations, requiring separate instructions. In the particular case of call/return, it also has the advantage that in a leaf function there is no need to write the return address to memory at all.
X86 has an equivalent of the jr instruction, jmp r/m32
, with the destination specified as a register. This instruction is not usually used for function return because then a separate instruction would be needed to pop the return address from the stack into a register (but I have written code that does exactly that, in special circumstances).