RISC-V J, JAL, JR, JALR

From the web.

Introduction

In computer architecture and assembly language programming, "j," "jal," "jr," and "jalr" are commonly used instructions. Here's an explanation of when and how to use each of them:


  1. J (Jump):
    • The "j" instruction is used to perform an unconditional jump to a specified memory address.
    • It transfers the program's control to the target address, which is specified in the instruction itself.
    • The target address is usually calculated by adding an immediate value or offset to the program counter (PC) value.
    • "j" is typically used for implementing loops, conditional statements, or for performing a non-sequential transfer of control within a program.

  2. JAL (Jump and Link):
    • The "jal" instruction also performs an unconditional jump like "j," but it additionally stores the return address in a register.
    • The return address is the address of the instruction immediately following the "jal" instruction.
    • "jal" is commonly used for implementing procedure calls and function returns.
    • It allows a subroutine to jump to a target address and then return back to the original caller by using the stored return address.

  3. JR (Jump Register):
    • The "jr" instruction is used to perform an unconditional jump to an address specified in a register.
    • Instead of specifying the target address directly in the instruction, it uses a register (usually one of the general-purpose registers) to hold the address.
    • "jr" is typically used for implementing function returns when the return address is stored in a register.
    • It transfers the control to the address stored in the specified register.

  4. JALR (Jump and Link Register):
    • The "jalr" instruction combines the functionalities of "jal" and "jr."
    • It performs an unconditional jump to an address specified in a register and stores the return address in another register.
    • Similar to "jr," it is often used for function returns when the return address is stored in a register.
    • Additionally, "jalr" can be used for implementing other types of indirect jumps or subroutine calls.

The choice of which instruction to use depends on the specific requirements of your program and the target architecture. "j" and "jal" are typically used for direct unconditional jumps, while "jr" and "jalr" are used when the target address is stored in a register.