Translating Java while loop into ARM Assembly?



I want to translate some Java code that calculates the sum from the below loop to ARM assembly, and I am wondering: how I can fix what I have so far?

Here is the Java code I am translating:

R0 = 0; 
R1 = 1;
while (R1 < 100) 
{
  R0 += R1;
  R1++;
}

And here is the code in ARM Assembly:

  MOV       R0,#0
  MOV       R1,#1
  MOV       R2,#100 
looptop
  CMP       R0, R2
  BGT       loopbottom

  ADD       R0, R0, R1
  ADD       R1, R1, #1
  B         looptop 
loopbottom

Answer

You don’t have to initialize r2 since you can use the immediate value of 100 with cmp:

    mov     r1, #1
    mov     r0, #0
1
    cmp     r1, #100
    add     r0, r0, r1
    add     r1, r1, #1
    blt     %b1

You can remove the cmp instruction altogether by constructing the loop with decreasing, zero-terminating counter:

    mov     r1, #100
    mov     r0, #0
1
    subs    r1, r1, #1
    addgt   r0, r0, r1
    bgt     %b1
 


Source: stackoverflow