Assembly Language Operations

Comparison Operations

There are four comparison operations in ARM assembly language. These comparisons work by performing arithmetic or logical operations on the values stored in the source registers and setting the appropriate condition code flags in the Current Program Status Register as necessary. However, the actual result of the underlying arithmetic or logical operation is not stored in any register.

Note that the comparison operations can have literals instead of registers as operands.

CMP r1, r2 ; set condition codes according to the result of r1 - r2

The CMP (compare) instruction will set the condition codes as follows:

    • N =1 if the most significant bit of (r1 - r2) is 1, i.e. r2 > r1
    • Z = 1 if (r1 - r2) = 0, i.e. r1 = r2
    • C = 1 if r1 and r2 are both unsigned integers AND (r1 < r2)
    • V = 1 if r1 and r2 are both signed integers AND (r1 < r2)
CMN r1, r2 ; set condition codes according to the result of r1 + r2

The CMN (compare negative) instruction determines the condition codes by performing the equivalent of: operand1 - ( - operand2). It is useful for comparing the values in registers against small negative numbers (such as -1 which might be used to mark the end of a data structure.)

TST r1, r2 ; set condition codes on r1 AND r2

The TST (test bits) instruction can be used to test if one or more bits are set. The first operand is the value to be tested; the second operand is the bit mask. The Z flag will be set if there is a match, otherwise it will be cleared.

TEQ r1, r2 ; set condition codes on r1 XOR r2

The TEQ (test equivalent) instruction is similar to TST, but differs in that it uses an exclusive-or operation. It can be used to determine if specific bits in two operands are the same or different. It does not change the overflow flag, unlike CMP. TEQ can be used to determine if two values have the same sign.

The CMP, CMN, TST, and TEQ instructions always alter the condition codes. Other data processing instructions (such as ADD, ADC, SUB, etc.,) can alter the condition codes if they have an "S" suffix.

ADDS r0, r1, r2 ; r0 := r1 + r2 and adjust condition codes for result placed in r0

As an example, consider adding 2 128-bit numbers together.

Let the first number be stored in registers 0, 1, 2 and 3. Let the second number be stored in registers 4, 5, 6 and 7. Store the result in registers 8, 9, 10, and 11.

ADDS r8, r0, r4 ; Add low words, adjusting condition codes
ADCS r9, r1, r5 ; Add next word with any carry from previous instruction, adjust codes
ADCS r10, r2, r6 ; Add third word with any carry from previous instruction, adjust codes
ADCS r11, r3, r7 ; Add high word with any carry from previous instruction, adjust codes