[PATCH 2/7] Add 'likely' and 'unlikely' macros

Kenneth Graunke kenneth at whitecape.org
Mon May 11 23:24:26 PDT 2015


On Monday, May 11, 2015 09:23:53 PM Keith Packard wrote:
> These two macros provide hints to the compiler about common code paths
> to help it optimize a bit better.
> 
> Signed-off-by: Keith Packard <keithp at keithp.com>
> ---
>  include/misc.h | 8 ++++++++
>  1 file changed, 8 insertions(+)
> 
> diff --git a/include/misc.h b/include/misc.h
> index 9b1c03a..74889f5 100644
> --- a/include/misc.h
> +++ b/include/misc.h
> @@ -291,6 +291,14 @@ version_compare(uint32_t a_major, uint32_t a_minor,
>  #define SwapRestL(stuff) \
>      SwapLongs((CARD32 *)(stuff + 1), LengthRestL(stuff))
>  
> +#if defined(__GNUC__) && (__GNUC__ > 2) && defined(__OPTIMIZE__)
> +#define likely(expr) (__builtin_expect (!!(expr), 1))
> +#define unlikely(expr) (__builtin_expect (!!(expr), 0))
> +#else
> +#define likely(expr) (expr)
> +#define unlikely(expr) (expr)
> +#endif
> +
>  #if defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))
>  void __attribute__ ((error("wrong sized variable passed to swap")))
>  wrong_size(void);
> 

In Mesa, we import this bit of m4 from the autoconf archive:
http://www.gnu.org/software/autoconf-archive/ax_gcc_builtin.html

then in configure.ac do:

AX_GCC_BUILTIN([__builtin_expect])

which lets us write this as:

#if !defined(HAVE___BUILTIN_EXPECT)
#  define __builtin_expect(x, y) (x)
#endif

#define likely(x)   __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)

We used to do ad-hoc GCC version checks like this, and we've had much
less trouble since moving to the autoconf checks and HAVE_feature macros.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 819 bytes
Desc: This is a digitally signed message part.
URL: <http://lists.x.org/archives/xorg-devel/attachments/20150511/1b6a83f5/attachment-0001.sig>


More information about the xorg-devel mailing list