1 // Copyright 2014 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef V8_BASE_MACROS_H_
6 #define V8_BASE_MACROS_H_
13 #include "src/base/build_config.h"
14 #include "src/base/compiler-specific.h"
15 #include "src/base/logging.h"
18 // The expression OFFSET_OF(type, field) computes the byte-offset
19 // of the specified field relative to the containing type. This
20 // corresponds to 'offsetof' (in stddef.h), except that it doesn't
21 // use 0 or NULL, which causes a problem with the compiler warnings
22 // we have enabled (which is also why 'offsetof' doesn't seem to work).
23 // Here we simply use the non-zero value 4, which seems to work.
24 #define OFFSET_OF(type, field) \
25 (reinterpret_cast<intptr_t>(&(reinterpret_cast<type*>(4)->field)) - 4)
30 // ARRAYSIZE_UNSAFE performs essentially the same calculation as arraysize,
31 // but can be used on anonymous types or types defined inside
32 // functions. It's less safe than arraysize as it accepts some
33 // (although not all) pointers. Therefore, you should use arraysize
36 // The expression ARRAYSIZE_UNSAFE(a) is a compile-time constant of type
39 // ARRAYSIZE_UNSAFE catches a few type errors. If you see a compiler error
41 // "warning: division by zero in ..."
43 // when using ARRAYSIZE_UNSAFE, you are (wrongfully) giving it a pointer.
44 // You should only use ARRAYSIZE_UNSAFE on statically allocated arrays.
46 // The following comments are on the implementation details, and can
47 // be ignored by the users.
49 // ARRAYSIZE_UNSAFE(arr) works by inspecting sizeof(arr) (the # of bytes in
50 // the array) and sizeof(*(arr)) (the # of bytes in one array
51 // element). If the former is divisible by the latter, perhaps arr is
52 // indeed an array, in which case the division result is the # of
53 // elements in the array. Otherwise, arr cannot possibly be an array,
54 // and we generate a compiler error to prevent the code from
57 // Since the size of bool is implementation-defined, we need to cast
58 // !(sizeof(a) & sizeof(*(a))) to size_t in order to ensure the final
59 // result has type size_t.
61 // This macro is not perfect as it wrongfully accepts certain
62 // pointers, namely where the pointer size is divisible by the pointee
63 // size. Since all our code has to go through a 32-bit compiler,
64 // where a pointer is 4 bytes, this means all pointers to a type whose
65 // size is 3 or greater than 4 will be (righteously) rejected.
66 #define ARRAYSIZE_UNSAFE(a) \
67 ((sizeof(a) / sizeof(*(a))) / \
68 static_cast<size_t>(!(sizeof(a) % sizeof(*(a))))) // NOLINT
70 // TODO(bmeurer): For some reason, the NaCl toolchain cannot handle the correct
71 // definition of arraysize() below, so we have to use the unsafe version for
73 #define arraysize ARRAYSIZE_UNSAFE
77 // The arraysize(arr) macro returns the # of elements in an array arr.
78 // The expression is a compile-time constant, and therefore can be
79 // used in defining new arrays, for example. If you use arraysize on
80 // a pointer by mistake, you will get a compile-time error.
82 // One caveat is that arraysize() doesn't accept any array of an
83 // anonymous type or a type defined inside a function. In these rare
84 // cases, you have to use the unsafe ARRAYSIZE_UNSAFE() macro below. This is
85 // due to a limitation in C++'s template system. The limitation might
86 // eventually be removed, but it hasn't happened yet.
87 #define arraysize(array) (sizeof(ArraySizeHelper(array)))
90 // This template function declaration is used in defining arraysize.
91 // Note that the function doesn't need an implementation, as we only
93 template <typename T, size_t N>
94 char (&ArraySizeHelper(T (&array)[N]))[N];
98 // That gcc wants both of these prototypes seems mysterious. VC, for
99 // its part, can't decide which to use (another mystery). Matching of
100 // template overloads: the final frontier.
101 template <typename T, size_t N>
102 char (&ArraySizeHelper(const T (&array)[N]))[N];
108 // The COMPILE_ASSERT macro can be used to verify that a compile time
109 // expression is true. For example, you could use it to verify the
110 // size of a static array:
112 // COMPILE_ASSERT(ARRAYSIZE_UNSAFE(content_type_names) == CONTENT_NUM_TYPES,
113 // content_type_names_incorrect_size);
115 // or to make sure a struct is smaller than a certain size:
117 // COMPILE_ASSERT(sizeof(foo) < 128, foo_too_large);
119 // The second argument to the macro is the name of the variable. If
120 // the expression is false, most compilers will issue a warning/error
121 // containing the name of the variable.
122 #if V8_HAS_CXX11_STATIC_ASSERT
124 // Under C++11, just use static_assert.
125 #define COMPILE_ASSERT(expr, msg) static_assert(expr, #msg)
130 struct CompileAssert {};
132 #define COMPILE_ASSERT(expr, msg) \
133 typedef CompileAssert<static_cast<bool>(expr)> \
134 msg[static_cast<bool>(expr) ? 1 : -1] ALLOW_UNUSED_TYPE
136 // Implementation details of COMPILE_ASSERT:
138 // - COMPILE_ASSERT works by defining an array type that has -1
139 // elements (and thus is invalid) when the expression is false.
141 // - The simpler definition
143 // #define COMPILE_ASSERT(expr, msg) typedef char msg[(expr) ? 1 : -1]
145 // does not work, as gcc supports variable-length arrays whose sizes
146 // are determined at run-time (this is gcc's extension and not part
147 // of the C++ standard). As a result, gcc fails to reject the
148 // following code with the simple definition:
151 // COMPILE_ASSERT(foo, msg); // not supposed to compile as foo is
152 // // not a compile-time constant.
154 // - By using the type CompileAssert<static_cast<bool>(expr)>, we ensure that
155 // expr is a compile-time constant. (Template arguments must be
156 // determined at compile-time.)
158 // - The array size is (static_cast<bool>(expr) ? 1 : -1), instead of simply
160 // ((expr) ? 1 : -1).
162 // This is to avoid running into a bug in MS VC 7.1, which
163 // causes ((0.0) ? 1 : -1) to incorrectly evaluate to 1.
168 // bit_cast<Dest,Source> is a template function that implements the
169 // equivalent of "*reinterpret_cast<Dest*>(&source)". We need this in
170 // very low-level functions like the protobuf library and fast math
173 // float f = 3.14159265358979;
174 // int i = bit_cast<int32>(f);
177 // The classical address-casting method is:
180 // float f = 3.14159265358979; // WRONG
181 // int i = * reinterpret_cast<int*>(&f); // WRONG
183 // The address-casting method actually produces undefined behavior
184 // according to ISO C++ specification section 3.10 -15 -. Roughly, this
185 // section says: if an object in memory has one type, and a program
186 // accesses it with a different type, then the result is undefined
187 // behavior for most values of "different type".
189 // This is true for any cast syntax, either *(int*)&f or
190 // *reinterpret_cast<int*>(&f). And it is particularly true for
191 // conversions between integral lvalues and floating-point lvalues.
193 // The purpose of 3.10 -15- is to allow optimizing compilers to assume
194 // that expressions with different types refer to different memory. gcc
195 // 4.0.1 has an optimizer that takes advantage of this. So a
196 // non-conforming program quietly produces wildly incorrect output.
198 // The problem is not the use of reinterpret_cast. The problem is type
199 // punning: holding an object in memory of one type and reading its bits
200 // back using a different type.
202 // The C++ standard is more subtle and complex than this, but that
203 // is the basic idea.
207 // bit_cast<> calls memcpy() which is blessed by the standard,
208 // especially by the example in section 3.9 . Also, of course,
209 // bit_cast<> wraps up the nasty logic in one place.
211 // Fortunately memcpy() is very fast. In optimized mode, with a
212 // constant size, gcc 2.95.3, gcc 4.0.1, and msvc 7.1 produce inline
213 // code with the minimal amount of data movement. On a 32-bit system,
214 // memcpy(d,s,4) compiles to one load and one store, and memcpy(d,s,8)
215 // compiles to two loads and two stores.
217 // I tested this code with gcc 2.95.3, gcc 4.0.1, icc 8.1, and msvc 7.1.
219 // WARNING: if Dest or Source is a non-POD type, the result of the memcpy
220 // is likely to surprise you.
221 template <class Dest, class Source>
222 V8_INLINE Dest bit_cast(Source const& source) {
223 COMPILE_ASSERT(sizeof(Dest) == sizeof(Source), VerifySizesAreEqual);
226 memcpy(&dest, &source, sizeof(dest));
231 // A macro to disallow the evil copy constructor and operator= functions
232 // This should be used in the private: declarations for a class
233 #define DISALLOW_COPY_AND_ASSIGN(TypeName) \
234 TypeName(const TypeName&) V8_DELETE; \
235 void operator=(const TypeName&) V8_DELETE
238 // A macro to disallow all the implicit constructors, namely the
239 // default constructor, copy constructor and operator= functions.
241 // This should be used in the private: declarations for a class
242 // that wants to prevent anyone from instantiating it. This is
243 // especially useful for classes containing only static methods.
244 #define DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \
245 TypeName() V8_DELETE; \
246 DISALLOW_COPY_AND_ASSIGN(TypeName)
249 // Newly written code should use V8_INLINE and V8_NOINLINE directly.
250 #define INLINE(declarator) V8_INLINE declarator
251 #define NO_INLINE(declarator) V8_NOINLINE declarator
254 // Newly written code should use WARN_UNUSED_RESULT.
255 #define MUST_USE_RESULT WARN_UNUSED_RESULT
258 // Define V8_USE_ADDRESS_SANITIZER macros.
259 #if defined(__has_feature)
260 #if __has_feature(address_sanitizer)
261 #define V8_USE_ADDRESS_SANITIZER 1
265 // Define DISABLE_ASAN macros.
266 #ifdef V8_USE_ADDRESS_SANITIZER
267 #define DISABLE_ASAN __attribute__((no_sanitize_address))
274 #define V8_IMMEDIATE_CRASH() __builtin_trap()
276 #define V8_IMMEDIATE_CRASH() ((void(*)())0)()
280 // Use C++11 static_assert if possible, which gives error
281 // messages that are easier to understand on first sight.
282 #if V8_HAS_CXX11_STATIC_ASSERT
283 #define STATIC_ASSERT(test) static_assert(test, #test)
285 // This is inspired by the static assertion facility in boost. This
286 // is pretty magical. If it causes you trouble on a platform you may
287 // find a fix in the boost code.
288 template <bool> class StaticAssertion;
289 template <> class StaticAssertion<true> { };
290 // This macro joins two tokens. If one of the tokens is a macro the
291 // helper call causes it to be resolved before joining.
292 #define SEMI_STATIC_JOIN(a, b) SEMI_STATIC_JOIN_HELPER(a, b)
293 #define SEMI_STATIC_JOIN_HELPER(a, b) a##b
294 // Causes an error during compilation of the condition is not
295 // statically known to be true. It is formulated as a typedef so that
296 // it can be used wherever a typedef can be used. Beware that this
297 // actually causes each use to introduce a new defined type with a
298 // name depending on the source line.
299 template <int> class StaticAssertionHelper { };
300 #define STATIC_ASSERT(test) \
301 typedef StaticAssertionHelper< \
302 sizeof(StaticAssertion<static_cast<bool>((test))>)> \
303 SEMI_STATIC_JOIN(__StaticAssertTypedef__, __LINE__) ALLOW_UNUSED_TYPE
308 // The USE(x) template is used to silence C++ compiler warnings
309 // issued for (yet) unused variables (typically parameters).
310 template <typename T>
311 inline void USE(T) { }
314 #define IS_POWER_OF_TWO(x) ((x) != 0 && (((x) & ((x) - 1)) == 0))
317 // Define our own macros for writing 64-bit constants. This is less fragile
318 // than defining __STDC_CONSTANT_MACROS before including <stdint.h>, and it
319 // works on compilers that don't have it (like MSVC).
321 # define V8_UINT64_C(x) (x ## UI64)
322 # define V8_INT64_C(x) (x ## I64)
323 # if V8_HOST_ARCH_64_BIT
324 # define V8_INTPTR_C(x) (x ## I64)
325 # define V8_PTR_PREFIX "ll"
327 # define V8_INTPTR_C(x) (x)
328 # define V8_PTR_PREFIX ""
329 # endif // V8_HOST_ARCH_64_BIT
331 # define V8_UINT64_C(x) (x ## ULL)
332 # define V8_INT64_C(x) (x ## LL)
333 # define V8_INTPTR_C(x) (x ## LL)
334 # define V8_PTR_PREFIX "I64"
335 #elif V8_HOST_ARCH_64_BIT
337 # define V8_UINT64_C(x) (x ## ULL)
338 # define V8_INT64_C(x) (x ## LL)
340 # define V8_UINT64_C(x) (x ## UL)
341 # define V8_INT64_C(x) (x ## L)
343 # define V8_INTPTR_C(x) (x ## L)
344 # define V8_PTR_PREFIX "l"
346 # define V8_UINT64_C(x) (x ## ULL)
347 # define V8_INT64_C(x) (x ## LL)
348 # define V8_INTPTR_C(x) (x)
349 # define V8_PTR_PREFIX ""
352 #define V8PRIxPTR V8_PTR_PREFIX "x"
353 #define V8PRIdPTR V8_PTR_PREFIX "d"
354 #define V8PRIuPTR V8_PTR_PREFIX "u"
356 // Fix for Mac OS X defining uintptr_t as "unsigned long":
359 #define V8PRIxPTR "lx"
362 // The following macro works on both 32 and 64-bit platforms.
363 // Usage: instead of writing 0x1234567890123456
364 // write V8_2PART_UINT64_C(0x12345678,90123456);
365 #define V8_2PART_UINT64_C(a, b) (((static_cast<uint64_t>(a) << 32) + 0x##b##u))
368 // Compute the 0-relative offset of some absolute value x of type T.
369 // This allows conversion of Addresses and integral types into
370 // 0-relative int offsets.
371 template <typename T>
372 inline intptr_t OffsetFrom(T x) {
373 return x - static_cast<T>(0);
377 // Compute the absolute value of type T for some 0-relative offset x.
378 // This allows conversion of 0-relative int offsets into Addresses and
380 template <typename T>
381 inline T AddressFrom(intptr_t x) {
382 return static_cast<T>(static_cast<T>(0) + x);
386 // Return the largest multiple of m which is <= x.
387 template <typename T>
388 inline T RoundDown(T x, intptr_t m) {
389 DCHECK(IS_POWER_OF_TWO(m));
390 return AddressFrom<T>(OffsetFrom(x) & -m);
394 // Return the smallest multiple of m which is >= x.
395 template <typename T>
396 inline T RoundUp(T x, intptr_t m) {
397 return RoundDown<T>(static_cast<T>(x + m - 1), m);
404 // TODO(yangguo): This is a poor man's replacement for std::is_fundamental,
405 // which requires C++11. Switch to std::is_fundamental once possible.
406 template <typename T>
407 inline bool is_fundamental() {
412 inline bool is_fundamental<uint8_t>() {
416 } // namespace v8::base
418 #endif // V8_BASE_MACROS_H_