首页 > 解决方案 > 为什么 GCC 不能为两个 int32 的结构生成最佳 operator==?

问题描述

一位同事向我展示了我认为没有必要的代码,但确实如此。我希望大多数编译器会在相等性测试中看到所有这三种尝试:

#include <cstdint>
#include <cstring>

struct Point {
    std::int32_t x, y;
};

[[nodiscard]]
bool naiveEqual(const Point &a, const Point &b) {
    return a.x == b.x && a.y == b.y;
}

[[nodiscard]]
bool optimizedEqual(const Point &a, const Point &b) {
    // Why can't the compiler produce the same assembly in naiveEqual as it does here?
    std::uint64_t ai, bi;
    static_assert(sizeof(Point) == sizeof(ai));
    std::memcpy(&ai, &a, sizeof(Point));
    std::memcpy(&bi, &b, sizeof(Point));
    return ai == bi;
}

[[nodiscard]]
bool optimizedEqual2(const Point &a, const Point &b) {
    return std::memcmp(&a, &b, sizeof(a)) == 0;
}


[[nodiscard]]
bool naiveEqual1(const Point &a, const Point &b) {
    // Let's try avoiding any jumps by using bitwise and:
    return (a.x == b.x) & (a.y == b.y);
}

但令我惊讶的是,只有那些被 GCC 比较memcpymemcmp变成单个 64 位的比较。为什么?(https://godbolt.org/z/aP1ocs

如果我在连续的四个字节对上检查相等性,这对于优化器来说不是很明显,这与在所有八个字节上进行比较是一样的吗?

避免单独布尔化这两个部分的尝试会更有效地编译(减少一条指令并且对 EDX 没有错误依赖),但仍然是两个单独的 32 位操作。

bool bithackEqual(const Point &a, const Point &b) {
    // a^b == 0 only if they're equal
    return ((a.x ^ b.x) | (a.y ^ b.y)) == 0;
}

GCC 和 Clang 在按值传递结构时都有相同的错过优化(a在 RDI 和bRSI 中也是如此,因为这就是 x86-64 System V 的调用约定将结构打包到寄存器中的方式):https ://godbolt.org/z/ v88a6s。memcpy / memcmp 版本都编译为cmp rdi, rsi / sete al,但其他版本执行单独的 32 位操作。

struct alignas(uint64_t) Point令人惊讶的是,在参数位于寄存器中的按值情况下仍然有帮助,优化 GCC 的两个 naiveEqual 版本,但不是 bithack XOR/OR。(https://godbolt.org/z/ofGa1f)。这会给我们关于 GCC 内部结构的任何提示吗?对齐对 Clang 没有帮助。

标签: c++gccx86-64compiler-optimizationmicro-optimization

解决方案


如果您“修复”对齐方式,则都给出相同的汇编语言输出(使用 GCC):

struct alignas(std::int64_t) Point {
    std::int32_t x, y;
};

演示

作为说明,一些正确/合法的方法来做一些事情(如类型双关语)是使用memcpy,因此在使用该函数时进行特定的优化(或更积极)似乎是合乎逻辑的。


推荐阅读