Assembly PC Relative Addressing Mode

2020-07-22 18:39发布

问题:

I am working on datapaths and have been trying to understand branch instructions.

So this is what I understand. In MIPS, every instruction is 32 bits. This is 4 bytes. So the next instruction would be four bytes away.

In terms of example, I say PC address is 128. My first issue is understanding what this 128 means. My current belief is that it is an index in the memory, so 128 refers to 128 bytes across in the memory. Therefore, in the datapath it always says to add 4 to the PC. Add 4 bits to the 128 bits makes 132, but this is actually 132 bytes across now (next instruction). This is the way I make sense of this.

In branch equals, say the offset is a binary number of 001. I know I must sign extend, so I would add the zeroes (I will omit for ease of reading). Then you shift left two, resulting in 100. What is the purpose of the shift? Does the offset actually represent bytes, and shifting left will represent bits? If so, adding this to the PC makes no sense to me. Because if PC refers to byte indeces, then adding the offset shifted left two would be adding the offset in number of bytes to PC that is in number of bytes. If PC 128 actually refers to 128 bits, so 32 bytes, then why do we only add 4 to it to get to the next instruction? When it says PC+4, does this actually mean adding 4 bytes?

My basic issue is with how PC relative addressing works, what the PC+4 means, and why offset is shifted by 2.

回答1:

Shifting left by n bits is the same thing as multiplying the number by 2n. Shifting left 2 bits multplies by 4.

If your branch offset is shifted left by 2, that means your branch offset operand is in whole instruction units, not bytes. So a branch instruction with an 8 operand means, jump 8 instructions, which is 32 bytes.

MIPS multiplies by 4 because instructions are always 32 bits. 32 bits is 4 bytes.

MIPS Instructions are guaranteed to begin at an address which is evenly divisible by 4. This means that the low two bits of the PC is guaranteed to be always zeros, so all branch offsets are guaranteed to have 00 in the low two bits. For this reason, there's no point storing the low two bits in a branch instruction. The MIPS designers were trying to maximize the range that branch instructions can reach.

PC means "Program Counter". The program counter is the address of the current instruction. PC+4 refers to the address 4 bytes past the current instruction.

Branch Offset

MIPS branch offsets, like most processors, are relative to the address of the instruction after the branch. A branch with an immediate operand of zero is a no-op, it branches to the instruction after the branch. A branch with a sign extended immediate operand of -1 branches back to the branch.

The branch target is at ((branch instruction address) + 4 + ((sign extended branch immediate operand) << 2)).