In the previous episode in this series, I started to look at how to control flow using an instruction which sets the NZCV flags, followed by a conditi

Code in ARM Assembly: Conditional loops

submited by
Style Pass
2021-06-29 08:30:04

In the previous episode in this series, I started to look at how to control flow using an instruction which sets the NZCV flags, followed by a conditional branch to a label. The example given there is among the simplest, a series of if … else if … statements or a small switch statement. That can be summarised in the diagram:

Although conditional loops can be written in several different ways using high-level languages like Swift, there are two basic patterns, depending on whether the test is made in the head or tail of the loop.

In Swift, the most widely used form of loop which tests whether the condition is met in the tail is the for statement: for index in 1...100 {
}

A typical implementation in ARM64 assembly language might start by setting up registers containing the start index value and the end index, then perform the code in the loop, incrementing the index value, and testing whether it remains less than or equal to the end index. If it does, then branch back to the loop to perform it again; if it doesn’t, then continue with the following operations.

Here’s an example in which the index is stored in register X5, and the maximum index in X4: MOV X5, #1 // start index = 1
MOV X4, #100 // end index = 100
for_loop: // do what you need in the loop
// …
ADD X5, X5, #1 // increment the index by 1
CMP X5, X4 // check whether end index has been reached
B.LE for_loop // if index <= end index, loop back
// next code after loop

Leave a Comment