I came across the instruction named jal and jalr while studying RISC-V assembly language.
I quite having hard times to understand the differences between jal and jalr.
jal x1, X
It seems that above code is meaning that jump to X, and save the return address which is normally PC+4 to the x1.
But after that, jalr x0, 0(x1)
comes.
0(x1)
means that going back to the address which is the return address, but what is x0?
Essentially x0 is zero in RISC-V, so why do we need x0?
What is the actual difference between those two instructions, jal
and jalr
?
The jump-and-link-register instruction ( JALR ) is the union of JAL and JR , meaning that it transfers control to the address in a specified register, and stores the return address in the register file. However, unlike JAL , JALR allows the programmer to specify the destination register of the return address.
The JAL instruction encodes two operands: a register, and an immediate.
These instructions can be simulated with a bgez or bltz respectively, followed by a jal , which means that both bgezal and bltzal should be classified as pseudo-instructions. However, both have opcodes assigned to them, hence they are classified as basic instructions.
The immediate can reach +/- 1 MB from the JAL itself. The immediate is shifted by one bit, the true LSB is always zero, so is not encoded. Because RISC V supports instructions in multiples of 16-bits (two bytes), we cannot assume the next-to-LSB is also zero, as it would be with MIPS (which has 32-bit instructions).
As we can see in specification (page 15), the main difference between jal
and jalr
is the address value encoding.
jal
use immediate (20bits) encoding for destination address and can jump +-1MiB range. And save the actual address + 4
in register rd
. (x1
in your example).
jalr
use indirect address (x1
in your example) plus a constant of 12bits (0 in your example). It save the actual address + 4
in register rd
too. In your example your set x0
as return address register because you «don't care».
When you return from subroutine for example, the return address is not usefull then we set x0
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With