Page 157 - ARM 64 Bit Assembly Language
P. 157
Structured programming 143
Listing 5.34 Initializing an array of integers in C.
.
1 . .
2 int x[100];
3 for(int i = 0; i < 100; i++)
4 x[i] = i;
.
5 . .
Listing 5.35 Initializing an array of integers in assembly.
.
1 . .
2 sub sp, sp, #400 // int x[100]
3 mov x0, #0 // x0 =i=0
4 loop:
5 str w0, [sp, x0, lsl #2] // x[i] = i
6 add x0, x0, #1 // i++
7 cmp x0, #100 // loop test
8 blt loop // if (i < 100) goto loop
.
9 . .
Listing 5.36 shows how a struct can be declared, allocated, and initialized in C. Listing 5.37
shows the equivalent code in AArch64 assembly.
Care must be taken using assembly to access data structures that were declared in higher
level languages such as C and C++. The compiler will typically pad a data structure to en-
sure that the data fields are aligned for efficiency. On most systems, it is more efficient for the
processor to access word-sized data if the data is aligned to a word boundary. Some proces-
sors simply cannot load or store a word from an address that is not on a word boundary, and
attempting to do so will result in an exception. The assembly programmer must somehow de-
termine the relative address of each field within the higher-level language structure. One way
that this can be accomplished in C is by writing a small function which prints out the offsets
to each field in the C structure. The offsets can then be used to access the fields of the struc-
ture from assembly language. Another method for finding the offsets is to run the program
under a debugger and examine the data structure.
5.5.3 Arrays of structured data
It is often useful to create arrays of structured data. For example, a color image may be repre-
sented as a two dimensional array of pixels, where each pixel consists of three integers which
specify the amount of red, green, and blue that are present in the pixel. Typically, each of the