<table border="1" cellspacing="0" cellpadding="8">
    <tr>
        <th>Issue</th>
        <td>
            <a href=https://github.com/llvm/llvm-project/issues/80100>80100</a>
        </td>
    </tr>

    <tr>
        <th>Summary</th>
        <td>
            bit-count operation fallbacks can be optimized based on mask
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            new issue
      </td>
    </tr>

    <tr>
      <th>Assignees</th>
      <td>
      </td>
    </tr>

    <tr>
      <th>Reporter</th>
      <td>
          Validark
      </td>
    </tr>
</table>

<pre>
    Let's say for example I want to popcount a value where I know only specific bits are set. On a machine without a dedicated popcount unit, I might do a fallback like so.

```zig
export fn popCountDefault(x: u64) u8 {
    return @popCount(x & 0x8080808080808080);
}

export fn popCountManual(x: u64) u8 {
    return @truncate((((x >> 7) & 0x0101010101010101) * 0x0101010101010101) >> 56);
}
```

The other other bit-count operations can be defined in terms of popcount.

```zig
export fn ctzDefault(x: u64) u8 {
    return @ctz(x & 0x8080808080808080) / 8;
}

export fn ctzManual(x: u64) u8 {
    const y = (x >> 7) & 0x0101010101010101;
    const z = ~y & (y -% 1);
    return @truncate(((z & 0x0101010101010101) * 0x0101010101010101) >> 56);
}
```

At the moment, no matter what we know about the argument `x`, we get the same emit for these operations. [Godbolt link](https://zig.godbolt.org/z/qv47ooG91)
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJy8VE-P47YP_TTMhZhAlmPHPviQmWwWC_x-6KXoXZYZW40suRI9-XPoZy8Uz87OYLfd6aWwIAMi3yOlR1LFaHpH1EDxCMV-pWYefGh-U9Z0KpxWre-uzf-IQW4jRnXFow9IFzVOlvALnpVjZI-Tn7SfHaPCZ2VnwvNAITmcnD-jd_aKcSJtjkZjaziiCoSReI2_OFQ4Kj0YR3g2PPg5sXTUGa2Yum_UszMM8gm_4Gj6gbHzqPCorG2VPqE1J8Lo1yD2IHYveymWdTP9ckKXyQfGo0u0T4l2T0c1WwZZXSDf4VxuQNY4VwjbxwWDiBiI5-AQNuIrLgEQZIniUon3H8ga8hcwbPdvM_o-_v-Vm5X9cHgOs0vvArJ6XReE_BPkn3CbsEtOInv_LZbd31kWfFH-OPWvz_j2Jr8OhJ4HCi97a_hh0clPFBQb7yJq5bAl7OhoHHVoHDKFMaI_vsr6YcE03_6tVppv_ywTgjxg9XOxNN8-pJP2LjJeEfI9flSY_Dv87Y7_83pHgKyu-ACywOytOD-pitt_VQY7Rh4IRz-Su3en8zgqZgp4HhTjmZYRoNrU18lVhX5OzgiluCQ2-ZS8elrMUY2ENBq-TxoeKNKbilojFI-ffdd6y2iNO0GxB1kNzFOEfAfyAPJwM_26X3zWPvTpBOThj-fN1vvPdbrpqmvyrs5rtaIm24qy3Jbbol4NDRVCd5RVbdnmG9LUallRrbQWbVZWoliZRgq5EVmeiU0h83otsyyvj5viWNdUVSXBRtCojF1b-zym8CsT40xNJTIhVla1ZON92Erp6Ix3I0iZZm9oEuahnfsIG2FN5PiNhQ1ban7QZa8j8LXd_MRmNDfqsFWROvQORxVPqznY5v1L9YaHuV1rP4I8pFAvv4cp-N9JM8jDPcEI8nC_wF8BAAD__9ZYysU">