Page 129 - ARM 64 Bit Assembly Language
P. 129
Structured programming 115
Listing 5.2 if statement in AArch64 assembly.
.
1 . .
2 if: cmp x0, x1 // perform test
3 blt endif // if (x < y) goto endif
.
4 . . // if statement body
5 endif:
.
6 . .
clarity, to show where the if statement begins, and the second label, endif: is the end of the
if statement. The condition in assembly is reversed from the C code. The C code checks if x
>= y to know if the if statement should be taken. In AArch64 assembly, the opposite check is
used with the instruction blt.If x<y, then the if statement is not executed. Instead, control
branches past the if statement.
5.2.2 If-then-else statement
Most high-level languages provide an extension to the basic if statement, which allows the
programmer to select one of two possible blocks of code to execute. The same behavior can
be achieved by using two sequential if statements, with logically opposite tests. However
the if-then-else construct results in code that is more efficient as well as easier to read,
understand, and debug.
5.2.2.1 Using branch instructions
Listing 5.3 shows a typical if-then-else statement in C. Listing 5.4 shows the AArch64
code equivalent, using branch instructions. Note that this method requires a conditional
branch, an unconditional branch, and two labels. This is the most common method of writ-
ing the bodies of the then and else selection constructs.
5.2.2.2 Using conditional selection
Branching is not the only way to write an if statement. AArch64 has selection instructions
that are able to choose between two source registers based on a condition code. These instruc-
tions can also optionally increment, set, or negate one of the choices.
Listing 5.5 shows the AArch64 code equivalent to Listing 5.3, using conditional operations.
Section 4.2.10 covers the eleven conditional selection instructions in AArch64. While they
cannot always be used to replace branch-based if statements, in certain examples such as
Listing 5.5, they can be used to accomplish the same task without using any branch instruc-
tions. In this and similar cases, the code is more efficient than using a branch.