ARM Loops

While loops

while (a < 0){
    a++;
}
loop: CMP r0, #0
      BGE end
      ADD r0, r0, #1 @ Body of loop
      B loop
end:
@ Equivalent to above
loop: CMP r0, #0
      ADDLT r0, r0, #1
      BLT loop
Do while
do {
    a++;
} while (a < 0);
@ loop part different to while loop
loop: ADD r0, r0, #1 @ body of 'do'
      CMP r0, #0
      BLT loop
For loops
for (i = 0; i < 10; i++){
    a++;
    b--;
}
MOV r0, #0
loop: CMP r0, #10
      BGE end
      ADD r1, r1, #1
      SUB r2, r2, #1
      B loop
end:
@ Equivalent to above
MOV r0, #0
loop: CMP r0, #10
      ADDLT r1, r1, #1
      SUBLT r2 ,r2, #1
      ADDLT r0, r0, #1
      BLT loop

C functions

Caller and callee functions:

main() {
// main in this case is a caller
    int a = 10, b = 20;
    int c = sum(a, b);
}
int sum(int x, y){
// sum is a callee
    return x + y;
}
Steps in function call
  1. Pass parameters (using registers)
  2. Call functions (sum)
  3. Compute return value, put it in the right register
  4. Transfer control back to caller (return)

1 and 2 are in main();

Making the function call
BL sum @ function call
BX @ return
...
B sum
return 
...
...
sum: ADD r0, r0, r1
B return_loc
...

Problems:

Reason:

lr (link register): register reserved to store the return address

...
BL sum 
...
...
sum: ADD r0, r0, r1
BX lr ; MOV pc,lr i.e., return
...
Passing arguments
main() {
    int a = 10, b = 20, c;
    c = sum(a, b);
    c++;
}
main:
MOV r0, #20
MOV r1, #20
BL sum

sum:
ADD r0, r0, r1 @ return value in r0
BX lr
Register conventions

A set of generally accepted rules as to which registers are guaranteed to be unchanged after a procedure call and which may be changed.

r0 – r3

Arguments and return values, otherwise corruptible.

r4 – r11

Callee has to make sure that the value in r4-r11 are unchanged by it.

r12 scratch register
Push and pop

Push registers onto, and pop registers off a full descending stack (usually within function call).

push {r4-r11}
...
pop {r4-r11}
Published on October 30, 2015