Ackermann function in assembly - stuck in infinite recursion

359 Views Asked by At

I'm trying to write Ackermann function as assembly code(in ARMV8).

(http://mathworld.wolfram.com/AckermannFunction.html https://en.wikipedia.org/wiki/Ackermann_function)

It requires recursion. My code goes into an infinite recursion. I couldn't find what is the problem about stack pointer handling.

X0 and X1 are input registers. I'm returning the result in X0.

     ack:
        SUB SP, SP, #24
        STUR X0,[SP,#16] // save input1 to stack pointer
        STUR X1,[SP,#8] // save input2 to stack pointer
        STUR X30,[SP,#0] // save return adress
        SUBS XZR,X0,#0 // check input1 <= 0
        B.GT cond1 
        ADD X0,X1,#1 
        B last 
  cond1:
        SUBS XZR,X1,#0
        B.GT gobig
        SUB X0,X0,#1
        MOVZ X1,0 
        ADD X1,X1,1 
        BL ack // call ack with input1-1 and 1
        LDUR X30,[SP,#0] //restore return address
        ADD SP,SP,#24
        BR X30 // return register adress
  gobig:
        LDUR X0,[SP,#16]
        LDUR X1,[SP,#8]
        SUB X1,X1,#1
        BL ack //call ack with input1 and input2-1 (call result r)
        ADD X1,X0,#0
        LDUR X0,[SP,#16]
        SUB X0,X0,#1
        BL ack //call ack wih input1-1 and r
  last:
        LDUR X30,[SP,#0]
        ADD SP,SP,#24 //restore stack pointer
        BR X30 //return adress register
0

There are 0 best solutions below