Tail Call Optimization

Recursive procedures are a hallmark of computer science and practically ever modern programming language (and many that are not so modern) include the ability for a function or procedure to call itsself. When a function or procedure is called, an activation record is pushed on to the call stack to tracking registers/variables, the return address, etc. This is part of the calling sequence and is a normal part of execution. Each call gets its own activation record, and so care must be taken not to cause a stack overflow. 

Not all recursion is created equally however, and there exists certain scenarios where instead of allocating a new activation record for the procedure call we can re-use the existing record. When a recursive procedure has it's recursive call as it's last instruction, it is called a tail call. Tail calls give use the opportunity to implement an optimization called tail call elimination which is the process of converting recursive calls into a simple loop. 

Recursion vs. Tail Recursion

Let's start by looking at two implementations of the same function, one using regular recursion, the other using tail recursion.  

def fib(var k) {
     if (k < 2) {
          return 1;
      }
      return fib(k-1)+fib(k-2);
}
def fibTail(let prev, let curr, let cnt, let limit) {
    if (cnt == limit) {
        return prev+curr;
    }
    return fibTail(curr, prev+curr, cnt+1, limit);
}

One thing that should pop out immediately is the difference in the terminating conditions of the two functions. The first example hits it's base case when k falls below 2, the second terminates when it's counter variable hits its limit. The reason I'm pointing this out is because what happens to each function when they do hit there terminating condition. Once fib(k) hits k < 2, the stack begins to unwind supplying the resultant operands for the addition operation. The version written tail recursively on the other hand, is done.

To help visualize the difference let's add the following snippet to both functions from above, well place them right above the if statements at the entrance to the procedure:

    let i := 0;
    while (i < curr) {
        print " ";
        i++;
    }
    println curr;

This will trace the tree of calls. First up is the output from the non-tail recursive version:

------------------
1:
 1
1
------------------
2:
  2
 1
0
2
------------------
3:
   3
  2
 1
0
 1
3
------------------
4:
    4
   3
  2
 1
0
 1
  2
 1
0
5
------------------
5:
     5
    4
   3
  2
 1
0
 1
  2
 1
0
   3
  2
 1
0
 1
8
------------------
6:
      6
     5
    4
   3
  2
 1
0
 1
  2
 1
0
   3
  2
 1
0
 1
    4
   3
  2
 1
0
 1
  2
 1
0
13
------------------
7:
       7
      6
     5
    4
   3
  2
 1
0
 1
  2
 1
0
   3
  2
 1
0
 1
    4
   3
  2
 1
0
 1
  2
 1
0
     5
    4
   3
  2
 1
0
 1
  2
 1
0
   3
  2
 1
0
 1
21
------------------

Of immediate notice is the amount of work being re-computed during each recursive call. And next is the output of the tail recursive version:

------------------
4:
 1
 1
  2
   3
8
------------------
5:
 1
 1
  2
   3
     5
13
------------------
6:
 1
 1
  2
   3
     5
        8
21
------------------
7:
 1
 1
  2
   3
     5
        8
             13
34
------------------
8:
 1
 1
  2
   3
     5
        8
             13
                     21
55
------------------
9:
 1
 1
  2
   3
     5
        8
             13
                     21
                                  34
89
------------------
10:
 1
 1
  2
   3
     5
        8
             13
                     21
                                  34
                                                       55
144

Right away we can tell just by the shape of recursion that the tail recursive version makes far, far fewer recursive calls to arrive at an answer. Additionally, once we reach our terminating condition, there is no more work left to do! But theres something else of far more importance under the hood that we can't necessarily observe without peeking at the run time stack and compiled bytecode.

Meanwhile On the Stack

The folloing is a snapshot of the runtime environment during execution of the non-tail recursive version. We can see that prior to fetching the next instruction, we have ten activation records on the call stack and our function closure is on top of the operand stack. This set's is up for the 'call' instruction, after which we have eleven activation records on the call stack.

Operands:  0: [(nil)] 1: [8] 2: [3] 3: [1] 4: [0] 5: [(closure)fib, 1] 
Callstack: 
           0: [ 1: {2}, 2: {(nil)}, 3: {(nil)}, 4: {(nil)}, 5: {(nil)}, ]
           1: [ 1: {4}, 2: {(nil)}, 3: {(nil)}, 4: {(nil)}, 5: {(nil)}, ]
           2: [ 1: {6}, 2: {(nil)}, 3: {(nil)}, 4: {(nil)}, 5: {(nil)}, ]
           3: [ 1: {7}, 2: {(nil)}, 3: {(nil)}, 4: {(nil)}, 5: {(nil)}, ]
           4: [ 1: {8}, 2: {(nil)}, 3: {(nil)}, 4: {(nil)}, 5: {(nil)}, ]
           5: [ 1: {9}, 2: {(nil)}, 3: {(nil)}, 4: {(nil)}, 5: {(nil)}, ]
           6: [ 1: {10}, 2: {(nil)}, 3: {(nil)}, 4: {(nil)}, 5: {(nil)}, ]
           7: [ 1: {11}, 2: {(nil)}, 3: {(nil)}, 4: {(nil)}, 5: {(nil)}, ]
           8: [ 1: {12}, 2: {(nil)}, 3: {(nil)}, 4: {(nil)}, 5: {(nil)}, ]
           9: [ 1: {13}, 2: {(nil)}, 3: {(nil)}, 4: {(nil)}, 5: {(nil)}, ]
           10: [ 1: {(closure)fib, 1}, 2: {(nil)}, 3: {(nil)}, 4: {(nil)}, 5: {(nil)}, ]
================
Instrctn: 18: [0x015(call), 1,1, -1]  
Operands:  0: [(nil)] 1: [8] 2: [3] 3: [1] 
Callstack: 
           0: [ 1: {0}, 2: {(nil)}, 3: {(nil)}, 4: {(nil)}, 5: {(nil)}, ]
           1: [ 1: {2}, 2: {(nil)}, 3: {(nil)}, 4: {(nil)}, 5: {(nil)}, ]
           2: [ 1: {4}, 2: {(nil)}, 3: {(nil)}, 4: {(nil)}, 5: {(nil)}, ]
           3: [ 1: {6}, 2: {(nil)}, 3: {(nil)}, 4: {(nil)}, 5: {(nil)}, ]
           4: [ 1: {7}, 2: {(nil)}, 3: {(nil)}, 4: {(nil)}, 5: {(nil)}, ]
           5: [ 1: {8}, 2: {(nil)}, 3: {(nil)}, 4: {(nil)}, 5: {(nil)}, ]
           6: [ 1: {9}, 2: {(nil)}, 3: {(nil)}, 4: {(nil)}, 5: {(nil)}, ]
           7: [ 1: {10}, 2: {(nil)}, 3: {(nil)}, 4: {(nil)}, 5: {(nil)}, ]
           8: [ 1: {11}, 2: {(nil)}, 3: {(nil)}, 4: {(nil)}, 5: {(nil)}, ]
           9: [ 1: {12}, 2: {(nil)}, 3: {(nil)}, 4: {(nil)}, 5: {(nil)}, ]
           10: [ 1: {13}, 2: {(nil)}, 3: {(nil)}, 4: {(nil)}, 5: {(nil)}, ]
           11: [ 1: {(closure)fib, 1}, 2: {(nil)}, 3: {(nil)}, 4: {(nil)}, 5: {(nil)}, ]

This is in stark contrast to the implementation taking advantage of tail call optimization & elimination. The operand stack is in a similar configuration to the 'tcall' instruction, but the call stack remains flat by sidestepping the need to create an activation record:

----------------
Operands:  0: [(nil)] 1: [5] 2: [8] 3: [5] 4: [5] 5: [(closure)fibTail, 1] 
Callstack: 
           0: [ 1: {3}, 2: {5}, 3: {4}, 4: {5}, 5: {(nil)}, ]
           1: [ 1: {(closure)fibTail, 1}, 2: {(nil)}, 3: {(nil)}, 4: {(nil)}, 5: {(nil)}, ]
================
Instrctn: 20: [0x014(tcall), 1,4]  
----------------
----------------
Operands:  0: [(nil)] 
Callstack: 
           0: [ 1: {5}, 2: {8}, 3: {5}, 4: {5}, 5: {(nil)}, ]
           1: [ 1: {(closure)fibTail, 1}, 2: {(nil)}, 3: {(nil)}, 4: {(nil)}, 5: {(nil)}, ]
================

Lets turn our attention to the compiled byecode so as to see how we managed to make this happen from a code standpoint. The following listings are the bytecode representation of the compiled fib and fibtail procedures, respectively:

; non-tail recursive
25: [0x30 defun 0 1 ]
26: [0x 5 ldlocal 1 . ]
27: [0x 1 ldconst . . ]
28: [0x28 binop 7 . ]
29: [0x22 brf 32 . ]
30: [0x 1 ldconst . . ]
31: [0x16 retfun . . ]
32: [0x 5 ldlocal 1 . ]
33: [0x 1 ldconst . . ]
34: [0x28 binop 2 . ]
35: [0x 4 ldglobal 2 . ]
36: [0x15 call 2 1 -1 ]
37: [0x 5 ldlocal 1 . ]
38: [0x 1 ldconst . . ]
39: [0x28 binop 2 . ]
40: [0x 4 ldglobal 2 . ]
41: [0x15 call 2 1 -1 ]
42: [0x28 binop 1 . ]
43: [0x16 retfun . . ]
; tail recursive
 1: [0x30 defun 0 1 ]
 2: [0x 5 ldlocal 3 . ]
 3: [0x 5 ldlocal 4 . ]
 4: [0x28 binop 9 . ]
 5: [0x22 brf 10 . ]
 6: [0x 5 ldlocal 1 . ]
 7: [0x 5 ldlocal 2 . ]
 8: [0x28 binop 1 . ]
 9: [0x16 retfun . . ]
10: [0x 5 ldlocal 2 . ]
11: [0x 5 ldlocal 1 . ]
12: [0x 5 ldlocal 2 . ]
13: [0x28 binop 1 . ]
14: [0x 5 ldlocal 3 . ]
15: [0x 1 ldconst . . ]
16: [0x28 binop 1 . ]
17: [0x 5 ldlocal 4 . ]
18: [0x 4 ldglobal 1 . ]
19: [0x14 tcall 1 4 ]
20: [0x16 retfun . . ]

Looking at the two functions' bytecode side-by-side, we can see that despite both of the functions ending with a returned function call, the function call is not the last operation before the return in the first version, and so it can't be optimized. Looking over at the tail recursive version we can see the actual optimization. On line 19 the 'call' bytecode op has been replaced with a 'tcall' operation. Lets take a closer look at what tcall does under the hood.

Enter the bytecode: call & tcall

The main advantage to tail call optimization is that we re-use the activation record of the current procedure call saving us the effort of creating a new one, assigning registers, etc. To accomplish this we introduce a 'tcall' instruction to the VM that functions almost identically to 'call':

void VM::tailCall(Instruction& inst) {
    int numArgs = inst.operand[1].intval;
    int cpIdx = inst.operand[0].intval;
    if (opstk[sp].type == OBJECT && opstk[sp].objval->type == CLOSURE) {
        Closure* close = pop().objval->closure;
        if (close != nullptr) {
            for (int i = numArgs; i > 0; i--) {
                callstk->locals[i] = pop();
            }
            callstk->locals[0] = close;
            ip = close->func.start_ip;
            return;
        }
    }
    cout <<"Fatal error: attempted function application without a function. ("<<cpIdx<<")"<<endl;
    running = false;
}

This function is nearly identical to the one for calling a regular procedure, the only difference is that where we would normally create an activation record an place it on the stack, we just... don't. Instead, we pop the arguments from the operand stack and load them into the local slots of the current activation record.

Now that we know the difference between tail recursive and regular recursive function calls and have added support for tail calls to the VM, we still need our compiler to know how and when to make the actual optimization.

Tail Call Optimization in Code Generation

Tail call optimization takes place during its own pass over the emitted bytecode. We first filter instruction sequences to check by looking for a call instruction immediately followed by a retval instruction, which signals a possible tail call. Should we find a prospective instruction sequence, we use isTailCall() to verify that the function is actually calling itself, and not a different procedure. 

   for (int i = 0; i < code.size()-1; i++) {
        if (code[i].op == call && code[i+1].op == retfun) {
            if (isTailCall(i)) {
                code[i].op = tcall;
            }
        }
    }

Once we know it's a valid optimization point, the only other thing we need to do is change the stored instruction from 'call' to 'tcall'. The isTailCall() function is simple enough, it just checks that the function being called is actually the same as the current function:

bool ByteCodeGenerator::isTailCall(int i) {
    int addr = code[i].operand[0].intval;
    while (--i > 0) {
        if (code[i].op == defun && i == addr)
            return true;
    }
    return false;
}

And that's it really! Go forth and recur!


Leave A Comment