Search code examples
cassemblyraspberry-piarmnested-loops

C nested loop to ARM assembly


I'm currently having issues translating a C program to ARM assembly. The C program is as follows:

int i = 1;
int j = 0;
int x = 0;

int main(){
    for( ; i < 10; i += 2){
        for( j = i; j < 10; j++){
            x += i + j;
        }
    }
    return x;
}

This code will output 240.

What I have currently is as follows:

.data

i:      .word   1
j:      .word   0
x:      .word   0

.text
.global main

main:
    LDR r6, addrJ
    LDR r5, addrI
    LDR r4, addrX
    LDR r3, [r6]
    LDR r2, [r5]
    LDR r1, [r4]
    b loop_outer

loop_outer:
    CMP r2, #10
    BGE done
    MOV r3, r2                      @ j = i
    loop_inner:
        CMP r3, #10             @ j < 10
        BGE inner_done
        ADD r1, r1, r2          @ x+=i
        ADD r1, r1, r3          @ x+=j
        ADD r3, r3, #1          @ j++
    inner_done:
        ADD r2, r2, #2          @ i+=2
        b loop_outer
        b done
done:
    MOV r0, r1
    bx lr

addrI: .word i
addrX: .word x
addrJ: .word j

This code currently outputs 50. I have tried debugging myself but I have been having a hard time with GDB.


Solution

  • You're missing the b loop_inner to repeat the inner loop.

    And b done is not needed, since it's after the unconditional b loop_outer, so it will never be executed.

    loop_outer:
        CMP r2, #10
        BGE done
        MOV r3, r2                  @ j = i
        loop_inner:
            CMP r3, #10             @ j < 10
            BGE inner_done
            ADD r1, r1, r2          @ x+=i
            ADD r1, r1, r3          @ x+=j
            ADD r3, r3, #1          @ j++
            b loop_inner
        inner_done:
            ADD r2, r2, #2          @ i+=2
            b loop_outer
    done:
        MOV r0, r1
        bx lr