Program Counter in ARM Processor
In x86 architecture, as we all know, the program counter register (actually called the instruction pointer in x86, same thing with a different name) always points to the next instruction to be executed during normal program flow (i.e. without branching). Well, this is not the case for a 32-bit ARM processor. In 32-bit ARM architecture, instead of pointing to the next intruction to be executed, the PC always points to the next instruction to be fetched. This means that the PC value of an ARM instruction is its address plus 8 due to a legacy of the three stage pipeline of the original ARM1 processor as illustrated in the picture below. We can see that when the first MOV instruction is being executed, the third MOV instruction whose address is the current PC value is being fetched.
To see this in real code, we can examine the machine code of the B instruction which is used for branching. The following is the disassembly of a piece of ARM assembler code containing the B instruction: b 0x10058 and its machine code eafffffe in hexadecimal. 0x10058 is the address of the target instruction, i.e. the instruction that the processor is about to jump to.
0x00010058 <+4>: eafffffe b 0x10058 <_start+4>
0x0001005C <+8>: ...
0x00010060 <+10>: ...
In this case it simply branches to itself which effectively causes the program to stop there forever. The picture below shows the encoding of the B instruction.
Now when the processor executes a branch instruction, it uses the current PC value to create the address of the target instruction using the following formula:
\[address\ of\ the\ target\ instruction = PC + imm24 << 2.\]For our case here, the imm24 field equals to fffffe which is the 2’s complement of -2. Shifting this number to the left by 2 bits effectively multipies it by 4 which gives us -8. Then -8 is added to the current PC value 0x00010060 to give our target instruction’s address. By the way, the imm24 << 2 part is the offset from the current PC value to the target instruction. This method of calculating instruction’s address is called PC-relative addressing.
Enjoy Reading This Article?
Here are some more articles you might like to read next: