C ++内联优化

时间:2017-07-30 13:38:54

标签: c++ compiler-optimization

请参阅我的示例here或 以下c ++&匹配程序集

IMPLICIT INLINE

#include <iostream>

int func(int i) 
{
    return i * i;
}

int main(int argc, char *argv[])  {

    auto value = atoi(argv[1]);
    std::cout << func(value);  


    value = atoi(argv[2]);
    std::cout << func(value);  

    return 1;
}

结果

func(int):
  imul edi, edi
  mov eax, edi
  ret
main:
  push rbx
  mov rdi, QWORD PTR [rsi+8]
  mov rbx, rsi
  mov edx, 10
  xor esi, esi
  call strtol
  imul eax, eax
  mov edi, OFFSET FLAT:std::cout
  mov esi, eax
  call std::basic_ostream<char, std::char_traits<char> >::operator<<(int)
  mov rdi, QWORD PTR [rbx+16]
  mov edx, 10
  xor esi, esi
  call strtol
  imul eax, eax
  mov edi, OFFSET FLAT:std::cout
  mov esi, eax
  call std::basic_ostream<char, std::char_traits<char> >::operator<<(int)
  mov eax, 1
  pop rbx
  ret
_GLOBAL__sub_I__Z4funci:
  sub rsp, 8
  mov edi, OFFSET FLAT:std::__ioinit
  call std::ios_base::Init::Init()
  mov edx, OFFSET FLAT:__dso_handle
  mov esi, OFFSET FLAT:std::__ioinit
  mov edi, OFFSET FLAT:std::ios_base::Init::~Init()
  add rsp, 8
  jmp __cxa_atexit

明确在线

#include <iostream>

inline int func(int i)
{
    return i * i;
}

int main(int argc, char *argv[])  {

    auto value = atoi(argv[1]);
    std::cout << func(value);  


    value = atoi(argv[2]);
    std::cout << func(value);  

    return 1;
}

结果

main:
  push rbx
  mov rdi, QWORD PTR [rsi+8]
  mov rbx, rsi
  mov edx, 10
  xor esi, esi
  call strtol
  imul eax, eax
  mov edi, OFFSET FLAT:std::cout
  mov esi, eax
  call std::basic_ostream<char, std::char_traits<char> >::operator<<(int)
  mov rdi, QWORD PTR [rbx+16]
  mov edx, 10
  xor esi, esi
  call strtol
  imul eax, eax
  mov edi, OFFSET FLAT:std::cout
  mov esi, eax
  call std::basic_ostream<char, std::char_traits<char> >::operator<<(int)
  mov eax, 1
  pop rbx
  ret
_GLOBAL__sub_I_main:
  sub rsp, 8
  mov edi, OFFSET FLAT:std::__ioinit
  call std::ios_base::Init::Init()
  mov edx, OFFSET FLAT:__dso_handle
  mov esi, OFFSET FLAT:std::__ioinit
  mov edi, OFFSET FLAT:std::ios_base::Init::~Init()
  add rsp, 8
  jmp __cxa_atexit

在该示例中,如果第5行被注释掉,则代码的优化会在两个调用点处内联函数“func”,但它会在生成的二进制文件中保留func的程序集。但是,如果显式内联'func',则输出程序集中不存在该函数。

为什么GCC优化器在编译汇编中隐式内联函数,即使内联函数的操作真的与调用代码内联?

1 个答案:

答案 0 :(得分:0)

如果标记为static,该函数将完全消失。因为它当前未标记为static,所以它可能被另一个编译单元引用,因此无法将其删除。