What does the program counter do?

I was browsing the architecture of a simple CPU but there is one thing a cannot understand. Why is there data from the ALU going to the program counter and what is that data for?

asked Mar 7, 2022 at 6:43 AdvilDuttay AdvilDuttay 61 1 1 silver badge 2 2 bronze badges

2 Answers 2

$\begingroup$

Since this is a simple CPU, it's almost certainly to compute branch targets. Branch instructions typically represent the location to branch to as a small signed number to add to the program counter. The reason for this is that conditional branches almost always occur within a procedure or function, so it makes sense to encode them as an offset, which uses fewer bits.

In "real" CPUs, another common use case is to support position-independent code.

answered Mar 7, 2022 at 7:14 23.1k 3 3 gold badges 45 45 silver badges 88 88 bronze badges

$\begingroup$ In your second paragraph, you mean to provide PC-relative addressing modes and/or address-generation into registers? That's not necessary to support PIC, but it helps efficiency. e.g. 32-bit x86 can only read the program counter by running a call instruction (which pushes a return address), then reading that memory (e.g. with pop into a register). This sucks a lot for PIC/PIE code: every function that accesses static data needs to find its own address and address the GOT relative to that, which is why x86-64 introduced RIP-relative addressing for data load/store, not just jumps/calls. $\endgroup$

Commented Mar 8, 2022 at 5:13

$\begingroup$ Many modern RISC ISAs have an instruction like adrp that sets a GP-integer register = PC + something, with page granularity so it can reach far (scaling the immediate offset). See What are the semantics of ADRP and ADRL instructions in ARM assembly? for details for AArch64. So that's a specific real-world example of what I think you're talking about in that 2nd paragraph. $\endgroup$