c++ - GCC 似乎错过了简单的优化

标签 c++ gcc assembly optimization

我正在尝试引入一个具有三元运算符语义的通用函数:E1? E2 : E3。我看到编译器能够根据三元运算符的 E1 条件消除 E2E3 之一的计算。然而,GCC 在 ternary 函数调用的情况下错过了这种优化(即使 E2/E3 没有副作用)。

在下面的列表中,函数 ternary 的行为类似于三元运算符。然而,GCC 可能会发出对函数 f 的潜在大量调用,这似乎可以消除某些输入值(对于三元运算符来说正是这样做的),因为 f 是用纯属性声明的 -请查看 GCC 生成的汇编代码的 godbolt 链接。

它是否可以在 GCC 中进行改进(优化空间)或 C++ 标准是否明确禁止此类优化?

// Very heavy function
int f() __attribute__ ((pure));

inline int ternary(bool cond, int n1, int n2) {
    return cond ? n1 : n2;
}

int foo1(int i) {
    return i == 0 ? f() : 0;
}

int foo2(int i) {
    return ternary(i == 0, f(), 0);
}

带有 -O3 -std=c++11 的程序集 list :

foo1(int):
  test edi, edi
  jne .L2
  jmp f()
.L2:
  xor eax, eax
  ret
foo2(int):
  push rbx
  mov ebx, edi
  call f()
  test ebx, ebx
  mov edx, 0
  pop rbx
  cmovne eax, edx
  ret

https://godbolt.org/z/HfpNzo

最佳答案

I see that compiler is able to eliminate calculation of one of E2 or E3 depending on E1 condition (as long as E2/E3 has no side effects) for the ternary operator.

编译器不会消除它;它只是从一开始就从未将其优化为 cmovC++ 抽象机评估三元运算符的未使用端。

int a, b;
void foo(int sel) {
    sel ? a++ : b++;
}

像这样编译(Godbolt):

foo(int):
    test    edi, edi
    je      .L2                # if(sel==0) goto
    add     DWORD PTR a[rip], 1   # ++a
    ret
.L2:
    add     DWORD PTR b[rip], 1   # ++b
    ret

如果两个输入都没有任何副作用,则三元运算符只能优化为 asm cmov。否则它们并不完全等同。


在 C++ 抽象机中(即 gcc 优化器的输入),您的 foo2 总是调用 f(),而您的 foo1 没有。 foo1 以这种方式编译也就不足为奇了。

要让 foo2 以这种方式编译,它必须优化掉对 f() 的调用。 它总是被调用来为 ternary( )


这里有一个 missed-optimization,你应该在 GCC 的 bugzilla 上报告(使用 missed-optimization 关键字作为标签)。 https://gcc.gnu.org/bugzilla/enter_bug.cgi?product=gcc

int f() __attribute__ ((pure)); 的调用 应该 能够被优化掉。它可以读取全局变量,但不能有任何副作用。 ( https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html )

正如@melpomene 在评论中发现的那样,int f() __attribute__ ((const)); 确实为您提供了您正在寻找的优化。 __attribute__((const)) 函数甚至不能读取全局变量,只能读取其参数。 (因此没有参数,它必须总是返回一个常量。)

HVD 指出 gcc 没有任何关于 f() 的成本信息。即使它可以优化掉对 ((pure)) f()((const)) f 的调用,也许不是因为它不知道它比条件分支更昂贵?可能使用配置文件引导优化进行编译会说服 gcc 做某事?

但鉴于它在 foo2 中以条件方式调用了 ((const)) f,gcc 可能只是不知道它可以优化对 的调用((pure)) 函数?也许它只能对它们进行 CSE(如果没有编写全局变量),但不能完全脱离基本 block 进行优化?或者,也许当前的优化器无法利用。就像我说的,看起来像是一个错误选择。

关于c++ - GCC 似乎错过了简单的优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52320679/

相关文章:

c++ - 构造函数、析构函数、重载=运算符函数、复制构造函数不会被继承。这究竟意味着什么?

c++ - 如何使用数组的值初始化 unordered_map

c - 这个 "c(.text+0x7): relocation truncated to fit: 8 .data"是什么类型的错误

assembly - AND 比整数模运算更快?

assembly - JIT 反汇编中的冗余存储

c++ - 对 org::opensplice::core::DWDeleter::DWDeleter 的 undefined reference

c++ - 堆分配类的成员是否在堆中自动分配?

gcc - CPLUS_INCLUDE_PATH 不起作用

android - android art elf和linux elf文件有什么区别?

c - 重新编译 -fPIC 问题