Assembly Language Programming(3) CPSR FLAGS

·

2 min read

✅ Code Explanation (ARMv7 Assembly)

.global _start
_start:
    MOV R0, #6      ; Store 6 in R0
    MOV R1, #7      ; Store 7 in R1
    SUBS R2, R0, R1 ; R2 = R0 - R1, updates CPSR flags

✅ Meaning of SUBS R2, R0, R1

  • SUB (Subtract operation): R2 = R0 - R1

  • S (Set flags): Updates CPSR (Current Program Status Register) based on the result.

  • Unlike SUB, which only performs subtraction, SUBS updates the CPSR flags accordingly.


✅ Relationship with CPSR (Current Program Status Register)

The CPSR stores status flags that reflect the result of the previous operation.

Major Flags in CPSR

BitFlagDescription
31N (Negative)Set to 1 if the result is negative
30Z (Zero)Set to 1 if the result is zero
29C (Carry/Borrow)Set to 1 if no borrow occurred in subtraction
28V (Overflow)Set to 1 if an overflow occurs

✅ Execution of SUBS

MOV R0, #6      ; R0 = 6
MOV R1, #7      ; R1 = 7
SUBS R2, R0, R1 ; R2 = R0 - R1 = 6 - 7 = -1
  • R2 = 6 - 7 = -1

  • Since the result is -1, the N (Negative) flag is set to 1.

  • The result is not zero, so Z (Zero) flag remains 0.

  • Borrow occurs (since 6 is smaller than 7), so C (Carry) flag is set to 0.

  • No overflow occurs, so V (Overflow) flag remains 0.

✅ CPSR Flag Status After Execution

FlagValueDescription
N1The result is negative (-1)
Z0The result is not zero
C0A borrow occurred
V0No overflow

✅ Summary

  • SUBS R2, R0, R1 performs R2 = R0 - R1 and modifies the CPSR flags.

  • If the result is negative, the N flag is set to 1.

  • If the result is zero, the Z flag is set to 1; otherwise, it remains 0.

  • The C flag is set based on whether a borrow occurs in the subtraction.

  • The V flag is set if an overflow occurs.

Since SUBS updates CPSR flags, it can influence conditional execution using instructions like BEQ, BNE, BMI, etc. 🚀