HDK
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
hints.h
Go to the documentation of this file.
1 //
2 // Copyright 2016 Pixar
3 //
4 // Licensed under the terms set forth in the LICENSE.txt file available at
5 // https://openusd.org/license.
6 //
7 #ifndef PXR_BASE_ARCH_HINTS_H
8 #define PXR_BASE_ARCH_HINTS_H
9 
10 #include "pxr/base/arch/defines.h"
11 
12 /// \file arch/hints.h
13 /// Compiler hints.
14 ///
15 /// \c ARCH_LIKELY(bool-expr) and \c ARCH_UNLIKELY(bool-expr) will evaluate to
16 /// the value of bool-expr but will also emit compiler intrinsics providing
17 /// hints for branch prediction if the compiler has such intrinsics. It is
18 /// advised that you only use these in cases where you empirically know the
19 /// outcome of bool-expr to a very high degree of certainty. For example,
20 /// fatal-error cases, invariants, first-time initializations, etc.
21 
22 #if defined(ARCH_COMPILER_GCC) || defined(ARCH_COMPILER_CLANG)
23 
24 #define ARCH_LIKELY(x) (__builtin_expect((bool)(x), true))
25 #define ARCH_UNLIKELY(x) (__builtin_expect((bool)(x), false))
26 
27 #else
28 
29 #define ARCH_LIKELY(x) (x)
30 #define ARCH_UNLIKELY(x) (x)
31 
32 #endif
33 
34 /// \c ARCH_GUARANTEE_TO_COMPILER(bool-expr) informs the compiler about value
35 /// constraints to help it make better optimizations. It is of critical
36 /// importance that the guarantee is in fact always 100% true, otherwise the
37 /// compiler may generate invalid code.
38 ///
39 /// This can be useful, for example, when an out-of-line function call could
40 /// potentially change a value previously known to compiler, but does not, based
41 /// on code invariants.
42 ///
43 /// This hint is best used after investigating generated assembly code and
44 /// seeing useless/unreachable code being generated that can be prevented with
45 /// this hint. This hint is often times not necessary, and should never be
46 /// inserted on a whim. The compiler will run with the promises we make it to
47 /// the ends of the earth, and this can lead to surprising results
48 /// (e.g. undefined behavior) if we are not careful.
49 
50 #if defined(ARCH_COMPILER_GCC) || \
51  defined(ARCH_COMPILER_CLANG) || \
52  defined(ARCH_COMPILER_ICC)
53 
54 // Intentionally using __builtin_unreachable on clang for consistency, since
55 // __builtin_assume does not evaluate the expression, and our only option on gcc
56 // is the __builtin_unreachable branch.
57 
58 #define ARCH_GUARANTEE_TO_COMPILER(x) \
59  if (static_cast<bool>(x)) { } else { __builtin_unreachable(); }
60 
61 #else
62 
63 #define ARCH_GUARANTEE_TO_COMPILER(x)
64 
65 #endif
66 
67 
68 #endif // PXR_BASE_ARCH_HINTS_H