ddmdgdc

Which D compilers will perform tail-call optimization on this function?


string reverse(string str) pure nothrow
{
    string reverse_impl(string temp, string str) pure nothrow
    {
        if (str.length == 0)
        {
            return temp;
        }
        else
        {
            return reverse_impl(str[0] ~ temp, str[1..$]);
        }
    }

    return reverse_impl("", str);
}

As far as I know, this code should be subject to tail-call optimization, but I can't tell if DMD is doing it or not. Which of the D compilers support tail-call optimization, and will they perform it on this function?


Solution

  • From looking at the disassembly, DMD performs TCO on your code:

    _D4test7reverseFNaNbAyaZAya12reverse_implMFNaNbAyaAyaZAya   comdat
        assume  CS:_D4test7reverseFNaNbAyaZAya12reverse_implMFNaNbAyaAyaZAya
    L0:     sub ESP,0Ch
            push    EBX
            push    ESI
            cmp dword ptr 018h[ESP],0
            jne L1C
    
    LC:     mov EDX,024h[ESP]
            mov EAX,020h[ESP]
            pop ESI
            pop EBX
            add ESP,0Ch
            ret 010h
    
    L1C:    push    dword ptr 024h[ESP]
            mov EAX,1
            mov EDX,offset FLAT:_D12TypeInfo_Aya6__initZ
            push    dword ptr 024h[ESP]
            mov ECX,024h[ESP]
            push    ECX
            push    EAX
            push    EDX
            call    near ptr __d_arraycatT
            mov EBX,02Ch[ESP]
            mov ESI,030h[ESP]
            mov 034h[ESP],EAX
            dec EBX
            lea ECX,1[ESI]
            mov 01Ch[ESP],EBX
            mov 020h[ESP],ECX
            mov 02Ch[ESP],EBX
            mov 030h[ESP],ECX
            mov 038h[ESP],EDX
            add ESP,014h
            cmp dword ptr 8[ESP],0
            jne L1C
            jmp short   LC
    _D4test7reverseFNaNbAyaZAya12reverse_implMFNaNbAyaAyaZAya   ends
        end