I'm new to the PowerPC architecture and I'm looking at some disassembled code with the bcctr
instruction. Although the manual specifies how the bcctr
instruction works, it doesn't explain what it typically would be used for.
Can you come up with examples of such uses, and detail what rôle the ctr
register plays?
My best guess is that it is used for indirect branches (e.g. to implement calls to function pointers or vtables), but the purpose of
"decrement
ctr
register and then branch toctr
"
is not at all clear to me. The dual use of the register as a counter and as a destination address is especially confusing.
The bcctr
(and its unconditional variant, bctr
) is generally used for branches to a function pointer.
The Power ISA instruction set has two instructions¹ that are available for branching to an address in a register: blr
(branch to link register) and bctr
(branch to counter register). Using bctr
means we can preserve the link register.
In this case, there's nothing special about using the ctr register here - it's just the address that we branch to. There'll be a mtctr
instruction earlier in the stream, where we load an address into the ctr register.
You'll probably see bctrl
used too: this sets the link register to the current address + 4, then does a branch to the counter. This allows the call (through the function pointer) to return, by branching back to the link register.
¹: in non-privileged mode, at least