Topic 3: ARM
Part 4: Control Flow Instructions
Control Flow Instructions
This is the third category of ARM
instructions
Control flow typically involves some kind
of branch
2
Control Flow Instruction: BEQ
BEQ (branch if equal)
Usage: CMP R1, R2
BEQ L1
(says go to the statement labelled L1 if the
value in register R1 is the same as the
value in register R2)
3
BNE: Another control flow instruction
Stands for Branch if not equal
Usage: MOV r0, #0; initialize counter
LOOP
ADD r0, r0, #1;
CMP r0, #10; compare with limit
BNE LOOP ; repeat if not equal
….. ; else proceed
4
Exercise .. What are r1 and r0 at
the end ?
AREA Reset, CODE, READONLY
ENTRY
MOV r0, #0 ; initialize counter
MOV r1, #5
LOOP
ADD r0, r0, #1
CMP r0, #2
ADD r1, r1, r0
BNE LOOP
stop
B stop
5 END
Other control flow instructions
BPL ; Branch if result positive or zero
BMI ; Branch if result is negative
BCC ; Branch if arithmetic operation did not
give carry out (carry clear)
BCS; Branch if arithmetic operation gave
carry out (Branch if carry is set)
BGE; Branch if greater than or equal (signed
integer comparison)
6
Exercise: What are r0 and r1 ?
AREA Reset, CODE, READONLY
ENTRY
EOR r0, r0, r0 ; clear r0
EOR r1, r1, r1 ; clear r1
Loop
ADD r0, r0, #1
CMP r0, #0
BPL Looptest
ADD r0, r0, #-1
BNE Loop
Looptest
ADD r1, r1, #2
stop
B stop
7 END
Alternate way of writing control instructions
An unusual feature of the ARM instruction
set is that conditional execution applies
not only to branches but also to other
ARM instructions
This allows us to write compact code.
Example next
8
Example
CMP r0, #5
BEQ BYPASS ; if (r0 !=5)
ADD r1, r1, r0 ; r1 := r1 + r0 – r2
SUB r1, r1, r2
BYPASS: ….
can be replaced by:
CMP r0, #5
ADDNE r1, r1, r0
SUBNE r1, r1, r2
9
Unsigned vs. Signed Comparison
BLT (branch if less than) is used when we
want signed integer comparison
BLO (branch if lower) is used when we
want unsigned comparison
Illustration next
10
Example
Let register r0 hold a string of 32 1’s
Also, let register r1 hold the string 0000…. 1
(i.e., 31 0’s and a 1 as the LSB)
Suppose we have
CMP r0, r1
Which conditional branch is taken ?
BLO L1 ; unsigned branch
BLT L2 ; signed branch
BLT is taken ! How ?
Value in register r0 represents -1 (base
10) if it is an integer (signed) and
4,294,967,295 if it is an unsigned integer
Value in register r1 represents 1 in either
case
BLO is not taken to L1 since 4,294,967,295
>1
BLT is taken to L2 since -1 (base 10) < 1
(base 10)
B: Unconditional Branch
A simple ARM instruction that allows for
branching always is
B <label>
WHERE IS THIS USEFUL ?
13
Where is unconditional branch
useful ?
Consider an ARM sequence for
if (i == j) f = g + h; else f = g – h;
14
Code for
if (i == j) f = g + h; else f = g – h;
Assume f, g,h, i and j correspond to
registers r0, r1, r2, r3 and r4
- Write a program
15
Solution ..
Assume f, g,h, i and j correspond to
registers r0, r1, r2, r3 and r4. Then we
have
CMP r3, r4
BNE Label1
ADD r0, r1, r2
B Exit
Label1 SUB r0, r1, r2
Exit