C ++ Lambda Generated ASM Code

I have C ++ source code:

class Lambda
{
public:
    int compute(int &value){
        auto get = [&value]() -> int {
            return 11 * value;
        };
        return get();
    }
};

int main(){
    Lambda lambda;
    int value = 77;
    return lambda.compute(value);
}

which compiled (using -O1) with clang generates below ASM:

main: # @main
  push rax
  mov dword ptr [rsp + 4], 77
  mov rdi, rsp
  lea rsi, [rsp + 4]
  call Lambda::compute(int&)
  pop rcx
  ret
Lambda::compute(int&): # @Lambda::compute(int&)
  push rax
  mov qword ptr [rsp], rsi
  mov rdi, rsp
  call Lambda::compute(int&)::{lambda()#1}::operator()() const
  pop rcx
  ret
Lambda::compute(int&)::{lambda()#1}::operator()() const: # @Lambda::compute(int&)::{lambda()#1}::operator()() const
  mov rax, qword ptr [rdi]
  mov eax, dword ptr [rax]
  lea ecx, [rax + 4*rax]
  lea eax, [rax + 2*rcx]
  ret

Questions:

  • What is {lambda()#1}what appears in ASM? As far as I know, this could be a closure that encapsulates a function object (i.e. lambda body). Please confirm this.
  • Does a new closure open every time it trips compute()? Or is this the same example?
+4
source share
2 answers
  • This is the body (implementation) of the lambda function that you specified in compute.
  • , , , ( 1), , - ( rdi, .. , this, -).

1 " " . , -. , -O2 clang main(). gcc -O1.

+2
  • , - [ , ]
  • compute, , , get(), - compute. , , - -O2 847 - . -, , . , .

    , , : compute, , , get.

    int value2 = 88;
    int tmp = lambda.compute(value2);

main ( clang++ Linux):

main:                                   # @main
    pushq   %rbx
    subq    $16, %rsp
    movl    $77, 12(%rsp)
    ## new line to set value2
    movl    $88, 8(%rsp)
    movq    %rsp, %rbx
    ## New line, passing reference of `value2` to lambda.compute
    leaq    8(%rsp), %rsi
    movq    %rbx, %rdi
    ## Call lambda.compute
    callq   _ZN6Lambda7computeERi
    ## Same as before.
    leaq    12(%rsp), %rsi
    movq    %rbx, %rdi
    callq   _ZN6Lambda7computeERi
    addq    $16, %rsp
    popq    %rbx
    retq

,

+2

Source: https://habr.com/ru/post/1694900/


All Articles