Tuesday, 17 January 2017

Unconditional branching


Unconditional branching on PowerPC instruction sets uses the I-Form instruction format:

I-Form instruction format

Bits 0-5
Opcode
Bits 6-29
Absolute or relative branch address
Bit 30
Absolute address bit -- If this field is set, the instruction is interpreted as an absolute address, otherwise it is interpreted as a relative address
Bit 31
Link bit -- If this field is set, the instruction sets the link register with the address of the next instruction
As mentioned earlier, adding the letter l onto a branch instruction causes the link bit to be set, so that the "return address" (the instruction after the branch) is stored in the link register. If you affix the letter a at the end (it comes after the l, if that is used), then the address specified is an absolute address (this is not often used in user-level code, because it limits the branch destinations too much).
Listing 2 illustrates unconditional branches, and then exits (enter as branch_example.s):
Listing 2. Unconditional branching examples
### ENTRY POINT DECLARATION ###
.section .opd, "aw"
.align 3
.globl _start
_start:
        .quad ._start, .TOC.@tocbase, 0

### PROGRAM CODE ###
.text
#branch to target t2
._start:
        b t2

t1:
#branch to target t3, setting the link register
        bl t3
#This is the instruction that it returns to
        b t4

t2:
#branch to target t1 as an absolute address
        ba t1

t3:
#branch to the address specified in the link register
#(i.e. the return address)
        blr

t4:
        li 0, 1
        li 3, 0
        sc
Assemble, link, and run it like this:
as -a64 branch_example.s -o branch_example.o
ld -melf64ppc branch_example.o -o branch_example
./branch_example

Notice that the targets for both b and ba are specified the same way in assembly language, despite the fact that they are coded differently in the instruction. The assembler and linker take care of converting the target address into a relative or absolute address for you.

No comments:

Post a Comment