branch-instructions
Source: samek-embedded
Branch instructions
B.N(Branch) instruction modifies thePCregister so that it skips to a different instructionBLT.Nconditional branching- only modifies
PCif theNbit in theAPSRis set. - the instruction to jump to is encoded within the instruction itself:
0xFC = -4, so jump back 4 instructions, from0x8eto0x8a
- only modifies
- Branching results in pipeline delays –> solution e.g. loop unrolling
BL (branch and link)
BLsaves the address of the next instruction into theLRlink register .- The previous value of
LR(i.e. previous function return address) must also be saved somehow. - The previous return address is saved to the stack .
- The previous value of
- Example of a main function executing (branching off into) the
delaysubfunction:1 2 3 4 5int main(){ GPIO_PORTF_DATA_BITS_R[LED_RED] = LED_RED; delay(); GPIO_PORTF_DATA_BITS_R[LED_RED] = 0; }1
| Disassembly | Register | |
|---|---|---|
Before BL | ![]() | ![]() |
After BL | ![]() | ![]() |
Notes:
- After branching off into the subfunction
delay, the stack is expanded by 4 memory units, as can be seen in theSUB SP, SP, #0X4instruction.10xF0 - 0x4 = 0xEC - At the end of
delay(), the reverse occurs. The stack is shrunk by 4 memory units:ADD SP, SP, #0X4and points to0xF0again, just like beforedelay()was executed. - The return of the
delay()function is given by theBXbranch instruction . - It would be expected that, right after
BL,LRstores the instruction address0x94, but instead0x95is stored.- This is also at odds with the fact that the ARM instructions must be aligned at even addresses.
- This is a legacy behaviour explained in the
BXsection . - At the end of the subfunction (after executing
BX), thePCregister is indeed updated to the correct instruction0x94.
BX (branch and exchange)
- Performed upon return of a function.
- Sets
PCto the value ofLR.- However, not all bits of
LRare transferred toPC. - The least significant bit of
PCis always set to zero, as the return address must be even. - Therefore, the least significant bit of
LRis not used for addressing. - Instead, it is used as the instruction set exchange bit.
- If 1: processor switches to the THUMB instruction set.
- If 0: processor switches to the ARM instruction set.
- This behavour, however, moot in Cortex-M (no possibility to switch to ARM instructions), and is therefore just a legacy behaviour.
- However, not all bits of



