Ryan Zhu
Ryan Zhu

Reputation: 553

what change should I make on these codes to make it conform to the assembly function call convention?

the function is foo, which is basically counting the number of ones in the valuesarray.

.data
.balign 4
values:
    .word 1
    .word 0
    .word 1 
    .word 2
    .word 1

.balign 4
count: .word 0
.balign 4
return .word 0

.text
.global foo
foo:
    mov r3, #0
    mov r2, #4
    mul r2, r1, r2
    add r2,r0,r2
    mov r4,#1

foo_loop:
    cmp r0,r2
    beq foo_exit
    ldr r1,[r0]
    cmp r1,r4
    beq foo_eq
    add r0,r0,#4
    b foo_loop

foo_eq:
    add r3,r3,#1
    add r0,r0,#4
    b foo_loop

foo_exit:
    mov r0,r3
    bx lr

.global main
main:
    ldr r1, =return
    str lr, [r1]

    ldr r0, =values
    mov r1,#5
    bl foo
    ldr r1, =count
    str r0,[r1]
    ldr lr, =return
    ldr lr,[lr]
    bx lr

Upvotes: 0

Views: 37

Answers (1)

Dric512
Dric512

Reputation: 3729

The only thing I can see which is not correct is that you use register r4 in the function without saving it. Only registers r0-r3 can be used as parameters and scratch registers.

So you should either do this:

.text
.global foo
foo:
    push {r4}
    ...

foo_exit:
    mov r0,r3
    pop {r4}
    bx lr

Or (Saving PC as well on the stack):

.text
.global foo
foo:
    push {r4,pc}
    ...

foo_exit:
    mov r0,r3
    pop {r4,lr}

Upvotes: 1

Related Questions