如何通过内联函数强制常量传播

How to force const propagation through an inline function?

本文关键字:常量 传播 函数 何通过      更新时间:2023-10-16

我试图强制预处理器为我执行一些数学运算,以便将常量传播到内联程序集中。以下是简化的情况:

inline
unsigned int RotateRight(unsigned char value, unsigned int amount)
{
    COMPILE_ASSERT(((unsigned char)(amount%32)) < 32);
    __asm__ ("rorb %1, %0" : "+mq" (value) : "I" ((unsigned char)(amount%32)));
    return value;
}

上面的代码依赖于 CPU 特定的功能,我可以接受它(当 GCC 可用时,它实际上是 x86/x64 Linux 上的模板专用化(。 "I"约束表示整数值必须在[0,31](含(之间。

代码的调用方如下所示:

byte b1 = RotateRight(1, 1);
byte b2 = RotateRight(1, 31);

RotateRight(1, 31)来自密码学家(它在 C/C++ 中未定义的行为,因为字节只能在 [0,7] 范围内旋转(。我可以使用 ASM 摆脱 C/C++ 约束。由于移位量在编译时是已知的,我希望在编译时减少它;我想要使用生成的即时 8 的 rorb 版本。

如果没有COMPILE_ASSERT,代码可以编译,但我不确定常量是否正在传播。也就是说,它可能以意外的减少(% 32 (生成。使用COMPILE_ASSERT,代码无法编译。

$ make validat1.o
g++ -DNDEBUG -g2 -O3 -march=native -pipe -c validat1.cpp
In file included from simple.h:10:0,
                 from filters.h:6,
                 from files.h:5,
                 from validat1.cpp:6:
misc.h: In function ‘T CryptoPP::rotlFixed(T, unsigned int) [with T = unsigned char]’:
misc.h:940:43: error: ‘y’ cannot appear in a constant-expression
  CRYPTOPP_COMPILE_ASSERT(((unsigned char)(y%32)) < 32);
                                           ^
misc.h:72:85: note: in definition of macro ‘CRYPTOPP_COMPILE_ASSERT_INSTANCE’
 _COMPILE_ASSERT_INSTANCE(assertion, instance) static CompileAssert<(assertion)>

我知道我不应该使用#define,C++内联函数就是答案。但我觉得我正在遭受脱节。

如何强制编译器传播涉及const值的值?

或者,如果COMPILE_ASSERT是错误的工具(正在传播const(,如何设置测试以便验证是否使用了 rorb 的 immediate-8 版本?


相关,这是一个C++03项目。它不使用Boost,不使用Cmake,不使用Autotools等。

amount 指定为函数参数时,会丢失其编译时恒常性。

你为什么不声明金额是模板参数?在这种情况下,函数用户也会被迫传递编译时常量,这也很好。

若要确保将 shift 用作编译时常量,可以创建一个静态 const 局部变量。

template<unsigned int amount> inline
unsigned int RotateRight(unsigned char value)
{
    static const unsigned char shift = (unsigned char)(amount%32);
    __asm__ ("rorb %1, %0" : "+mq" (value) : "I" (shift));
    return value;
}