[llvm-dev] Another tail call optimization question

Alexey via llvm-dev llvm-dev at lists.llvm.org
Sat Oct 3 03:34:59 PDT 2020


Hi Haoran,

On 03.10.2020 12:02, Haoran Xu via llvm-dev wrote:
> Hello,
>
> Could anyone kindly explain to me why the 'g()' in the following 
> function cannot have tail call optimization?
>
>     voidf(int* x);
>     voidg();
>     voidh(intv) {
>        f(&v);
>        g();
>     }
>
> A while ago I was taught that tail call optimization cannot apply if 
> local variables needs to be kept alive, but 'g()' doesn't seem to 
> require anything to be alive on the stack.
> I tried to manually add 'tail' to the emitted LLVM IR and it appears 
> to work.
>
> Any idea how I could fix this and let clang automatically generate 
> tail call?


In that test case the pointer to "v" could escape through call to f();
That prevents from doing tail call for g().
If it is already known that f() does not capture its parameter
then it could be declared with attribute noescape :

https://clang.llvm.org/docs/AttributeReference.html#noescape

In this case tailcall happens:

cat test.cpp
     void f(__attribute__((noescape)) int* x);
     void g();
     void h(int v) {
        f(&v);
        g();
     }

clang++ -O3 -S test.cpp

grep _Z1gv test.s

jmp    _Z1gv                           # TAILCALL



> Thanks!
>
> Best,
> Haoran
>
> _______________________________________________
> LLVM Developers mailing list
> llvm-dev at lists.llvm.org
> https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-dev
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-dev/attachments/20201003/9ee71be9/attachment.html>


More information about the llvm-dev mailing list