Fireurza
Fireurza

Reputation: 29

ARM loop cmp issue

This is homework. I have been trying to figure out what I am doing wrong for quite a while now. The assignment is:

Consider the following code in C:

int foo(int a, int b) 
 {   
 if (a > b) return 0;   
 if (a == b) return b;   
 return a + foo(a+1, b); 
 } 

Implement this function in assembly. After branching back from your function, the output should be as follows. If the user enters 4 then 10: 4 10 49

END

If the user enters 10 then 4:

10 4 0

END

My code so far is:

@main program
_start:        
    mov sp,#0x100000        @ set up stack

    ldr r4,=0x101f1000    
    @ ASCII codes stored 
    @ at [r4] get printed

    @ get input
    bl get_int
    mov r5, r0
    bl get_int
    mov r6, r0

    @ mov a to r0 b to r1
        mov r0, r5
        mov r1, r6

    @ branch to the function you write
        bl  foo

    @ print the number in r0 after branching back from your function
        bl  print10

        @ branch to exit
        b my_exit

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@       Your code starts here      @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

foo:
        cmp r0,r1
        blt Less
        bge More
        mov r0,r1
        b Exit
Less:
        mov r3,r0
        add r0,r0,#1
        add r3,r3,r0
        cmp r0,r1
        blt More
        mov r0,r3
More:
        mov r0,#0
Exit:
        bx lr

The problem I am having is when I run it, no matter what numbers I input, I always get an output of 0.

Upvotes: 0

Views: 815

Answers (1)

Dric512
Dric512

Reputation: 3729

What you're missing is how to pass parameters and return a value. On the ARM ABI, the equivalent of:

int less(int a, int b)

Would be:

  • a (first parameter) is passed in r0
  • b (Second parameter) is passed in r1
  • Return value has to be written to r0
  • Mov lr to pc to return from function

So to call the less function, you need to: - Move a to r0 - Move b to r1 - Call the function (bllt) - Make sure to call bl (Branch and link) instead of a simple b (Branch). The branch and link form copies the address of the instruction after the bl to permit a return - Get the result from r0

You also need to be carreful that when you call a function, r0-r3 will be corrupted. And if you need to modify the other registers, you need to push them on the stack and restore before returning.

Upvotes: 1

Related Questions