Re: [PATCH v2] libbpf: Fix is_pow_of_2

From: Andrii Nakryiko
Date: Fri Jun 03 2022 - 14:34:37 EST


On Fri, Jun 3, 2022 at 9:58 AM Joe Perches <joe@xxxxxxxxxxx> wrote:
>
> On Thu, 2022-06-02 at 22:57 -0700, Ian Rogers wrote:
> > On Thu, Jun 2, 2022 at 10:52 PM Ian Rogers <irogers@xxxxxxxxxx> wrote:
> > > From: Yuze Chi <chiyuze@xxxxxxxxxx>
> []
> > > diff --git a/tools/lib/bpf/libbpf_internal.h b/tools/lib/bpf/libbpf_internal.h
> []
> > > @@ -580,4 +580,9 @@ struct bpf_link * usdt_manager_attach_usdt(struct usdt_manager *man,
> > > const char *usdt_provider, const char *usdt_name,
> > > __u64 usdt_cookie);
> > >
> > > +static inline bool is_pow_of_2(size_t x)
> > > +{
> > > + return x && (x & (x - 1)) == 0;
> > > +}
> > > +
> > > #endif /* __LIBBPF_LIBBPF_INTERNAL_H */
>
> If speed of execution is a potential issue, maybe:

It's not, as it's not in any sort of high-frequency hot path. But even
if it was, we should be careful with __builtin_popcount() because
depending on target CPU architecture __builtin_popcount() can be
turned into a helper function call instead of using hardware
instruction. But either way, keeping it simple is prefereable.

>
> #if __has_builtin(__builtin_popcount)
> return __builtin_popcount(x) == 1;
> #else
> return x && (x & (x-1)) == 0;
> #endif
>