以下代碼在GCC中調用clz/ctz的內置函數,並在其他系統上調用C版本。顯然,如果系統具有像x86和ARM這樣的內置clz/ctz指令,那麼C版本就不太理想。如何使用MSVC intrinsics獲得這個GCC代碼的等價物?
#ifdef __GNUC__
#define clz(x) __builtin_clz(x)
#define ctz(x) __builtin_ctz(x)
#else
static uint32_t ALWAYS_INLINE popcnt(uint32_t x)
{
x -= ((x >> 1) & 0x55555555);
x = (((x >> 2) & 0x33333333) + (x & 0x33333333));
x = (((x >> 4) + x) & 0x0f0f0f0f);
x += (x >> 8);
x += (x >> 16);
return x & 0x0000003f;
}
static uint32_t ALWAYS_INLINE clz(uint32_t x)
{
x |= (x >> 1);
x |= (x >> 2);
x |= (x >> 4);
x |= (x >> 8);
x |= (x >> 16);
return 32 - popcnt(x);
}
static uint32_t ALWAYS_INLINE ctz(uint32_t x)
{
return popcnt((x & -x) - 1);
}
#endif
我需要調用哪些函數,需要包含哪些頭文件等,以在此爲MSVC添加適當的ifdef?我已經看過this page,但我不完全確定#pragma的用途(是否需要?)以及它對MSVC版本編譯要求的限制。作爲沒有真正使用MSVC的人,我也不知道這些內在函數在其他體系結構上是否具有C等價物,或者在定義它們時是否必須#ifdef x86/x86_64。
上述引用的頁面指的是.NET運行時的一部分功能,您是試圖構建.NET程序還是本機Windows可執行文件? – 2008-12-10 13:49:46
這是一個本地Windows可執行文件 - 我要求的部分原因是我發現現在很難找到真正討論C的微軟文檔頁面。 – 2008-12-10 18:04:59
Libcxx實現https://github.com/llvm-mirror/libcxx/blob/9dcbb46826fd4d29b1485f25e8986d36019a6dca/include/support/win32/support.h#L106-L182 – KindDragon 2017-04-03 10:35:54