Skip to content

Commit

Permalink
ctz/clz fix
Browse files Browse the repository at this point in the history
  • Loading branch information
yamt committed Aug 12, 2024
1 parent 8236407 commit f893602
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 17 deletions.
38 changes: 25 additions & 13 deletions lib/insn.c
Original file line number Diff line number Diff line change
Expand Up @@ -235,17 +235,14 @@ wasm_fmax(double a, double b)
static uint32_t
clz(uint32_t v)
{
if (v == 0) {
return 32;
}
#if __has_builtin(__builtin_clz)
return __builtin_clz(v);
#else
uint32_t cnt = 0;
uint32_t u = v;
while ((u & 0x80000000) == 0) {
cnt++;
u << 1;
u <<= 1;
}
return cnt;
#endif
Expand All @@ -254,9 +251,6 @@ clz(uint32_t v)
static uint32_t
ctz(uint32_t v)
{
if (v == 0) {
return 32;
}
#if __has_builtin(__builtin_ctz)
return __builtin_ctz(v);
#else
Expand All @@ -270,6 +264,24 @@ ctz(uint32_t v)
#endif
}

static uint32_t
wasm_clz(uint32_t v)
{
if (v == 0) {
return 32;
}
return clz(v);
}

static uint32_t
wasm_ctz(uint32_t v)
{
if (v == 0) {
return 32;
}
return ctz(v);
}

static uint32_t
wasm_popcount(uint32_t v)
{
Expand All @@ -287,29 +299,29 @@ wasm_popcount(uint32_t v)
}

static uint64_t
clz64(uint64_t v)
wasm_clz64(uint64_t v)
{
if (v == 0) {
return 64;
}
uint32_t high = v >> 32;
if (high == 0) {
return 32 + __builtin_clz(v);
return 32 + clz(v);
}
return __builtin_clz(high);
return clz(high);
}

static uint64_t
ctz64(uint64_t v)
wasm_ctz64(uint64_t v)
{
if (v == 0) {
return 64;
}
uint32_t low = (uint32_t)v;
if (low == 0) {
return 32 + __builtin_ctz((uint32_t)(v >> 32));
return 32 + ctz((uint32_t)(v >> 32));
}
return __builtin_ctz(low);
return ctz(low);
}

static uint64_t
Expand Down
8 changes: 4 additions & 4 deletions lib/insn_impl_base.h
Original file line number Diff line number Diff line change
Expand Up @@ -383,8 +383,8 @@ CMPOP(i64_le_u, 64, uint64_t, <=)
CMPOP(i64_ge_s, 64, int64_t, >=)
CMPOP(i64_ge_u, 64, uint64_t, >=)

BITCOUNTOP(i32_clz, i32, clz)
BITCOUNTOP(i32_ctz, i32, ctz)
BITCOUNTOP(i32_clz, i32, wasm_clz)
BITCOUNTOP(i32_ctz, i32, wasm_ctz)
BITCOUNTOP(i32_popcnt, i32, wasm_popcount)

BINOP(i32_add, i, 32, ADD)
Expand All @@ -406,8 +406,8 @@ BINOP(i32_shr_u, i, 32, SHR_U)
BINOP(i32_rotl, i, 32, ROTL)
BINOP(i32_rotr, i, 32, ROTR)

BITCOUNTOP(i64_clz, i64, clz64)
BITCOUNTOP(i64_ctz, i64, ctz64)
BITCOUNTOP(i64_clz, i64, wasm_clz64)
BITCOUNTOP(i64_ctz, i64, wasm_ctz64)
BITCOUNTOP(i64_popcnt, i64, wasm_popcount64)

BINOP(i64_add, i, 64, ADD)
Expand Down

0 comments on commit f893602

Please sign in to comment.