Jump instruction in MIPS Assembly

前端 未结 2 1827
南方客
南方客 2020-12-18 00:40

Here is some MIPS assembly code I wrote to test the jump instruction:

addi $a0, $0, 1
j next
next:
j skip1
add $a0, $a0, $a0
skip1:
j skip2:
add $a0, $a0, $a         


        
相关标签:
2条回答
  • 2020-12-18 00:59

    Just look into a reference manual for more details about the opcode encoding.

    Short version: In a 32 bit instruction you can not include a 32-bit jump destination. The opcode uses 6 bits, which leaves 26 bits for the instruction. The target address is constructed by taking the first 4 bits of the address of the instruction following the j instruction, then 2 zero bits are appended to the 26 bits from the jump instruction operand. (As the instructions are 32 bits, alignment is useful and allows the omitting of the last two 0's.)

    To the backward jump: The addresses are absolute, NOT relative, so it only depends on the address of the jump instruction, whether it is a forward or a backward jump.

    EDIT: More detailed description: We have at address x jump instruction j. Let t represent the jump operand of j. t is 26 bit wide. The bit pattern of address of the next instruction is computed as follows:

    upper_6_bits_of(x+4),t,0,0
    

    So the jump is ALWAYS absolute. There are no relative jumps. when the result is smaller than x then it is a backward jump, when it is greater it is a forward jump (and if you want something stupid, you make it equal ;-).

    So let's look at the 5th jump of your example:

    The first 6 bits of the jump target are: 000000, because the upper 6 bits of the address of the instruction behind the jump are 000000.

    The next 26 bits are the lowest 26 bits of the jump instruction, that is 00000000000000000000001000

    The last 2 bits are: 00, because the got always appended.

    Together we have: 0000000000000000000000000000100000, which is hex 20. And at that address is exactly the label/instruction where the flow should continue.

    0 讨论(0)
  • 2020-12-18 01:10

    In MIPS, J is a J-type instruction:

    J-type instructions (Jumps)
    3    22
    1    65                        0
    +----+-------------------------+
    | op |         target          |
    +----+-------------------------+
    

    So we have a target that is 26-bits long. It gets combined with the PC of the next instruction as follows:

    I
    I+1 PC <- (PC & 0xf0000000) | (target << 2)
    

    It is shifted left 2 bits, since MIPS instructions (ignoring the MIPS16 extension) are 32-bits long, meaning they all start in an address whose lower 2 bits are zero.

    0 讨论(0)
提交回复
热议问题