Assembly Language Programming (7)BL,BX
Table of contents
Understanding BX
and BL
in ARM Assembly
In ARM assembly, BX
(Branch and Exchange) and BL
(Branch with Link) are essential for function calls and dynamic branching.
BL(Branch with Link)
What does BL
do?
Calls a subroutine (function).
Saves the return address in the Link Register (
LR
).Execution jumps to the function.
✅ Example: Using BL
to Call a Function
.global _start
_start:
MOV R0, #5 ; Store 5 in R0
MOV R1, #10 ; Store 10 in R1
BL add_func ; Call add_func (stores return address in LR)
MOV R3, #4 ; This executes after returning from add_func
add_func:
ADD R2, R0, R1 ; R2 = R0 + R1 (5 + 10 = 15)
BX LR ; Return to the caller (_start)
Execution Flow
BL add_func
saves the return address inLR
and jumps toadd_func
.The function executes
R2 = R0 + R1
.BX LR
returns to_start
, continuing execution fromMOV R3, #4
.
BX (Branch and Exchange)
What does BX
do?
Jumps to an address stored in a register.
Used for returning from functions (
BX LR
).Can switch between ARM and Thumb modes (based on the least significant bit of the address).
Can be used for dynamic function calls (
BX Rn
).
Example 1: Returning from a Function (BX LR
)
.global _start
_start:
MOV R0, #3
MOV R1, #7
BL multiply ; Calls function (stores return address in LR)
MOV R3, #4 ; Executes after returning from multiply
multiply:
MUL R2, R0, R1 ; R2 = R0 * R1 (3 * 7 = 21)
BX LR ; Return to caller (_start)
Execution Flow
BL multiply
stores return address inLR
and jumps tomultiply
.MUL
instruction multipliesR0
andR1
, storing the result inR2
.BX LR
returns to_start
, continuing execution withMOV R3, #4
.
Example 2: Dynamic Function Calls (BX Rn
)
.global _start
_start:
LDR R1, =func ; Load function address into R1
BX R1 ; Jump to function address in R1
func:
MOV R0, #42 ; Store 42 in R0
BX LR ; Return to caller
BX R1
jumps to the address stored inR1
.func
executes and returns viaBX LR
.This is useful for function pointers or dynamic branching.
Example 3: Mode Switching using BX
BX R0 ; Switch mode based on R0’s address LSB (0 = ARM mode, 1 = Thumb mode)
If R0’s least significant bit (LSB) is
1
, execution switches to Thumb mode.If R0’s LSB is
0
, execution remains in ARM mode.
Difference Between BX
and BL
Instruction | Purpose |
BL label | Calls a function (stores return address in LR ) |
BX LR | Returns from a function (jumps to the address in LR ) |
BX Rn | Jumps to the address in Rn (dynamic branching) |
✅ Summary
Use
BL function_name
to call a function (stores the return address inLR
).Use
BX LR
to return from a function (jumps to the saved return address).Use
BX Rn
for dynamic jumps (whenRn
contains a function address).BX
can switch between ARM and Thumb modes based on the least significant bit of the address.
Thus, BL
is for calling functions, and BX
is for returning or dynamic branching! 🚀