cpucpu-architectureprogram-counter

Program Counter incrementation


Does the Program Counter in a CPU need to incremented by 1 always. That's true when a jump instruction is detected it just point to that address. But otherwise, do we make Program Counters to increment by other numbers?

I want to know whether we can make Program Counters to increment by any number other than 1 or not.


Solution

  • After executing a (non-jump) instruction, the program counter needs to increment by the length of that instruction, so that it ends up pointing to the following instruction.

    On some architectures, all instructions have the same length - e.g. on ARM64 it's 4 bytes - so on such an architecture, the program counter would increment by 4 after each instruction. On others (such as x86), instructions have varying lengths, and so the process of decoding an instruction needs to also determine how long it was, so that the program counter can be incremented by the proper amount.

    The only way that an architecture would always increment its program counter by 1 would be if:

    However, something kind of similar happens on some architectures. Taking ARM64 as an example, it is byte-addressed, every instruction is 4 bytes long, and instructions must always be aligned to 4 bytes. So although the program counter is nominally a 64-bit register, the 2 low bits are always 0 (so that the value is always a multiple of 4). In that sense, instead of thinking of pc as a 64-bit register that increments by 4, you could think of it as a 62-bit register that increments by 1, which is then combined with two hard-wired zero bits (or equivalently, left-shifted by 2 bits) to determine the actual instruction fetch address.