LLVM tail call optimization

Jonathan Gallagher picture Jonathan Gallagher · Sep 4, 2013 · Viewed 9k times · Source

Here is my understanding of things:

A function "f" is tail recursive when calling itself is its last action. Tail-recursion can be significantly optimized by forming a loop instead of calling the function again; the function's parameters are updated in place, and the body is ran again. This is called recursive tail call optimization.

LLVM implements recursive tail call optimization when using fastcc, GHC, or the HiPE calling convention. http://llvm.org/docs/CodeGenerator.html#tail-call-optimization

I have some questions: Let's consider the silly example:

int h(int x){
  if (x <= 0)
    return x;
  else
    h(x-1);
}

1) In their example, the keyword "tail" preceeds call. Elsewhere I read that this keyword is optional. Suppose the function above is translated to LLVM appropriately, do the last few lines need to be

%x' = load *i32 %x
%m = tail call fastcc i32 @h(i32 %x')
ret %m

2) What is the meaning of the inreg option in their example?

3) I would not want to perform tail call optimizations all over the place, only for recursive functions. Is there a way I can get LLVM to only perform the optimization (when available) for recursive functions?

Answer

J D picture J D · Sep 26, 2017

There are two different things here:

  1. You can optimise self-recursive tail calls into a loop. LLVM provides an optimisation pass that does this. It does not require a specific calling convention.
  2. You can use a different calling convention to guarantee tail call optimisation of all calls in tail position (i.e. including calls to other functions). With LLVM, you need to specify the calling convention on the function, on the call instruction and mark the call as a tail call.

Sounds like you want the former.