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.
4
5#ifndef V8_BASE_MACROS_H_
6#define V8_BASE_MACROS_H_
7
8#include <cstring>
9
10#include "include/v8stdint.h"
11#include "src/base/build_config.h"
12#include "src/base/compiler-specific.h"
13#include "src/base/logging.h"
14
15
16// The expression OFFSET_OF(type, field) computes the byte-offset
17// of the specified field relative to the containing type. This
18// corresponds to 'offsetof' (in stddef.h), except that it doesn't
19// use 0 or NULL, which causes a problem with the compiler warnings
20// we have enabled (which is also why 'offsetof' doesn't seem to work).
21// Here we simply use the non-zero value 4, which seems to work.
22#define OFFSET_OF(type, field)                                          \
23  (reinterpret_cast<intptr_t>(&(reinterpret_cast<type*>(4)->field)) - 4)
24
25
26// ARRAYSIZE_UNSAFE performs essentially the same calculation as arraysize,
27// but can be used on anonymous types or types defined inside
28// functions.  It's less safe than arraysize as it accepts some
29// (although not all) pointers.  Therefore, you should use arraysize
30// whenever possible.
31//
32// The expression ARRAYSIZE_UNSAFE(a) is a compile-time constant of type
33// size_t.
34//
35// ARRAYSIZE_UNSAFE catches a few type errors.  If you see a compiler error
36//
37//   "warning: division by zero in ..."
38//
39// when using ARRAYSIZE_UNSAFE, you are (wrongfully) giving it a pointer.
40// You should only use ARRAYSIZE_UNSAFE on statically allocated arrays.
41//
42// The following comments are on the implementation details, and can
43// be ignored by the users.
44//
45// ARRAYSIZE_UNSAFE(arr) works by inspecting sizeof(arr) (the # of bytes in
46// the array) and sizeof(*(arr)) (the # of bytes in one array
47// element).  If the former is divisible by the latter, perhaps arr is
48// indeed an array, in which case the division result is the # of
49// elements in the array.  Otherwise, arr cannot possibly be an array,
50// and we generate a compiler error to prevent the code from
51// compiling.
52//
53// Since the size of bool is implementation-defined, we need to cast
54// !(sizeof(a) & sizeof(*(a))) to size_t in order to ensure the final
55// result has type size_t.
56//
57// This macro is not perfect as it wrongfully accepts certain
58// pointers, namely where the pointer size is divisible by the pointee
59// size.  Since all our code has to go through a 32-bit compiler,
60// where a pointer is 4 bytes, this means all pointers to a type whose
61// size is 3 or greater than 4 will be (righteously) rejected.
62#define ARRAYSIZE_UNSAFE(a)     \
63  ((sizeof(a) / sizeof(*(a))) / \
64   static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))  // NOLINT
65
66
67#if V8_OS_NACL
68
69// TODO(bmeurer): For some reason, the NaCl toolchain cannot handle the correct
70// definition of arraysize() below, so we have to use the unsafe version for
71// now.
72#define arraysize ARRAYSIZE_UNSAFE
73
74#else  // V8_OS_NACL
75
76// The arraysize(arr) macro returns the # of elements in an array arr.
77// The expression is a compile-time constant, and therefore can be
78// used in defining new arrays, for example.  If you use arraysize on
79// a pointer by mistake, you will get a compile-time error.
80//
81// One caveat is that arraysize() doesn't accept any array of an
82// anonymous type or a type defined inside a function.  In these rare
83// cases, you have to use the unsafe ARRAYSIZE_UNSAFE() macro below.  This is
84// due to a limitation in C++'s template system.  The limitation might
85// eventually be removed, but it hasn't happened yet.
86#define arraysize(array) (sizeof(ArraySizeHelper(array)))
87
88
89// This template function declaration is used in defining arraysize.
90// Note that the function doesn't need an implementation, as we only
91// use its type.
92template <typename T, size_t N>
93char (&ArraySizeHelper(T (&array)[N]))[N];
94
95
96#if !V8_CC_MSVC
97// That gcc wants both of these prototypes seems mysterious. VC, for
98// its part, can't decide which to use (another mystery). Matching of
99// template overloads: the final frontier.
100template <typename T, size_t N>
101char (&ArraySizeHelper(const T (&array)[N]))[N];
102#endif
103
104#endif  // V8_OS_NACL
105
106
107// The COMPILE_ASSERT macro can be used to verify that a compile time
108// expression is true. For example, you could use it to verify the
109// size of a static array:
110//
111//   COMPILE_ASSERT(ARRAYSIZE_UNSAFE(content_type_names) == CONTENT_NUM_TYPES,
112//                  content_type_names_incorrect_size);
113//
114// or to make sure a struct is smaller than a certain size:
115//
116//   COMPILE_ASSERT(sizeof(foo) < 128, foo_too_large);
117//
118// The second argument to the macro is the name of the variable. If
119// the expression is false, most compilers will issue a warning/error
120// containing the name of the variable.
121#if V8_HAS_CXX11_STATIC_ASSERT
122
123// Under C++11, just use static_assert.
124#define COMPILE_ASSERT(expr, msg) static_assert(expr, #msg)
125
126#else
127
128template <bool>
129struct CompileAssert {};
130
131#define COMPILE_ASSERT(expr, msg)                \
132  typedef CompileAssert<static_cast<bool>(expr)> \
133      msg[static_cast<bool>(expr) ? 1 : -1] ALLOW_UNUSED
134
135// Implementation details of COMPILE_ASSERT:
136//
137// - COMPILE_ASSERT works by defining an array type that has -1
138//   elements (and thus is invalid) when the expression is false.
139//
140// - The simpler definition
141//
142//     #define COMPILE_ASSERT(expr, msg) typedef char msg[(expr) ? 1 : -1]
143//
144//   does not work, as gcc supports variable-length arrays whose sizes
145//   are determined at run-time (this is gcc's extension and not part
146//   of the C++ standard).  As a result, gcc fails to reject the
147//   following code with the simple definition:
148//
149//     int foo;
150//     COMPILE_ASSERT(foo, msg); // not supposed to compile as foo is
151//                               // not a compile-time constant.
152//
153// - By using the type CompileAssert<(bool(expr))>, we ensures that
154//   expr is a compile-time constant.  (Template arguments must be
155//   determined at compile-time.)
156//
157// - The outer parentheses in CompileAssert<(bool(expr))> are necessary
158//   to work around a bug in gcc 3.4.4 and 4.0.1.  If we had written
159//
160//     CompileAssert<bool(expr)>
161//
162//   instead, these compilers will refuse to compile
163//
164//     COMPILE_ASSERT(5 > 0, some_message);
165//
166//   (They seem to think the ">" in "5 > 0" marks the end of the
167//   template argument list.)
168//
169// - The array size is (bool(expr) ? 1 : -1), instead of simply
170//
171//     ((expr) ? 1 : -1).
172//
173//   This is to avoid running into a bug in MS VC 7.1, which
174//   causes ((0.0) ? 1 : -1) to incorrectly evaluate to 1.
175
176#endif
177
178
179// bit_cast<Dest,Source> is a template function that implements the
180// equivalent of "*reinterpret_cast<Dest*>(&source)".  We need this in
181// very low-level functions like the protobuf library and fast math
182// support.
183//
184//   float f = 3.14159265358979;
185//   int i = bit_cast<int32>(f);
186//   // i = 0x40490fdb
187//
188// The classical address-casting method is:
189//
190//   // WRONG
191//   float f = 3.14159265358979;            // WRONG
192//   int i = * reinterpret_cast<int*>(&f);  // WRONG
193//
194// The address-casting method actually produces undefined behavior
195// according to ISO C++ specification section 3.10 -15 -.  Roughly, this
196// section says: if an object in memory has one type, and a program
197// accesses it with a different type, then the result is undefined
198// behavior for most values of "different type".
199//
200// This is true for any cast syntax, either *(int*)&f or
201// *reinterpret_cast<int*>(&f).  And it is particularly true for
202// conversions between integral lvalues and floating-point lvalues.
203//
204// The purpose of 3.10 -15- is to allow optimizing compilers to assume
205// that expressions with different types refer to different memory.  gcc
206// 4.0.1 has an optimizer that takes advantage of this.  So a
207// non-conforming program quietly produces wildly incorrect output.
208//
209// The problem is not the use of reinterpret_cast.  The problem is type
210// punning: holding an object in memory of one type and reading its bits
211// back using a different type.
212//
213// The C++ standard is more subtle and complex than this, but that
214// is the basic idea.
215//
216// Anyways ...
217//
218// bit_cast<> calls memcpy() which is blessed by the standard,
219// especially by the example in section 3.9 .  Also, of course,
220// bit_cast<> wraps up the nasty logic in one place.
221//
222// Fortunately memcpy() is very fast.  In optimized mode, with a
223// constant size, gcc 2.95.3, gcc 4.0.1, and msvc 7.1 produce inline
224// code with the minimal amount of data movement.  On a 32-bit system,
225// memcpy(d,s,4) compiles to one load and one store, and memcpy(d,s,8)
226// compiles to two loads and two stores.
227//
228// I tested this code with gcc 2.95.3, gcc 4.0.1, icc 8.1, and msvc 7.1.
229//
230// WARNING: if Dest or Source is a non-POD type, the result of the memcpy
231// is likely to surprise you.
232template <class Dest, class Source>
233V8_INLINE Dest bit_cast(Source const& source) {
234  COMPILE_ASSERT(sizeof(Dest) == sizeof(Source), VerifySizesAreEqual);
235
236  Dest dest;
237  memcpy(&dest, &source, sizeof(dest));
238  return dest;
239}
240
241
242// A macro to disallow the evil copy constructor and operator= functions
243// This should be used in the private: declarations for a class
244#define DISALLOW_COPY_AND_ASSIGN(TypeName)  \
245  TypeName(const TypeName&) V8_DELETE;      \
246  void operator=(const TypeName&) V8_DELETE
247
248
249// A macro to disallow all the implicit constructors, namely the
250// default constructor, copy constructor and operator= functions.
251//
252// This should be used in the private: declarations for a class
253// that wants to prevent anyone from instantiating it. This is
254// especially useful for classes containing only static methods.
255#define DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName)  \
256  TypeName() V8_DELETE;                           \
257  DISALLOW_COPY_AND_ASSIGN(TypeName)
258
259
260// Newly written code should use V8_INLINE and V8_NOINLINE directly.
261#define INLINE(declarator)    V8_INLINE declarator
262#define NO_INLINE(declarator) V8_NOINLINE declarator
263
264
265// Newly written code should use WARN_UNUSED_RESULT.
266#define MUST_USE_RESULT WARN_UNUSED_RESULT
267
268
269// Define V8_USE_ADDRESS_SANITIZER macros.
270#if defined(__has_feature)
271#if __has_feature(address_sanitizer)
272#define V8_USE_ADDRESS_SANITIZER 1
273#endif
274#endif
275
276// Define DISABLE_ASAN macros.
277#ifdef V8_USE_ADDRESS_SANITIZER
278#define DISABLE_ASAN __attribute__((no_sanitize_address))
279#else
280#define DISABLE_ASAN
281#endif
282
283
284#if V8_CC_GNU
285#define V8_IMMEDIATE_CRASH() __builtin_trap()
286#else
287#define V8_IMMEDIATE_CRASH() ((void(*)())0)()
288#endif
289
290
291// Use C++11 static_assert if possible, which gives error
292// messages that are easier to understand on first sight.
293#if V8_HAS_CXX11_STATIC_ASSERT
294#define STATIC_ASSERT(test) static_assert(test, #test)
295#else
296// This is inspired by the static assertion facility in boost.  This
297// is pretty magical.  If it causes you trouble on a platform you may
298// find a fix in the boost code.
299template <bool> class StaticAssertion;
300template <> class StaticAssertion<true> { };
301// This macro joins two tokens.  If one of the tokens is a macro the
302// helper call causes it to be resolved before joining.
303#define SEMI_STATIC_JOIN(a, b) SEMI_STATIC_JOIN_HELPER(a, b)
304#define SEMI_STATIC_JOIN_HELPER(a, b) a##b
305// Causes an error during compilation of the condition is not
306// statically known to be true.  It is formulated as a typedef so that
307// it can be used wherever a typedef can be used.  Beware that this
308// actually causes each use to introduce a new defined type with a
309// name depending on the source line.
310template <int> class StaticAssertionHelper { };
311#define STATIC_ASSERT(test)                                                    \
312  typedef                                                                     \
313    StaticAssertionHelper<sizeof(StaticAssertion<static_cast<bool>((test))>)> \
314    SEMI_STATIC_JOIN(__StaticAssertTypedef__, __LINE__) ALLOW_UNUSED
315
316#endif
317
318
319// The USE(x) template is used to silence C++ compiler warnings
320// issued for (yet) unused variables (typically parameters).
321template <typename T>
322inline void USE(T) { }
323
324
325#define IS_POWER_OF_TWO(x) ((x) != 0 && (((x) & ((x) - 1)) == 0))
326
327
328// Define our own macros for writing 64-bit constants.  This is less fragile
329// than defining __STDC_CONSTANT_MACROS before including <stdint.h>, and it
330// works on compilers that don't have it (like MSVC).
331#if V8_CC_MSVC
332# define V8_UINT64_C(x)   (x ## UI64)
333# define V8_INT64_C(x)    (x ## I64)
334# if V8_HOST_ARCH_64_BIT
335#  define V8_INTPTR_C(x)  (x ## I64)
336#  define V8_PTR_PREFIX   "ll"
337# else
338#  define V8_INTPTR_C(x)  (x)
339#  define V8_PTR_PREFIX   ""
340# endif  // V8_HOST_ARCH_64_BIT
341#elif V8_CC_MINGW64
342# define V8_UINT64_C(x)   (x ## ULL)
343# define V8_INT64_C(x)    (x ## LL)
344# define V8_INTPTR_C(x)   (x ## LL)
345# define V8_PTR_PREFIX    "I64"
346#elif V8_HOST_ARCH_64_BIT
347# if V8_OS_MACOSX
348#  define V8_UINT64_C(x)   (x ## ULL)
349#  define V8_INT64_C(x)    (x ## LL)
350# else
351#  define V8_UINT64_C(x)   (x ## UL)
352#  define V8_INT64_C(x)    (x ## L)
353# endif
354# define V8_INTPTR_C(x)   (x ## L)
355# define V8_PTR_PREFIX    "l"
356#else
357# define V8_UINT64_C(x)   (x ## ULL)
358# define V8_INT64_C(x)    (x ## LL)
359# define V8_INTPTR_C(x)   (x)
360# define V8_PTR_PREFIX    ""
361#endif
362
363#define V8PRIxPTR V8_PTR_PREFIX "x"
364#define V8PRIdPTR V8_PTR_PREFIX "d"
365#define V8PRIuPTR V8_PTR_PREFIX "u"
366
367// Fix for Mac OS X defining uintptr_t as "unsigned long":
368#if V8_OS_MACOSX
369#undef V8PRIxPTR
370#define V8PRIxPTR "lx"
371#endif
372
373// The following macro works on both 32 and 64-bit platforms.
374// Usage: instead of writing 0x1234567890123456
375//      write V8_2PART_UINT64_C(0x12345678,90123456);
376#define V8_2PART_UINT64_C(a, b) (((static_cast<uint64_t>(a) << 32) + 0x##b##u))
377
378
379// Compute the 0-relative offset of some absolute value x of type T.
380// This allows conversion of Addresses and integral types into
381// 0-relative int offsets.
382template <typename T>
383inline intptr_t OffsetFrom(T x) {
384  return x - static_cast<T>(0);
385}
386
387
388// Compute the absolute value of type T for some 0-relative offset x.
389// This allows conversion of 0-relative int offsets into Addresses and
390// integral types.
391template <typename T>
392inline T AddressFrom(intptr_t x) {
393  return static_cast<T>(static_cast<T>(0) + x);
394}
395
396
397// Return the largest multiple of m which is <= x.
398template <typename T>
399inline T RoundDown(T x, intptr_t m) {
400  DCHECK(IS_POWER_OF_TWO(m));
401  return AddressFrom<T>(OffsetFrom(x) & -m);
402}
403
404
405// Return the smallest multiple of m which is >= x.
406template <typename T>
407inline T RoundUp(T x, intptr_t m) {
408  return RoundDown<T>(static_cast<T>(x + m - 1), m);
409}
410
411#endif   // V8_BASE_MACROS_H_
412