Page 154 - ARM 64 Bit Assembly Language
P. 154
140 Chapter 5
41 // return 0
42 mov w0, #0
43 ldp x29, x30, [sp], #16
44 ret
45 .size main, (. - main)
The code in Listing 5.31 is slightly more efficient than a literal translation of the C code
shown in Listing 5.30. First, the string is stored in the data section instead of actually on the
stack. This saves instructions that would be required to load the string onto the stack and pos-
sibly remove it. Also, the local variable tmp is not needed in the assembly implementation.
Instead, both characters are loaded, then stored to their new destination. This means that the
function can use half as much stack space and will run much faster than an implementation
that stores the local variable on the stack.
The previous examples used the concept of an array of characters to access the string that is
being reversed. Listing 5.32 shows how this problem can be solved in C using pointers to the
first and last characters in the string, rather than using array indices. This version only has two
parameters in the reverse function, and uses pointer dereferencing rather than array indexing
to access each character. Other than that difference, it works the same as the original version.
Listing 5.33 shows how the reverse function can be implemented efficiently in AArch64 as-
sembly. This reverse function implementation has the same number of instructions as the
previous version, but lines 11 through 14 use a different addressing mode. On an AArch64
processor, the pointer method and the array index method are equally efficient. However,
many processors do not have the rich set of addressing modes available on the AArch64. On
those processors, the pointer method may be significantly more efficient.
Listing 5.32 String reversing in C using pointers.
1 #include <stdio.h>
2 #include <string.h>
3
4 void reverse(char *left, char *right)
5 {
6 char tmp;
7 if(left <= right)
8 {
9 tmp = *left;
10 *left = *right;
11 *right = tmp;
12 reverse(left+1, right-1);
13 }
14 }
15
16 int main()
17 {