Page 137 - ARM 64 Bit Assembly Language
P. 137
Structured programming 123
Listing 5.16 pre-test loop in AArch64 assembly.
1 .section .rodata
2 str: .string "Hello World - %d\n"
3 .text
.
4 . .
5 mov x4, #0 //x4=i=0
6 loop:
7 cmp x4, #10 // perform comparison
8 bge done // end loop if i >= 10
9 adr x0, str // load pointer to format string
10 mov x1, x4 // copy i into x1
11 bl printf // printf("Hello World - %d\n", i);
12 add x4, x4, #1 // i++
13 b loop // repeat loop
14 done:
.
15 . .
Listing 5.17 for loop re-written as a post-test loop in C.
.
1 . .
2 int i = 0;
3 do {
4 printf("Hello World - %d\n", i);
5 i++;
6 } while(i < 10);
.
7 . .
efficient, because the loop control variable is tested one time less than for a pre-test loop.
Also, a post-test loop requires only one label and one conditional branch instruction, whereas
a pre-test loop requires two labels, a conditional branch, and an unconditional branch.
Since the loop in Listing 5.14 always executes the body exactly ten times, we know that the
body will always execute at least once. Therefore, the loop can be converted to a post-test
loop. Listing 5.17 shows the program re-written as a post-test loop so that it is easier to trans-
late into assembly. Note that, as in the previous example, the initialization of the loop variable
has been moved to its own line before the do-while loop, and the loop variable is modi-
fied on the last line of the loop body. This post-test version will produce the same output as
the pre-test version. This is a straightforward conversion from one type of loop to an equiva-
lent type. Listing 5.18 shows a straightforward translation of the post-test loop structure into
AArch64 assembly.