Page 133 - ARM 64 Bit Assembly Language
P. 133

Structured programming 119


                                      Listing 5.8 Unconditional loop in AArch64 assembly.

                    1         .section .rodata
                    2  hstr:  .string "Hello World\n"
                    3         .text
                    4         .type  main, %function
                    5         .global main
                    6  main:
                    7  loop:  adr    x0,hstr         // load pointer to "Hello World\n\0"
                    8         bl     printf          // print "Hello World\n"
                    9         b      loop            // repeat main unconditionally
                   10         .size  main, (. - main)



                     Note that the number of comparisons that execute will always be minimized, and the number
                     of branches has also been minimized. The only way that line 23 can be reached is if one of the
                     first two comparisons evaluates to false. The program fragment will always reach line 26 and
                     a value will be stored in x. Thus, the AArch64 assembly code fragment in Listing 5.7 can be
                     considered to be a block of code with exactly one entry point and one exit point.

                     When writing nested selection structures, it is important to maintain a block structure, even if
                     the bodies of the blocks consist of only a single instruction. It is often very helpful to write the
                     algorithm in pseudo-code or a high-level language, such as C or Java, before converting it to
                     assembly. Prolific commenting of the code is also strongly encouraged.



                     5.3 Iteration

                     Iteration involves the transfer of control from a statement in a sequence to a previous state-
                     ment in the sequence. The simplest type of iteration is the unconditional loop, also known
                     as the infinite loop. This type of loop may be used in programs or tasks that should continue
                     running indefinitely. Listing 5.8 shows an AArch64 assembly fragment containing an uncon-
                     ditional loop. Few high-level languages provide a true unconditional loop, but the high-level
                     programmer can achieve a similar effect by using a conditional loop and specifying a condi-
                     tion that always evaluates to true.



                     5.3.1 Pre-test loop

                     A pre-test loop is a loop in which a test is performed before the block of instructions forming
                     the loop body is executed. If the test evaluates to true, then the loop body is executed. The last
                     instruction in the loop body is a branch back to the beginning of the test. If the test evaluates
   128   129   130   131   132   133   134   135   136   137   138