为什么 Clang-Tidy 建议更大的对齐?

Why does Clang-Tidy suggest a larger alignment?

给定以下 C 语言结构定义:

typedef struct PackTest {
    long long a;
    int b;
    int c;
} PackTest;

Clang-Tidy 给出以下消息:

Accessing fields in struct 'PackTest' is inefficient due to poor alignment; currently aligned to 8 bytes, but recommended alignment is 16 bytes

我知道为什么结构对齐到 8 字节,但我不知道这个建议是否有效以及为什么。

一些特定的专用汇编指令可能有对齐要求(例如,x86 non-scalar SSE instructions strictly require alignment to 16 bytes boundaries). Other instructions might have lower throughput when used on data that is not aligned to 16 byte boundaries (for example, x86 SSE2)。

这类指令通常用于根据处理器的硬件特性执行积极的优化。总的来说,您收到的消息仅在这些情况下有用(即,如果您确实打算利用此类说明)。

另请参阅:

  • What does alignment to 16-byte boundary mean in x86

最后我只引用 Rich from 因为他们提出了一个非常好的观点:

There is nothing "untidy" about having standard structs that are not ridiculously over-aligned. For very specialized purposes you might want an over-aligned object, but if it's flagging this then most things it's flagging are just wrong, and encouraging you to write code that's inefficient and gratuitously nonstandard.

您可以为 Clang-Tidy 添加 -altera-struct-pack-align 以禁用此警告

来源:https://www.mail-archive.com/cfe-commits@lists.llvm.org/msg171275.html