如何在不支持的架构上编译C 代码?'_mm512_aesenc_epi128':目标相关选项不匹配

编程语言 2026-07-09

我这边有个问题:我为可移植的AES内在指令写了宏,并在目标架构支持时使用AVX512。代码片段:

#if defined __VAES__ // required AVX512-VAES, not used if unsupported
# include <vaesintrin.h>
# define aes_enc_block_x4(blocks_pad_512, round_key_of_4) ((simde__m512i)_mm512_aesenc_epi128(blocks_pad_512, round_key_of_4))
#else
// defining aes_enc_block_x4 for 256-bit and 128-bit arrays
#endif

问题在于:实际在不带 -mvaes标志编译代码时,出现如下错误:

inlining failed in call to 'always_inline' '_mm512_aesenc_epi128': target specific option mismatch

我的CPU既不支持AVX512,也不支持VAES,然而我希望与其他体系结构保持兼容,因为这会把吞吐量提升到四倍。添加这个不必要的标志会导致程序在我的CPU上不可运行。我只有在实际使用AVX512内在指令时才需要启用该标志。

如何解决?我需要让编译器在未使用这些内在指令时不要强制指令集标志(例如 __VAES__ 未定义,正如上面使用VAES版本的aes_enc_block_x4宏也是如此)

UPD1:按照建议,我尝试使用 __attribute__((target())) 提示,但错误仍然存在。更新后的代码:

#if defined __VAES__
# include <vaesintrin.h>
static forceinline simde__m512i __attribute__((target("aes,vaes,avx512f,evex512"))) aes_enc_block_x4(simde__m512i blocks_pad_512, simde__m512i round_keys_of_4) {
    return (simde__m512i)_mm512_aesenc_epi128(blocks_pad_512, round_keys_of_4);
}
#else
// defining aes_enc_block_x4 function for 256-bit and 128-bit arrays
#endif

UPD2:基于宏的解决方案需要在代码中使用宏选择的pragmas来让编译器静默。与MSVC不同,在GCC和 Clang上必须通过pragmas选择目标架构,因此最终的代码看起来像这样:

#if defined __VAES__
# include <vaesintrin.h>
# ifdef __clang__
#  if __clang_major__ >= 18 && __clang_major__ < 22
#   pragma clang attribute push(__attribute__((target("aes,vaes,avx512f,evex512"))), apply_to = function)
#  else
#   pragma clang attribute push(__attribute__((target("aes,vaes,avx512f"))), apply_to = function)
#  endif
# elif defined(__GNUC__)
#  pragma GCC target("aes,vaes,avx512f")
# endif
# define aes_enc_block_x4(blocks_pad_512, round_key_of_4) (simde__m512i)_mm512_aesenc_epi128(blocks_pad_512, round_key_of_4)
# ifdef __clang__
#  pragma clang attribute pop
# endif
#else
// defining aes_enc_block_x4 for 256-bit and 128-bit arrays
#endif
//

解决方案

将为特定CPU编写的函数拆分到一个独立的.C文件中,然后可以用允许这些CPU特定指令被接受并翻译的编译选项来编译该.C文件;或者你必须把它回退到内联汇编(不推荐)写进你的.C文件。

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章