简体   繁体   中英

MIPS branch instead of jump

What is the reason for using a branch with a predetermined condition, such as this:

beq $0, $0, TEST

Instead of just using a jump like this?

j TEST

Branches are used to test for conditions, but in this case, the branch has been used with a condition that will always be true. So why use it over a jump? Is it somehow faster?

I came across this answer , but I don't know if it is indeed the correct answer to my question because I don't know anything about relocation yet.

The J instruction is encoded as follows:

----------------------------
| opcode |   instr_index   |
----------------------------

instr_index is the least significant 28 bits of the target address, shifted right by 2 to give you a 26-bit value. And the address you'll end up jumping to is (PC & 0xF0000000) | (instr_index << 2) (PC & 0xF0000000) | (instr_index << 2)

The BEQ variant is encoded as follows:

-----------------------------
| opcode | 0 | 0 |  offset  |
-----------------------------

And the address you'll end up branching to is PC + sign_extend(offset << 2) .

(Note, in both cases PC is the address of the instruction immediately after the branch/jump instruction, not the branch/jump instruction itself).

Now, let's say that you have the following code:

main:
j foo
nop
foo:

And that this code is originally intended to be loaded at address 0x00400024 . The address of foo will then be 0x0040002c , and the J instruction will be encoded as (2 << 26) | (0x0040002c >> 2) (2 << 26) | (0x0040002c >> 2) = 0x0810000b .

But then you decide that you want to relocate this code (copy it to some other location in memory and execute it at that location). Let's say that your code is now executing at 0x00410000 . In this case we would want the J instruction to jump to 0x00410008 , but it will still be jumping to 0x0040002c ( (0x00410004 & 0xF0000000) | (0x010000b << 2) = 0x0040002c ).

If on the other hand you had used BEQ you would have the instruction word 0x10000001 ( (4 << 26) | (4 >> 2) ). Even if the code is relocated you will still end up branching to the correct address: 0x00410004 + (1 << 2) = 0x00410008 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM