Skip to content

Basic checks against count-leading/trailing zeroes should be optimized #76810

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Validark opened this issue Jan 3, 2024 · 0 comments
Open

Comments

@Validark
Copy link

Validark commented Jan 3, 2024

Here are some basic transformations applicable on architectures lacking fast clz/ctz instructions: Godbolt link

const T = u64;

export fn isCountLeadingZeroesEven1(x: T) bool {
    return 1 == @clz(x) & 1;
}

export fn isCountLeadingZeroesEven2(x: T) bool {
    const odd_bits: @TypeOf(x) =
@bitCast(@as(@Vector(@divExact(@bitSizeOf(@TypeOf(x)), 8), u8), @splat(0xaa)));
    return (x & ~odd_bits) > (x & odd_bits);
}

The previous code [1, 2] is actually useful for Atkinson et al.'s 1986 Min-Max Heap for telling whether a layer is a min layer or max layer. Here is an analogous transformation for count-trailing zeroes:

const T = u64;

export fn isCountTrailingZeroesEven1(x: u64) bool {
    return 1 == @ctz(x) & 1;
}

export fn isCountTrailingZeroesEven2(x: u64) bool {
    const odd_bits: @TypeOf(x) =
@bitCast(@as(@Vector(@divExact(@bitSizeOf(@TypeOf(x)), 8), u8), @splat(0xaa)));
    return ((x & (~x +% 1)) & odd_bits) != 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants