0
\$\begingroup\$

I'm confused on what happens during POP. When POP LR happens does that change the PC to the location of LR, which would be sumi. If it does take it back to sumi wouldn't that just take the recursion even further?

c++:

int sumi(int n) {
  if(n == 0)
  return 0;
else
  return n+sumi(n-1);
}

assembly:

sumi:
CMP R2,#0 ; n is R2
BNE else

then:
MOV R0,#0 ; result in R0
BX LR

else:
PUSH LR 
PUSH R2
SUB R2,R2,#1 
BL sumi
POP R2
ADD R0,R2,R0
POP LR
BX LR
\$\endgroup\$
  • 2
    \$\begingroup\$ I'm voting to close this question as off-topic because this is a pure software question. \$\endgroup\$ – DoxyLover Feb 13 '17 at 6:51
  • 1
    \$\begingroup\$ These very low-level programming questions tend to be accepted on EE. \$\endgroup\$ – Wouter van Ooijen Feb 13 '17 at 7:40
0
\$\begingroup\$

The POP LR instruction just pops a value off the stack and puts that value in LR. But together with the next instruction, BX LR, it does pop a value from the stack and put that in PC. On other architectures that action would be called RET or RETURN.

For a single call to sumi (n==0) the stack is not used: the BX LR causes the return to the instruction after the call to sumi.

For a recursive call, the PUSH LR first pushes the LR value on the stack, then the recursive call happens, after which the LR value is restored and copied to the PC by POP LR; BX LR.

Note: if you don't know the role of the LR in ARM subroutine calls you will definitely have to study that!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.