optimization.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. //
  2. // Copyright 2017 The Abseil Authors.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // https://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. //
  16. // -----------------------------------------------------------------------------
  17. // File: optimization.h
  18. // -----------------------------------------------------------------------------
  19. //
  20. // This header file defines portable macros for performance optimization.
  21. //
  22. // This header is included in both C++ code and legacy C code and thus must
  23. // remain compatible with both C and C++. C compatibility will be removed if
  24. // the legacy code is removed or converted to C++. Do not include this header in
  25. // new code that requires C compatibility or assume C compatibility will remain
  26. // indefinitely.
  27. // SKIP_ABSL_INLINE_NAMESPACE_CHECK
  28. #ifndef ABSL_BASE_OPTIMIZATION_H_
  29. #define ABSL_BASE_OPTIMIZATION_H_
  30. #include <assert.h>
  31. #ifdef __cplusplus
  32. // Included for std::unreachable()
  33. #include <utility>
  34. #endif // __cplusplus
  35. #include "absl/base/config.h"
  36. #include "absl/base/options.h"
  37. // ABSL_BLOCK_TAIL_CALL_OPTIMIZATION
  38. //
  39. // Instructs the compiler to avoid optimizing tail-call recursion. This macro is
  40. // useful when you wish to preserve the existing function order within a stack
  41. // trace for logging, debugging, or profiling purposes.
  42. //
  43. // Example:
  44. //
  45. // int f() {
  46. // int result = g();
  47. // ABSL_BLOCK_TAIL_CALL_OPTIMIZATION();
  48. // return result;
  49. // }
  50. #if defined(__pnacl__)
  51. #define ABSL_BLOCK_TAIL_CALL_OPTIMIZATION() if (volatile int x = 0) { (void)x; }
  52. #elif defined(__clang__)
  53. // Clang will not tail call given inline volatile assembly.
  54. #define ABSL_BLOCK_TAIL_CALL_OPTIMIZATION() __asm__ __volatile__("")
  55. #elif defined(__GNUC__)
  56. // GCC will not tail call given inline volatile assembly.
  57. #define ABSL_BLOCK_TAIL_CALL_OPTIMIZATION() __asm__ __volatile__("")
  58. #elif defined(_MSC_VER)
  59. #include <intrin.h>
  60. // The __nop() intrinsic blocks the optimisation.
  61. #define ABSL_BLOCK_TAIL_CALL_OPTIMIZATION() __nop()
  62. #else
  63. #define ABSL_BLOCK_TAIL_CALL_OPTIMIZATION() if (volatile int x = 0) { (void)x; }
  64. #endif
  65. // ABSL_CACHELINE_SIZE
  66. //
  67. // Explicitly defines the size of the L1 cache for purposes of alignment.
  68. // Setting the cacheline size allows you to specify that certain objects be
  69. // aligned on a cacheline boundary with `ABSL_CACHELINE_ALIGNED` declarations.
  70. // (See below.)
  71. //
  72. // NOTE: this macro should be replaced with the following C++17 features, when
  73. // those are generally available:
  74. //
  75. // * `std::hardware_constructive_interference_size`
  76. // * `std::hardware_destructive_interference_size`
  77. //
  78. // See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0154r1.html
  79. // for more information.
  80. #if defined(__GNUC__)
  81. // Cache line alignment
  82. #if defined(__i386__) || defined(__x86_64__)
  83. #define ABSL_CACHELINE_SIZE 64
  84. #elif defined(__powerpc64__)
  85. #define ABSL_CACHELINE_SIZE 128
  86. #elif defined(__aarch64__)
  87. // We would need to read special register ctr_el0 to find out L1 dcache size.
  88. // This value is a good estimate based on a real aarch64 machine.
  89. #define ABSL_CACHELINE_SIZE 64
  90. #elif defined(__arm__)
  91. // Cache line sizes for ARM: These values are not strictly correct since
  92. // cache line sizes depend on implementations, not architectures. There
  93. // are even implementations with cache line sizes configurable at boot
  94. // time.
  95. #if defined(__ARM_ARCH_5T__)
  96. #define ABSL_CACHELINE_SIZE 32
  97. #elif defined(__ARM_ARCH_7A__)
  98. #define ABSL_CACHELINE_SIZE 64
  99. #endif
  100. #endif
  101. #endif
  102. #ifndef ABSL_CACHELINE_SIZE
  103. // A reasonable default guess. Note that overestimates tend to waste more
  104. // space, while underestimates tend to waste more time.
  105. #define ABSL_CACHELINE_SIZE 64
  106. #endif
  107. // ABSL_CACHELINE_ALIGNED
  108. //
  109. // Indicates that the declared object be cache aligned using
  110. // `ABSL_CACHELINE_SIZE` (see above). Cacheline aligning objects allows you to
  111. // load a set of related objects in the L1 cache for performance improvements.
  112. // Cacheline aligning objects properly allows constructive memory sharing and
  113. // prevents destructive (or "false") memory sharing.
  114. //
  115. // NOTE: callers should replace uses of this macro with `alignas()` using
  116. // `std::hardware_constructive_interference_size` and/or
  117. // `std::hardware_destructive_interference_size` when C++17 becomes available to
  118. // them.
  119. //
  120. // See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0154r1.html
  121. // for more information.
  122. //
  123. // On some compilers, `ABSL_CACHELINE_ALIGNED` expands to an `__attribute__`
  124. // or `__declspec` attribute. For compilers where this is not known to work,
  125. // the macro expands to nothing.
  126. //
  127. // No further guarantees are made here. The result of applying the macro
  128. // to variables and types is always implementation-defined.
  129. //
  130. // WARNING: It is easy to use this attribute incorrectly, even to the point
  131. // of causing bugs that are difficult to diagnose, crash, etc. It does not
  132. // of itself guarantee that objects are aligned to a cache line.
  133. //
  134. // NOTE: Some compilers are picky about the locations of annotations such as
  135. // this attribute, so prefer to put it at the beginning of your declaration.
  136. // For example,
  137. //
  138. // ABSL_CACHELINE_ALIGNED static Foo* foo = ...
  139. //
  140. // class ABSL_CACHELINE_ALIGNED Bar { ...
  141. //
  142. // Recommendations:
  143. //
  144. // 1) Consult compiler documentation; this comment is not kept in sync as
  145. // toolchains evolve.
  146. // 2) Verify your use has the intended effect. This often requires inspecting
  147. // the generated machine code.
  148. // 3) Prefer applying this attribute to individual variables. Avoid
  149. // applying it to types. This tends to localize the effect.
  150. #if defined(__clang__) || defined(__GNUC__)
  151. #define ABSL_CACHELINE_ALIGNED __attribute__((aligned(ABSL_CACHELINE_SIZE)))
  152. #elif defined(_MSC_VER)
  153. #define ABSL_CACHELINE_ALIGNED __declspec(align(ABSL_CACHELINE_SIZE))
  154. #else
  155. #define ABSL_CACHELINE_ALIGNED
  156. #endif
  157. // ABSL_PREDICT_TRUE, ABSL_PREDICT_FALSE
  158. //
  159. // Enables the compiler to prioritize compilation using static analysis for
  160. // likely paths within a boolean branch.
  161. //
  162. // Example:
  163. //
  164. // if (ABSL_PREDICT_TRUE(expression)) {
  165. // return result; // Faster if more likely
  166. // } else {
  167. // return 0;
  168. // }
  169. //
  170. // Compilers can use the information that a certain branch is not likely to be
  171. // taken (for instance, a CHECK failure) to optimize for the common case in
  172. // the absence of better information (ie. compiling gcc with `-fprofile-arcs`).
  173. //
  174. // Recommendation: Modern CPUs dynamically predict branch execution paths,
  175. // typically with accuracy greater than 97%. As a result, annotating every
  176. // branch in a codebase is likely counterproductive; however, annotating
  177. // specific branches that are both hot and consistently mispredicted is likely
  178. // to yield performance improvements.
  179. #if ABSL_HAVE_BUILTIN(__builtin_expect) || \
  180. (defined(__GNUC__) && !defined(__clang__))
  181. #define ABSL_PREDICT_FALSE(x) (__builtin_expect(false || (x), false))
  182. #define ABSL_PREDICT_TRUE(x) (__builtin_expect(false || (x), true))
  183. #else
  184. #define ABSL_PREDICT_FALSE(x) (x)
  185. #define ABSL_PREDICT_TRUE(x) (x)
  186. #endif
  187. // `ABSL_INTERNAL_IMMEDIATE_ABORT_IMPL()` aborts the program in the fastest
  188. // possible way, with no attempt at logging. One use is to implement hardening
  189. // aborts with ABSL_OPTION_HARDENED. Since this is an internal symbol, it
  190. // should not be used directly outside of Abseil.
  191. #if ABSL_HAVE_BUILTIN(__builtin_trap) || \
  192. (defined(__GNUC__) && !defined(__clang__))
  193. #define ABSL_INTERNAL_IMMEDIATE_ABORT_IMPL() __builtin_trap()
  194. #else
  195. #define ABSL_INTERNAL_IMMEDIATE_ABORT_IMPL() abort()
  196. #endif
  197. // `ABSL_INTERNAL_UNREACHABLE_IMPL()` is the platform specific directive to
  198. // indicate that a statement is unreachable, and to allow the compiler to
  199. // optimize accordingly. Clients should use `ABSL_UNREACHABLE()`, which is
  200. // defined below.
  201. #if defined(__cpp_lib_unreachable) && __cpp_lib_unreachable >= 202202L
  202. #define ABSL_INTERNAL_UNREACHABLE_IMPL() std::unreachable()
  203. #elif defined(__GNUC__) || ABSL_HAVE_BUILTIN(__builtin_unreachable)
  204. #define ABSL_INTERNAL_UNREACHABLE_IMPL() __builtin_unreachable()
  205. #elif ABSL_HAVE_BUILTIN(__builtin_assume)
  206. #define ABSL_INTERNAL_UNREACHABLE_IMPL() __builtin_assume(false)
  207. #elif defined(_MSC_VER)
  208. #define ABSL_INTERNAL_UNREACHABLE_IMPL() __assume(false)
  209. #else
  210. #define ABSL_INTERNAL_UNREACHABLE_IMPL()
  211. #endif
  212. // `ABSL_UNREACHABLE()` is an unreachable statement. A program which reaches
  213. // one has undefined behavior, and the compiler may optimize accordingly.
  214. #if ABSL_OPTION_HARDENED == 1 && defined(NDEBUG)
  215. // Abort in hardened mode to avoid dangerous undefined behavior.
  216. #define ABSL_UNREACHABLE() \
  217. do { \
  218. ABSL_INTERNAL_IMMEDIATE_ABORT_IMPL(); \
  219. ABSL_INTERNAL_UNREACHABLE_IMPL(); \
  220. } while (false)
  221. #else
  222. // The assert only fires in debug mode to aid in debugging.
  223. // When NDEBUG is defined, reaching ABSL_UNREACHABLE() is undefined behavior.
  224. #define ABSL_UNREACHABLE() \
  225. do { \
  226. /* NOLINTNEXTLINE: misc-static-assert */ \
  227. assert(false && "ABSL_UNREACHABLE reached"); \
  228. ABSL_INTERNAL_UNREACHABLE_IMPL(); \
  229. } while (false)
  230. #endif
  231. // ABSL_ASSUME(cond)
  232. //
  233. // Informs the compiler that a condition is always true and that it can assume
  234. // it to be true for optimization purposes.
  235. //
  236. // WARNING: If the condition is false, the program can produce undefined and
  237. // potentially dangerous behavior.
  238. //
  239. // In !NDEBUG mode, the condition is checked with an assert().
  240. //
  241. // NOTE: The expression must not have side effects, as it may only be evaluated
  242. // in some compilation modes and not others. Some compilers may issue a warning
  243. // if the compiler cannot prove the expression has no side effects. For example,
  244. // the expression should not use a function call since the compiler cannot prove
  245. // that a function call does not have side effects.
  246. //
  247. // Example:
  248. //
  249. // int x = ...;
  250. // ABSL_ASSUME(x >= 0);
  251. // // The compiler can optimize the division to a simple right shift using the
  252. // // assumption specified above.
  253. // int y = x / 16;
  254. //
  255. #if !defined(NDEBUG)
  256. #define ABSL_ASSUME(cond) assert(cond)
  257. #elif ABSL_HAVE_BUILTIN(__builtin_assume)
  258. #define ABSL_ASSUME(cond) __builtin_assume(cond)
  259. #elif defined(_MSC_VER)
  260. #define ABSL_ASSUME(cond) __assume(cond)
  261. #elif defined(__cpp_lib_unreachable) && __cpp_lib_unreachable >= 202202L
  262. #define ABSL_ASSUME(cond) ((cond) ? void() : std::unreachable())
  263. #elif defined(__GNUC__) || ABSL_HAVE_BUILTIN(__builtin_unreachable)
  264. #define ABSL_ASSUME(cond) ((cond) ? void() : __builtin_unreachable())
  265. #elif ABSL_INTERNAL_CPLUSPLUS_LANG >= 202002L
  266. // Unimplemented. Uses the same definition as ABSL_ASSERT in the NDEBUG case.
  267. #define ABSL_ASSUME(expr) (decltype((expr) ? void() : void())())
  268. #else
  269. #define ABSL_ASSUME(expr) (false ? ((expr) ? void() : void()) : void())
  270. #endif
  271. // ABSL_INTERNAL_UNIQUE_SMALL_NAME(cond)
  272. // This macro forces small unique name on a static file level symbols like
  273. // static local variables or static functions. This is intended to be used in
  274. // macro definitions to optimize the cost of generated code. Do NOT use it on
  275. // symbols exported from translation unit since it may cause a link time
  276. // conflict.
  277. //
  278. // Example:
  279. //
  280. // #define MY_MACRO(txt)
  281. // namespace {
  282. // char VeryVeryLongVarName[] ABSL_INTERNAL_UNIQUE_SMALL_NAME() = txt;
  283. // const char* VeryVeryLongFuncName() ABSL_INTERNAL_UNIQUE_SMALL_NAME();
  284. // const char* VeryVeryLongFuncName() { return txt; }
  285. // }
  286. //
  287. #if defined(__GNUC__)
  288. #define ABSL_INTERNAL_UNIQUE_SMALL_NAME2(x) #x
  289. #define ABSL_INTERNAL_UNIQUE_SMALL_NAME1(x) ABSL_INTERNAL_UNIQUE_SMALL_NAME2(x)
  290. #define ABSL_INTERNAL_UNIQUE_SMALL_NAME() \
  291. asm(ABSL_INTERNAL_UNIQUE_SMALL_NAME1(.absl.__COUNTER__))
  292. #else
  293. #define ABSL_INTERNAL_UNIQUE_SMALL_NAME()
  294. #endif
  295. #endif // ABSL_BASE_OPTIMIZATION_H_