Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of the PowerPC instruction `bcctr`?

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 to ctr" is not clear at all to me. The dual use off the register as a counter and as a destination address is especially confusing.

like image 441
John Källén Avatar asked Mar 05 '15 15:03

John Källén


1 Answers

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

like image 169
Jeremy Kerr Avatar answered Oct 22 '22 21:10

Jeremy Kerr