globals.h 62.4 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4

5 6
#ifndef V8_COMMON_GLOBALS_H_
#define V8_COMMON_GLOBALS_H_
7

8 9
#include <stddef.h>
#include <stdint.h>
10

11
#include <limits>
12 13
#include <ostream>

14
#include "include/v8-internal.h"
15
#include "src/base/atomic-utils.h"
16
#include "src/base/build_config.h"
17
#include "src/base/enum-set.h"
18
#include "src/base/flags.h"
19
#include "src/base/logging.h"
20
#include "src/base/macros.h"
21

22
#define V8_INFINITY std::numeric_limits<double>::infinity()
23

24
namespace v8 {
25 26 27 28

namespace base {
class Mutex;
class RecursiveMutex;
29
}  // namespace base
30

31
namespace internal {
32

33 34 35 36
constexpr int KB = 1024;
constexpr int MB = KB * 1024;
constexpr int GB = MB * 1024;

37
// Determine whether we are running in a simulated environment.
38 39 40
// Setting USE_SIMULATOR explicitly from the build script will force
// the use of a simulated environment.
#if !defined(USE_SIMULATOR)
41
#if (V8_TARGET_ARCH_ARM64 && !V8_HOST_ARCH_ARM64)
42 43
#define USE_SIMULATOR 1
#endif
44 45 46
#if (V8_TARGET_ARCH_ARM && !V8_HOST_ARCH_ARM)
#define USE_SIMULATOR 1
#endif
47 48 49
#if (V8_TARGET_ARCH_PPC && !V8_HOST_ARCH_PPC)
#define USE_SIMULATOR 1
#endif
50 51 52
#if (V8_TARGET_ARCH_PPC64 && !V8_HOST_ARCH_PPC64)
#define USE_SIMULATOR 1
#endif
53 54
#if (V8_TARGET_ARCH_MIPS && !V8_HOST_ARCH_MIPS)
#define USE_SIMULATOR 1
55
#endif
56 57 58
#if (V8_TARGET_ARCH_MIPS64 && !V8_HOST_ARCH_MIPS64)
#define USE_SIMULATOR 1
#endif
59 60 61
#if (V8_TARGET_ARCH_S390 && !V8_HOST_ARCH_S390)
#define USE_SIMULATOR 1
#endif
Brice Dobry's avatar
Brice Dobry committed
62 63 64
#if (V8_TARGET_ARCH_RISCV64 && !V8_HOST_ARCH_RISCV64)
#define USE_SIMULATOR 1
#endif
65 66
#endif

67 68
// Determine whether the architecture uses an embedded constant pool
// (contiguous constant pool embedded in code object).
69
#if V8_TARGET_ARCH_PPC || V8_TARGET_ARCH_PPC64
70
#define V8_EMBEDDED_CONSTANT_POOL true
71
#else
72
#define V8_EMBEDDED_CONSTANT_POOL false
73
#endif
74

75 76 77 78 79 80 81
#if V8_TARGET_ARCH_ARM || V8_TARGET_ARCH_ARM64
// Set stack limit lower for ARM and ARM64 than for other architectures because:
//  - on Arm stack allocating MacroAssembler takes 120K bytes.
//    See issue crbug.com/405338
//  - on Arm64 when running in single-process mode for Android WebView, when
//    initializing V8 we already have a large stack and so have to set the
//    limit lower. See issue crbug.com/v8/10575
82 83 84 85 86 87 88
#define V8_DEFAULT_STACK_SIZE_KB 864
#else
// Slightly less than 1MB, since Windows' default stack size for
// the main execution thread is 1MB for both 32 and 64-bit.
#define V8_DEFAULT_STACK_SIZE_KB 984
#endif

89
// Minimum stack size in KB required by compilers.
90
constexpr int kStackSpaceRequiredForCompilation = 40;
91

92 93 94 95 96 97 98 99 100 101 102
// In order to emit more efficient stack checks in optimized code,
// deoptimization may implicitly exceed the V8 stack limit by this many bytes.
// Stack checks in functions with `difference between optimized and unoptimized
// stack frame sizes <= slack` can simply emit the simple stack check.
constexpr int kStackLimitSlackForDeoptimizationInBytes = 256;

// Sanity-check, assuming that we aim for a real OS stack size of at least 1MB.
STATIC_ASSERT(V8_DEFAULT_STACK_SIZE_KB* KB +
                  kStackLimitSlackForDeoptimizationInBytes <=
              MB);

103 104
// Determine whether the short builtin calls optimization is enabled.
#ifdef V8_SHORT_BUILTIN_CALLS
105
#ifndef V8_COMPRESS_POINTERS
106 107
// TODO(11527): Fix this by passing Isolate* to Code::OffHeapInstructionStart()
// and friends.
108
#error Short builtin calls feature requires pointer compression
109 110 111
#endif
#endif

112 113 114 115
// This constant is used for detecting whether the machine has >= 4GB of
// physical memory by checking the max old space size.
const size_t kShortBuiltinCallsOldSpaceSizeThreshold = size_t{2} * GB;

116
// Determine whether dict mode prototypes feature is enabled.
117 118
#ifdef V8_ENABLE_SWISS_NAME_DICTIONARY
#define V8_ENABLE_SWISS_NAME_DICTIONARY_BOOL true
119
#else
120
#define V8_ENABLE_SWISS_NAME_DICTIONARY_BOOL false
121 122
#endif

123 124 125 126 127 128 129
// Determine whether dict property constness tracking feature is enabled.
#ifdef V8_DICT_PROPERTY_CONST_TRACKING
#define V8_DICT_PROPERTY_CONST_TRACKING_BOOL true
#else
#define V8_DICT_PROPERTY_CONST_TRACKING_BOOL false
#endif

130 131
#ifdef V8_EXTERNAL_CODE_SPACE
#define V8_EXTERNAL_CODE_SPACE_BOOL true
132 133
class CodeDataContainer;
using CodeT = CodeDataContainer;
134 135
#else
#define V8_EXTERNAL_CODE_SPACE_BOOL false
136 137
class Code;
using CodeT = Code;
138 139
#endif

140 141 142 143 144 145 146 147
// Determine whether tagged pointers are 8 bytes (used in Torque layouts for
// choosing where to insert padding).
#if V8_TARGET_ARCH_64_BIT && !defined(V8_COMPRESS_POINTERS)
#define TAGGED_SIZE_8_BYTES true
#else
#define TAGGED_SIZE_8_BYTES false
#endif

148
// Some types of tracing require the SFI to store a unique ID.
149
#if defined(V8_TRACE_MAPS) || defined(V8_TRACE_UNOPTIMIZED)
150
#define V8_SFI_HAS_UNIQUE_ID true
151 152
#else
#define V8_SFI_HAS_UNIQUE_ID false
153 154
#endif

155 156 157 158
#if defined(V8_OS_WIN) && defined(V8_TARGET_ARCH_X64)
#define V8_OS_WIN_X64 true
#endif

159 160 161 162 163 164 165 166
#if defined(V8_OS_WIN) && defined(V8_TARGET_ARCH_ARM64)
#define V8_OS_WIN_ARM64 true
#endif

#if defined(V8_OS_WIN_X64) || defined(V8_OS_WIN_ARM64)
#define V8_OS_WIN64 true
#endif

167 168 169 170 171 172 173 174 175
// Superclass for classes only using static method functions.
// The subclass of AllStatic cannot be instantiated at all.
class AllStatic {
#ifdef DEBUG
 public:
  AllStatic() = delete;
#endif
};

176
using byte = uint8_t;
177

178 179 180
// -----------------------------------------------------------------------------
// Constants

181 182 183 184 185 186 187 188 189 190
constexpr int kMaxInt = 0x7FFFFFFF;
constexpr int kMinInt = -kMaxInt - 1;
constexpr int kMaxInt8 = (1 << 7) - 1;
constexpr int kMinInt8 = -(1 << 7);
constexpr int kMaxUInt8 = (1 << 8) - 1;
constexpr int kMinUInt8 = 0;
constexpr int kMaxInt16 = (1 << 15) - 1;
constexpr int kMinInt16 = -(1 << 15);
constexpr int kMaxUInt16 = (1 << 16) - 1;
constexpr int kMinUInt16 = 0;
191 192
constexpr int kMaxInt31 = kMaxInt / 2;
constexpr int kMinInt31 = kMinInt / 2;
193 194 195 196

constexpr uint32_t kMaxUInt32 = 0xFFFFFFFFu;
constexpr int kMinUInt32 = 0;

197
constexpr int kInt8Size = sizeof(int8_t);
198
constexpr int kUInt8Size = sizeof(uint8_t);
199
constexpr int kByteSize = sizeof(byte);
200 201
constexpr int kCharSize = sizeof(char);
constexpr int kShortSize = sizeof(short);  // NOLINT
202
constexpr int kInt16Size = sizeof(int16_t);
203 204 205 206 207 208 209 210 211 212
constexpr int kUInt16Size = sizeof(uint16_t);
constexpr int kIntSize = sizeof(int);
constexpr int kInt32Size = sizeof(int32_t);
constexpr int kInt64Size = sizeof(int64_t);
constexpr int kUInt32Size = sizeof(uint32_t);
constexpr int kSizetSize = sizeof(size_t);
constexpr int kFloatSize = sizeof(float);
constexpr int kDoubleSize = sizeof(double);
constexpr int kIntptrSize = sizeof(intptr_t);
constexpr int kUIntptrSize = sizeof(uintptr_t);
213 214
constexpr int kSystemPointerSize = sizeof(void*);
constexpr int kSystemPointerHexDigits = kSystemPointerSize == 4 ? 8 : 12;
215 216
constexpr int kPCOnStackSize = kSystemPointerSize;
constexpr int kFPOnStackSize = kSystemPointerSize;
217

Jakob Kummerow's avatar
Jakob Kummerow committed
218
#if V8_TARGET_ARCH_X64 || V8_TARGET_ARCH_IA32
219
constexpr int kElidedFrameSlots = kPCOnStackSize / kSystemPointerSize;
220
#else
221
constexpr int kElidedFrameSlots = 0;
222 223
#endif

224
constexpr int kDoubleSizeLog2 = 3;
225 226
// The maximal length of the string representation for a double value
// (e.g. "-2.2250738585072020E-308"). It is composed as follows:
227
// - 17 decimal digits, see base::kBase10MaximalLength (dtoa.h)
228 229 230 231 232 233
// - 1 sign
// - 1 decimal point
// - 1 E or e
// - 1 exponent sign
// - 3 exponent
constexpr int kMaxDoubleStringLength = 24;
234

235 236
// Total wasm code space per engine (i.e. per process) is limited to make
// certain attacks that rely on heap spraying harder.
237 238
// Just below 4GB, such that {kMaxWasmCodeMemory} fits in a 32-bit size_t.
constexpr size_t kMaxWasmCodeMB = 4095;
239
constexpr size_t kMaxWasmCodeMemory = kMaxWasmCodeMB * MB;
240

241
#if V8_HOST_ARCH_64_BIT
242
constexpr int kSystemPointerSizeLog2 = 3;
243
constexpr intptr_t kIntptrSignBit =
244
    static_cast<intptr_t>(uintptr_t{0x8000000000000000});
245
constexpr bool kPlatformRequiresCodeRange = true;
246 247
#if (V8_HOST_ARCH_PPC || V8_HOST_ARCH_PPC64) && \
    (V8_TARGET_ARCH_PPC || V8_TARGET_ARCH_PPC64) && V8_OS_LINUX
248
constexpr size_t kMaximalCodeRangeSize = 512 * MB;
249
constexpr size_t kMinExpectedOSPageSize = 64 * KB;  // OS page on PPC Linux
250 251
#elif V8_TARGET_ARCH_ARM64
constexpr size_t kMaximalCodeRangeSize = 128 * MB;
252
constexpr size_t kMinExpectedOSPageSize = 4 * KB;  // OS page.
253
#else
254
constexpr size_t kMaximalCodeRangeSize = 128 * MB;
255
constexpr size_t kMinExpectedOSPageSize = 4 * KB;  // OS page.
256
#endif
257
#if V8_OS_WIN
258 259
constexpr size_t kMinimumCodeRangeSize = 4 * MB;
constexpr size_t kReservedCodeRangePages = 1;
260
#else
261 262
constexpr size_t kMinimumCodeRangeSize = 3 * MB;
constexpr size_t kReservedCodeRangePages = 0;
263
#endif
264
#else
265
constexpr int kSystemPointerSizeLog2 = 2;
266
constexpr intptr_t kIntptrSignBit = 0x80000000;
267 268
#if (V8_HOST_ARCH_PPC || V8_HOST_ARCH_PPC64) && \
    (V8_TARGET_ARCH_PPC || V8_TARGET_ARCH_PPC64) && V8_OS_LINUX
269
constexpr bool kPlatformRequiresCodeRange = false;
270 271
constexpr size_t kMaximalCodeRangeSize = 0 * MB;
constexpr size_t kMinimumCodeRangeSize = 0 * MB;
272
constexpr size_t kMinExpectedOSPageSize = 64 * KB;  // OS page on PPC Linux
273
#elif V8_TARGET_ARCH_MIPS
274
constexpr bool kPlatformRequiresCodeRange = false;
275 276 277
constexpr size_t kMaximalCodeRangeSize = 2048LL * MB;
constexpr size_t kMinimumCodeRangeSize = 0 * MB;
constexpr size_t kMinExpectedOSPageSize = 4 * KB;  // OS page.
278
#else
279
constexpr bool kPlatformRequiresCodeRange = false;
280 281
constexpr size_t kMaximalCodeRangeSize = 0 * MB;
constexpr size_t kMinimumCodeRangeSize = 0 * MB;
282
constexpr size_t kMinExpectedOSPageSize = 4 * KB;  // OS page.
283
#endif
284
constexpr size_t kReservedCodeRangePages = 0;
285
#endif
286

287 288
STATIC_ASSERT(kSystemPointerSize == (1 << kSystemPointerSizeLog2));

289 290 291 292 293 294 295 296 297 298
#ifdef V8_COMPRESS_ZONES
#define COMPRESS_ZONES_BOOL true
#else
#define COMPRESS_ZONES_BOOL false
#endif  // V8_COMPRESS_ZONES

// The flag controls whether zones pointer compression should be enabled for
// TurboFan graphs or not.
static constexpr bool kCompressGraphZone = COMPRESS_ZONES_BOOL;

299 300 301 302 303 304 305 306 307 308
#ifdef V8_COMPRESS_POINTERS
static_assert(
    kSystemPointerSize == kInt64Size,
    "Pointer compression can be enabled only for 64-bit architectures");

constexpr int kTaggedSize = kInt32Size;
constexpr int kTaggedSizeLog2 = 2;

// These types define raw and atomic storage types for tagged values stored
// on V8 heap.
309
using Tagged_t = uint32_t;
310 311 312 313
using AtomicTagged_t = base::Atomic32;

#else

314 315 316
constexpr int kTaggedSize = kSystemPointerSize;
constexpr int kTaggedSizeLog2 = kSystemPointerSizeLog2;

317 318 319 320
// These types define raw and atomic storage types for tagged values stored
// on V8 heap.
using Tagged_t = Address;
using AtomicTagged_t = base::AtomicWord;
321 322 323 324

#endif  // V8_COMPRESS_POINTERS

STATIC_ASSERT(kTaggedSize == (1 << kTaggedSizeLog2));
325
STATIC_ASSERT((kTaggedSize == 8) == TAGGED_SIZE_8_BYTES);
326

327 328 329 330
using AsAtomicTagged = base::AsAtomicPointerImpl<AtomicTagged_t>;
STATIC_ASSERT(sizeof(Tagged_t) == kTaggedSize);
STATIC_ASSERT(sizeof(AtomicTagged_t) == kTaggedSize);

331 332
STATIC_ASSERT(kTaggedSize == kApiTaggedSize);

333
// TODO(ishell): use kTaggedSize or kSystemPointerSize instead.
334
#ifndef V8_COMPRESS_POINTERS
335 336 337
constexpr int kPointerSize = kSystemPointerSize;
constexpr int kPointerSizeLog2 = kSystemPointerSizeLog2;
STATIC_ASSERT(kPointerSize == (1 << kPointerSizeLog2));
338
#endif
339

340 341 342 343
// This type defines raw storage type for external (or off-V8 heap) pointers
// stored on V8 heap.
constexpr int kExternalPointerSize = sizeof(ExternalPointer_t);

344
constexpr int kEmbedderDataSlotSize = kSystemPointerSize;
345 346 347 348 349

constexpr int kEmbedderDataSlotSizeInTaggedSlots =
    kEmbedderDataSlotSize / kTaggedSize;
STATIC_ASSERT(kEmbedderDataSlotSize >= kSystemPointerSize);

350 351
constexpr int kExternalAllocationSoftLimit =
    internal::Internals::kExternalAllocationSoftLimit;
352

353 354 355 356 357
// Maximum object size that gets allocated into regular pages. Objects larger
// than that size are allocated in large object space and are never moved in
// memory. This also applies to new space allocation, since objects are never
// migrated from new space to large object space. Takes double alignment into
// account.
358
//
359 360
// Current value: half of the page size.
constexpr int kMaxRegularHeapObjectSize = (1 << (kPageSizeBits - 1));
361

362 363
constexpr int kBitsPerByte = 8;
constexpr int kBitsPerByteLog2 = 3;
364
constexpr int kBitsPerSystemPointer = kSystemPointerSize * kBitsPerByte;
365 366
constexpr int kBitsPerSystemPointerLog2 =
    kSystemPointerSizeLog2 + kBitsPerByteLog2;
367
constexpr int kBitsPerInt = kIntSize * kBitsPerByte;
368

369
// IEEE 754 single precision floating point number bit layout.
370 371 372 373 374 375 376 377
constexpr uint32_t kBinary32SignMask = 0x80000000u;
constexpr uint32_t kBinary32ExponentMask = 0x7f800000u;
constexpr uint32_t kBinary32MantissaMask = 0x007fffffu;
constexpr int kBinary32ExponentBias = 127;
constexpr int kBinary32MaxExponent = 0xFE;
constexpr int kBinary32MinExponent = 0x01;
constexpr int kBinary32MantissaBits = 23;
constexpr int kBinary32ExponentShift = 23;
378

379 380
// Quiet NaNs have bits 51 to 62 set, possibly the sign bit, and no
// other bits set.
381
constexpr uint64_t kQuietNaNMask = static_cast<uint64_t>(0xfff) << 51;
382

383
constexpr int kOneByteSize = kCharSize;
384

385
// 128 bit SIMD value size.
386
constexpr int kSimd128Size = 16;
387

388 389 390
// Maximum ordinal used for tracking asynchronous module evaluation order.
constexpr unsigned kMaxModuleAsyncEvaluatingOrdinal = (1 << 30) - 1;

391
// FUNCTION_ADDR(f) gets the address of a C function f.
392
#define FUNCTION_ADDR(f) (reinterpret_cast<v8::internal::Address>(f))
393 394 395

// FUNCTION_CAST<F>(addr) casts an address into a function
// of type F. Used to invoke generated code from within C.
396 397 398 399 400
template <typename F>
F FUNCTION_CAST(byte* addr) {
  return reinterpret_cast<F>(reinterpret_cast<Address>(addr));
}

401 402
template <typename F>
F FUNCTION_CAST(Address addr) {
403
  return reinterpret_cast<F>(addr);
404 405
}

406 407 408
// Determine whether the architecture uses function descriptors
// which provide a level of indirection between the function pointer
// and the function entrypoint.
409
#if (V8_HOST_ARCH_PPC || V8_HOST_ARCH_PPC64) &&                    \
410
    (V8_OS_AIX || (V8_TARGET_ARCH_PPC64 && V8_TARGET_BIG_ENDIAN && \
411
                   (!defined(_CALL_ELF) || _CALL_ELF == 1)))
412 413 414 415 416 417 418 419
#define USES_FUNCTION_DESCRIPTORS 1
#define FUNCTION_ENTRYPOINT_ADDRESS(f)       \
  (reinterpret_cast<v8::internal::Address*>( \
      &(reinterpret_cast<intptr_t*>(f)[0])))
#else
#define USES_FUNCTION_DESCRIPTORS 0
#endif

420 421 422 423
// -----------------------------------------------------------------------------
// Declarations for use in both the preparser and the rest of V8.

// The Strict Mode (ECMA-262 5th edition, 4.2.2).
424

425 426 427 428 429 430
enum class LanguageMode : bool { kSloppy, kStrict };
static const size_t LanguageModeSize = 2;

inline size_t hash_value(LanguageMode mode) {
  return static_cast<size_t>(mode);
}
marja's avatar
marja committed
431

432
inline const char* LanguageMode2String(LanguageMode mode) {
433
  switch (mode) {
434
    case LanguageMode::kSloppy:
435
      return "sloppy";
436
    case LanguageMode::kStrict:
437
      return "strict";
438
  }
439
  UNREACHABLE();
440 441
}

442 443 444 445
inline std::ostream& operator<<(std::ostream& os, LanguageMode mode) {
  return os << LanguageMode2String(mode);
}

marja's avatar
marja committed
446
inline bool is_sloppy(LanguageMode language_mode) {
447
  return language_mode == LanguageMode::kSloppy;
marja's avatar
marja committed
448 449
}

450
inline bool is_strict(LanguageMode language_mode) {
451
  return language_mode != LanguageMode::kSloppy;
452 453 454
}

inline bool is_valid_language_mode(int language_mode) {
455 456
  return language_mode == static_cast<int>(LanguageMode::kSloppy) ||
         language_mode == static_cast<int>(LanguageMode::kStrict);
marja's avatar
marja committed
457 458
}

459 460
inline LanguageMode construct_language_mode(bool strict_bit) {
  return static_cast<LanguageMode>(strict_bit);
461
}
462

463 464 465 466 467 468 469 470 471
// Return kStrict if either of the language modes is kStrict, or kSloppy
// otherwise.
inline LanguageMode stricter_language_mode(LanguageMode mode1,
                                           LanguageMode mode2) {
  STATIC_ASSERT(LanguageModeSize == 2);
  return static_cast<LanguageMode>(static_cast<int>(mode1) |
                                   static_cast<int>(mode2));
}

472 473 474 475
// A non-keyed store is of the form a.x = foo or a["x"] = foo whereas
// a keyed store is of the form a[expression] = foo.
enum class StoreOrigin { kMaybeKeyed, kNamed };

476
enum class TypeofMode { kInside, kNotInside };
477

478 479
// Use by RecordWrite stubs.
enum class RememberedSetAction { kOmit, kEmit };
480
// Enums used by CEntry.
481 482
enum class SaveFPRegsMode { kIgnore, kSave };
enum class ArgvMode { kStack, kRegister };
483

yangguo's avatar
yangguo committed
484
// This constant is used as an undefined value when passing source positions.
485
constexpr int kNoSourcePosition = -1;
marja's avatar
marja committed
486

487 488 489 490
// This constant is used to signal the function entry implicit stack check
// bytecode offset.
constexpr int kFunctionEntryBytecodeOffset = -1;

491 492 493 494
// This constant is used to signal the function exit interrupt budget handling
// bytecode offset.
constexpr int kFunctionExitBytecodeOffset = -1;

495
// This constant is used to indicate missing deoptimization information.
496
constexpr int kNoDeoptimizationId = -1;
497

498 499 500 501 502 503 504 505
// Deoptimize bailout kind:
// - Eager: a check failed in the optimized code and deoptimization happens
//   immediately.
// - Lazy: the code has been marked as dependent on some assumption which
//   is checked elsewhere and can trigger deoptimization the next time the
//   code is executed.
// - Soft: similar to lazy deoptimization, but does not contribute to the
//   total deopt count which can lead to disabling optimization for a function.
506 507 508
// - Bailout: a check failed in the optimized code but we don't
//   deoptimize the code, but try to heal the feedback and try to rerun
//   the optimized code again.
509 510 511
// - EagerWithResume: a check failed in the optimized code, but we can execute
//   a more expensive check in a builtin that might either result in us resuming
//   execution in the optimized code, or deoptimizing immediately.
512 513 514
enum class DeoptimizeKind : uint8_t {
  kEager,
  kSoft,
515
  kBailout,
516
  kLazy,
517
  kEagerWithResume,
518
};
519
constexpr DeoptimizeKind kFirstDeoptimizeKind = DeoptimizeKind::kEager;
520
constexpr DeoptimizeKind kLastDeoptimizeKind = DeoptimizeKind::kEagerWithResume;
521 522
STATIC_ASSERT(static_cast<int>(kFirstDeoptimizeKind) == 0);
constexpr int kDeoptimizeKindCount = static_cast<int>(kLastDeoptimizeKind) + 1;
523 524 525 526 527 528 529 530 531
inline size_t hash_value(DeoptimizeKind kind) {
  return static_cast<size_t>(kind);
}
inline std::ostream& operator<<(std::ostream& os, DeoptimizeKind kind) {
  switch (kind) {
    case DeoptimizeKind::kEager:
      return os << "Eager";
    case DeoptimizeKind::kSoft:
      return os << "Soft";
532 533
    case DeoptimizeKind::kLazy:
      return os << "Lazy";
534 535
    case DeoptimizeKind::kBailout:
      return os << "Bailout";
536 537
    case DeoptimizeKind::kEagerWithResume:
      return os << "EagerMaybeResume";
538 539 540
  }
}

541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
// Indicates whether the lookup is related to sloppy-mode block-scoped
// function hoisting, and is a synthetic assignment for that.
enum class LookupHoistingMode { kNormal, kLegacySloppy };

inline std::ostream& operator<<(std::ostream& os,
                                const LookupHoistingMode& mode) {
  switch (mode) {
    case LookupHoistingMode::kNormal:
      return os << "normal hoisting";
    case LookupHoistingMode::kLegacySloppy:
      return os << "legacy sloppy hoisting";
  }
  UNREACHABLE();
}

556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
static_assert(kSmiValueSize <= 32, "Unsupported Smi tagging scheme");
// Smi sign bit position must be 32-bit aligned so we can use sign extension
// instructions on 64-bit architectures without additional shifts.
static_assert((kSmiValueSize + kSmiShiftSize + kSmiTagSize) % 32 == 0,
              "Unsupported Smi tagging scheme");

constexpr bool kIsSmiValueInUpper32Bits =
    (kSmiValueSize + kSmiShiftSize + kSmiTagSize) == 64;
constexpr bool kIsSmiValueInLower32Bits =
    (kSmiValueSize + kSmiShiftSize + kSmiTagSize) == 32;
static_assert(!SmiValuesAre32Bits() == SmiValuesAre31Bits(),
              "Unsupported Smi tagging scheme");
static_assert(SmiValuesAre32Bits() == kIsSmiValueInUpper32Bits,
              "Unsupported Smi tagging scheme");
static_assert(SmiValuesAre31Bits() == kIsSmiValueInLower32Bits,
              "Unsupported Smi tagging scheme");

573
// Mask for the sign bit in a smi.
574 575
constexpr intptr_t kSmiSignMask = static_cast<intptr_t>(
    uintptr_t{1} << (kSmiValueSize + kSmiShiftSize + kSmiTagSize - 1));
576

577 578
// Desired alignment for tagged pointers.
constexpr int kObjectAlignmentBits = kTaggedSizeLog2;
579 580
constexpr intptr_t kObjectAlignment = 1 << kObjectAlignmentBits;
constexpr intptr_t kObjectAlignmentMask = kObjectAlignment - 1;
581

582 583
// Desired alignment for system pointers.
constexpr intptr_t kPointerAlignment = (1 << kSystemPointerSizeLog2);
584
constexpr intptr_t kPointerAlignmentMask = kPointerAlignment - 1;
585 586

// Desired alignment for double values.
587 588
constexpr intptr_t kDoubleAlignment = 8;
constexpr intptr_t kDoubleAlignmentMask = kDoubleAlignment - 1;
589 590 591

// Desired alignment for generated code is 32 bytes (to improve cache line
// utilization).
592 593 594
constexpr int kCodeAlignmentBits = 5;
constexpr intptr_t kCodeAlignment = 1 << kCodeAlignmentBits;
constexpr intptr_t kCodeAlignmentMask = kCodeAlignment - 1;
595

596
const Address kWeakHeapObjectMask = 1 << 1;
597 598 599 600 601 602 603 604 605 606 607 608 609 610

// The lower 32 bits of the cleared weak reference value is always equal to
// the |kClearedWeakHeapObjectLower32| constant but on 64-bit architectures
// the value of the upper 32 bits part may be
// 1) zero when pointer compression is disabled,
// 2) upper 32 bits of the isolate root value when pointer compression is
//    enabled.
// This is necessary to make pointer decompression computation also suitable
// for cleared weak reference.
// Note, that real heap objects can't have lower 32 bits equal to 3 because
// this offset belongs to page header. So, in either case it's enough to
// compare only the lower 32 bits of a MaybeObject value in order to figure
// out if it's a cleared reference or not.
const uint32_t kClearedWeakHeapObjectLower32 = 3;
611 612 613 614

// Zap-value: The value used for zapping dead objects.
// Should be a recognizable hex value tagged as a failure.
#ifdef V8_HOST_ARCH_64_BIT
615
constexpr uint64_t kClearedFreeMemoryValue = 0;
616 617 618 619 620 621 622
constexpr uint64_t kZapValue = uint64_t{0xdeadbeedbeadbeef};
constexpr uint64_t kHandleZapValue = uint64_t{0x1baddead0baddeaf};
constexpr uint64_t kGlobalHandleZapValue = uint64_t{0x1baffed00baffedf};
constexpr uint64_t kFromSpaceZapValue = uint64_t{0x1beefdad0beefdaf};
constexpr uint64_t kDebugZapValue = uint64_t{0xbadbaddbbadbaddb};
constexpr uint64_t kSlotsZapValue = uint64_t{0xbeefdeadbeefdeef};
constexpr uint64_t kFreeListZapValue = 0xfeed1eaffeed1eaf;
623
#else
624
constexpr uint32_t kClearedFreeMemoryValue = 0;
625 626 627 628 629 630 631
constexpr uint32_t kZapValue = 0xdeadbeef;
constexpr uint32_t kHandleZapValue = 0xbaddeaf;
constexpr uint32_t kGlobalHandleZapValue = 0xbaffedf;
constexpr uint32_t kFromSpaceZapValue = 0xbeefdaf;
constexpr uint32_t kSlotsZapValue = 0xbeefdeef;
constexpr uint32_t kDebugZapValue = 0xbadbaddb;
constexpr uint32_t kFreeListZapValue = 0xfeed1eaf;
632 633
#endif

634 635
constexpr int kCodeZapValue = 0xbadc0de;
constexpr uint32_t kPhantomReferenceZap = 0xca11bac;
636

637 638 639
// Page constants.
static const intptr_t kPageAlignmentMask = (intptr_t{1} << kPageSizeBits) - 1;

640 641 642 643 644 645 646
// On Intel architecture, cache line size is 64 bytes.
// On ARM it may be less (32 bytes), but as far this constant is
// used for aligning data, it doesn't hurt to align on a greater value.
#define PROCESSOR_CACHE_LINE_SIZE 64

// Constants relevant to double precision floating point numbers.
// If looking only at the top 32 bits, the QNaN mask is bits 19 to 30.
647
constexpr uint32_t kQuietNaNHighBitsMask = 0xfff << (51 - 32);
648

649 650 651 652 653
enum class HeapObjectReferenceType {
  WEAK,
  STRONG,
};

654 655 656 657 658
enum class ArgumentsType {
  kRuntime,
  kJS,
};

659 660 661 662
// -----------------------------------------------------------------------------
// Forward declarations for frequently used classes

class AccessorInfo;
663
template <ArgumentsType>
664
class Arguments;
665 666
using RuntimeArguments = Arguments<ArgumentsType::kRuntime>;
using JavaScriptArguments = Arguments<ArgumentsType::kJS>;
667
class Assembler;
668
class ClassScope;
669
class Code;
670
class CodeDataContainer;
671
class CodeSpace;
672
class Context;
673
class DeclarationScope;
674 675 676 677 678 679
class Debug;
class DebugInfo;
class Descriptor;
class DescriptorArray;
class TransitionArray;
class ExternalReference;
680
class FeedbackVector;
681
class FixedArray;
682
class Foreign;
683
class FreeStoreAllocationPolicy;
684
class FunctionTemplateInfo;
685
class GlobalDictionary;
686 687
template <typename T>
class Handle;
688 689
class Heap;
class HeapObject;
690
class HeapObjectReference;
691 692 693 694 695 696 697
class IC;
class InterceptorInfo;
class Isolate;
class JSReceiver;
class JSArray;
class JSFunction;
class JSObject;
698
class LocalIsolate;
699 700 701 702
class MacroAssembler;
class Map;
class MapSpace;
class MarkCompactCollector;
703 704
template <typename T>
class MaybeHandle;
705
class MaybeObject;
706 707 708 709 710
class MemoryChunk;
class MessageLocation;
class ModuleScope;
class Name;
class NameDictionary;
711
class NativeContext;
712
class NewSpace;
713
class NewLargeObjectSpace;
714
class NumberDictionary;
715
class Object;
716
class OldLargeObjectSpace;
717 718
template <HeapObjectReferenceType kRefType, typename StorageType>
class TaggedImpl;
719 720
class StrongTaggedValue;
class TaggedValue;
721 722 723 724
class CompressedObjectSlot;
class CompressedMaybeObjectSlot;
class CompressedMapWordSlot;
class CompressedHeapObjectSlot;
725
class OffHeapCompressedObjectSlot;
726 727 728
class FullObjectSlot;
class FullMaybeObjectSlot;
class FullHeapObjectSlot;
729
class OffHeapFullObjectSlot;
730
class OldSpace;
731
class ReadOnlySpace;
732
class RelocInfo;
733 734 735
class Scope;
class ScopeInfo;
class Script;
736
class SimpleNumberDictionary;
737 738
class Smi;
template <typename Config, class Allocator = FreeStoreAllocationPolicy>
739
class SplayTree;
740
class String;
741
class StringStream;
742
class Struct;
743
class Symbol;
744 745
class Variable;

746 747 748
// Slots are either full-pointer slots or compressed slots depending on whether
// pointer compression is enabled or not.
struct SlotTraits {
749 750 751 752
#ifdef V8_COMPRESS_POINTERS
  using TObjectSlot = CompressedObjectSlot;
  using TMaybeObjectSlot = CompressedMaybeObjectSlot;
  using THeapObjectSlot = CompressedHeapObjectSlot;
753
  using TOffHeapObjectSlot = OffHeapCompressedObjectSlot;
754 755
  // TODO(v8:11880): switch to OffHeapCompressedObjectSlot.
  using TCodeObjectSlot = CompressedObjectSlot;
756
#else
757 758 759
  using TObjectSlot = FullObjectSlot;
  using TMaybeObjectSlot = FullMaybeObjectSlot;
  using THeapObjectSlot = FullHeapObjectSlot;
760
  using TOffHeapObjectSlot = OffHeapFullObjectSlot;
761 762
  // TODO(v8:11880): switch to OffHeapFullObjectSlot.
  using TCodeObjectSlot = FullObjectSlot;
763
#endif
764 765 766
};

// An ObjectSlot instance describes a kTaggedSize-sized on-heap field ("slot")
767 768
// holding an Object value (smi or strong heap object).
using ObjectSlot = SlotTraits::TObjectSlot;
769 770 771

// A MaybeObjectSlot instance describes a kTaggedSize-sized on-heap field
// ("slot") holding MaybeObject (smi or weak heap object or strong heap object).
772
using MaybeObjectSlot = SlotTraits::TMaybeObjectSlot;
773 774 775 776

// A HeapObjectSlot instance describes a kTaggedSize-sized field ("slot")
// holding a weak or strong pointer to a heap object (think:
// HeapObjectReference).
777 778 779 780 781 782
using HeapObjectSlot = SlotTraits::THeapObjectSlot;

// An OffHeapObjectSlot instance describes a kTaggedSize-sized field ("slot")
// holding an Object value (smi or strong heap object), whose slot location is
// off-heap.
using OffHeapObjectSlot = SlotTraits::TOffHeapObjectSlot;
783

784 785 786 787 788 789
// A CodeObjectSlot instance describes a kTaggedSize-sized field ("slot")
// holding a strong pointer to a Code object. The Code object slots might be
// compressed and since code space might be allocated off the main heap
// the load operations require explicit cage base value for code space.
using CodeObjectSlot = SlotTraits::TCodeObjectSlot;

790
using WeakSlotCallback = bool (*)(FullObjectSlot pointer);
791

792
using WeakSlotCallbackWithHeap = bool (*)(Heap* heap, FullObjectSlot pointer);
793 794 795 796 797 798 799

// -----------------------------------------------------------------------------
// Miscellaneous

// NOTE: SpaceIterator depends on AllocationSpace enumeration values being
// consecutive.
enum AllocationSpace {
800 801 802 803 804
  RO_SPACE,       // Immortal, immovable and immutable objects,
  OLD_SPACE,      // Old generation regular object space.
  CODE_SPACE,     // Old generation code object space, marked executable.
  MAP_SPACE,      // Old generation map object space, non-movable.
  LO_SPACE,       // Old generation large object space.
805 806
  CODE_LO_SPACE,  // Old generation large code object space.
  NEW_LO_SPACE,   // Young generation large object space.
807 808
  NEW_SPACE,  // Young generation semispaces for regular objects collected with
              // Scavenger.
809

810
  FIRST_SPACE = RO_SPACE,
811 812 813
  LAST_SPACE = NEW_SPACE,
  FIRST_MUTABLE_SPACE = OLD_SPACE,
  LAST_MUTABLE_SPACE = NEW_SPACE,
814 815
  FIRST_GROWABLE_PAGED_SPACE = OLD_SPACE,
  LAST_GROWABLE_PAGED_SPACE = MAP_SPACE
816
};
817
constexpr int kSpaceTagSize = 4;
818
STATIC_ASSERT(FIRST_SPACE == 0);
819

820
enum class AllocationType : uint8_t {
821 822 823 824 825 826 827 828
  kYoung,      // Regular object allocated in NEW_SPACE or NEW_LO_SPACE
  kOld,        // Regular object allocated in OLD_SPACE or LO_SPACE
  kCode,       // Code object allocated in CODE_SPACE or CODE_LO_SPACE
  kMap,        // Map object allocated in MAP_SPACE
  kReadOnly,   // Object allocated in RO_SPACE
  kSharedOld,  // Regular object allocated in SHARED_OLD_SPACE or
               // SHARED_LO_SPACE
  kSharedMap,  // Map object in SHARED_MAP_SPACE
829 830
};

831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846
inline size_t hash_value(AllocationType kind) {
  return static_cast<uint8_t>(kind);
}

inline std::ostream& operator<<(std::ostream& os, AllocationType kind) {
  switch (kind) {
    case AllocationType::kYoung:
      return os << "Young";
    case AllocationType::kOld:
      return os << "Old";
    case AllocationType::kCode:
      return os << "Code";
    case AllocationType::kMap:
      return os << "Map";
    case AllocationType::kReadOnly:
      return os << "ReadOnly";
847 848 849 850
    case AllocationType::kSharedOld:
      return os << "SharedOld";
    case AllocationType::kSharedMap:
      return os << "SharedMap";
851 852 853 854
  }
  UNREACHABLE();
}

855 856 857 858 859
inline constexpr bool IsSharedAllocationType(AllocationType kind) {
  return kind == AllocationType::kSharedOld ||
         kind == AllocationType::kSharedMap;
}

860
// TODO(ishell): review and rename kWordAligned to kTaggedAligned.
861
enum AllocationAlignment { kWordAligned, kDoubleAligned, kDoubleUnaligned };
862

863 864
enum class AccessMode { ATOMIC, NON_ATOMIC };

865 866
enum class AllowLargeObjects { kFalse, kTrue };

867 868 869 870 871
enum MinimumCapacity {
  USE_DEFAULT_MINIMUM_CAPACITY,
  USE_CUSTOM_MINIMUM_CAPACITY
};

872
enum GarbageCollector { SCAVENGER, MARK_COMPACTOR, MINOR_MARK_COMPACTOR };
873

874
enum class CompactionSpaceKind {
875
  kNone,
876 877 878
  kCompactionSpaceForScavenge,
  kCompactionSpaceForMarkCompact,
  kCompactionSpaceForMinorMarkCompact,
879 880
};

881 882
enum Executability { NOT_EXECUTABLE, EXECUTABLE };

883
enum class CodeFlushMode {
884 885
  kFlushBytecode,
  kFlushBaselineCode,
886
  kStressFlushCode,
887 888
};

889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904
bool inline IsBaselineCodeFlushingEnabled(base::EnumSet<CodeFlushMode> mode) {
  return mode.contains(CodeFlushMode::kFlushBaselineCode);
}

bool inline IsByteCodeFlushingEnabled(base::EnumSet<CodeFlushMode> mode) {
  return mode.contains(CodeFlushMode::kFlushBytecode);
}

bool inline IsStressFlushingEnabled(base::EnumSet<CodeFlushMode> mode) {
  return mode.contains(CodeFlushMode::kStressFlushCode);
}

bool inline IsFlushingDisabled(base::EnumSet<CodeFlushMode> mode) {
  return mode.empty();
}

Simon Zünd's avatar
Simon Zünd committed
905 906 907 908 909 910
// Indicates whether a script should be parsed and compiled in REPL mode.
enum class REPLMode {
  kYes,
  kNo,
};

911 912 913 914
inline REPLMode construct_repl_mode(bool is_repl_mode) {
  return is_repl_mode ? REPLMode::kYes : REPLMode::kNo;
}

915
// Flag indicating whether code is built into the VM (one of the natives files).
916
enum NativesFlag { NOT_NATIVES_CODE, EXTENSION_CODE, INSPECTOR_CODE };
917

918 919
// ParseRestriction is used to restrict the set of valid statements in a
// unit of compilation.  Restriction violations cause a syntax error.
920
enum ParseRestriction : bool {
921 922 923 924
  NO_PARSE_RESTRICTION,         // All expressions are allowed.
  ONLY_SINGLE_FUNCTION_LITERAL  // Only a single FunctionLiteral expression.
};

925 926
// State for inline cache call sites. Aliased as IC::State.
enum InlineCacheState {
927 928
  // No feedback will be collected.
  NO_FEEDBACK,
929 930 931 932
  // Has never been executed.
  UNINITIALIZED,
  // Has been executed and only one receiver type has been seen.
  MONOMORPHIC,
933
  // Check failed due to prototype (or map deprecation).
934
  RECOMPUTE_HANDLER,
935 936
  // Multiple receiver types have been seen.
  POLYMORPHIC,
937 938
  // Many DOM receiver types have been seen for the same accessor.
  MEGADOM,
939 940 941 942 943 944
  // Many receiver types have been seen.
  MEGAMORPHIC,
  // A generic handler is installed and no extra typefeedback is recorded.
  GENERIC,
};

945 946 947
// Printing support.
inline const char* InlineCacheState2String(InlineCacheState state) {
  switch (state) {
948 949
    case NO_FEEDBACK:
      return "NOFEEDBACK";
950 951 952 953 954 955 956 957 958 959
    case UNINITIALIZED:
      return "UNINITIALIZED";
    case MONOMORPHIC:
      return "MONOMORPHIC";
    case RECOMPUTE_HANDLER:
      return "RECOMPUTE_HANDLER";
    case POLYMORPHIC:
      return "POLYMORPHIC";
    case MEGAMORPHIC:
      return "MEGAMORPHIC";
960 961
    case MEGADOM:
      return "MEGADOM";
962 963 964 965 966 967
    case GENERIC:
      return "GENERIC";
  }
  UNREACHABLE();
}

968
enum WhereToStart { kStartAtReceiver, kStartAtPrototype };
969

970 971
enum ResultSentinel { kNotFound = -1, kUnsupported = -2 };

972 973 974 975
enum ShouldThrow {
  kThrowOnError = Internals::kThrowOnError,
  kDontThrow = Internals::kDontThrow
};
976

977
enum class ThreadKind { kMain, kBackground };
978 979 980 981 982 983 984

// Union used for customized checking of the IEEE double types
// inlined within v8 runtime, rather than going to the underlying
// platform headers and libraries
union IeeeDoubleLittleEndianArchType {
  double d;
  struct {
985 986 987 988
    unsigned int man_low : 32;
    unsigned int man_high : 20;
    unsigned int exp : 11;
    unsigned int sign : 1;
989 990 991 992 993 994
  } bits;
};

union IeeeDoubleBigEndianArchType {
  double d;
  struct {
995 996 997 998
    unsigned int sign : 1;
    unsigned int exp : 11;
    unsigned int man_high : 20;
    unsigned int man_low : 32;
999 1000 1001
  } bits;
};

1002
#if V8_TARGET_LITTLE_ENDIAN
1003
using IeeeDoubleArchType = IeeeDoubleLittleEndianArchType;
1004 1005
constexpr int kIeeeDoubleMantissaWordOffset = 0;
constexpr int kIeeeDoubleExponentWordOffset = 4;
1006
#else
1007
using IeeeDoubleArchType = IeeeDoubleBigEndianArchType;
1008 1009
constexpr int kIeeeDoubleMantissaWordOffset = 4;
constexpr int kIeeeDoubleExponentWordOffset = 0;
1010
#endif
1011 1012 1013 1014 1015 1016 1017

// -----------------------------------------------------------------------------
// Macros

// Testers for test.

#define HAS_SMI_TAG(value) \
1018
  ((static_cast<i::Tagged_t>(value) & ::i::kSmiTagMask) == ::i::kSmiTag)
1019

1020 1021
#define HAS_STRONG_HEAP_OBJECT_TAG(value)                          \
  (((static_cast<i::Tagged_t>(value) & ::i::kHeapObjectTagMask) == \
1022
    ::i::kHeapObjectTag))
1023

1024 1025
#define HAS_WEAK_HEAP_OBJECT_TAG(value)                            \
  (((static_cast<i::Tagged_t>(value) & ::i::kHeapObjectTagMask) == \
1026 1027
    ::i::kWeakHeapObjectTag))

1028
// OBJECT_POINTER_ALIGN returns the value aligned as a HeapObject pointer
1029 1030
#define OBJECT_POINTER_ALIGN(value) \
  (((value) + ::i::kObjectAlignmentMask) & ~::i::kObjectAlignmentMask)
1031

1032 1033 1034 1035
// OBJECT_POINTER_PADDING returns the padding size required to align value
// as a HeapObject pointer
#define OBJECT_POINTER_PADDING(value) (OBJECT_POINTER_ALIGN(value) - (value))

1036
// POINTER_SIZE_ALIGN returns the value aligned as a system pointer.
1037 1038
#define POINTER_SIZE_ALIGN(value) \
  (((value) + ::i::kPointerAlignmentMask) & ~::i::kPointerAlignmentMask)
1039

1040 1041 1042 1043
// POINTER_SIZE_PADDING returns the padding size required to align value
// as a system pointer.
#define POINTER_SIZE_PADDING(value) (POINTER_SIZE_ALIGN(value) - (value))

1044
// CODE_POINTER_ALIGN returns the value aligned as a generated code segment.
1045 1046
#define CODE_POINTER_ALIGN(value) \
  (((value) + ::i::kCodeAlignmentMask) & ~::i::kCodeAlignmentMask)
1047

1048 1049 1050 1051
// CODE_POINTER_PADDING returns the padding size required to align value
// as a generated code segment.
#define CODE_POINTER_PADDING(value) (CODE_POINTER_ALIGN(value) - (value))

1052 1053
// DOUBLE_POINTER_ALIGN returns the value algined for double pointers.
#define DOUBLE_POINTER_ALIGN(value) \
1054
  (((value) + ::i::kDoubleAlignmentMask) & ~::i::kDoubleAlignmentMask)
1055

1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
// Defines hints about receiver values based on structural knowledge.
enum class ConvertReceiverMode : unsigned {
  kNullOrUndefined,     // Guaranteed to be null or undefined.
  kNotNullOrUndefined,  // Guaranteed to never be null or undefined.
  kAny                  // No specific knowledge about receiver.
};

inline size_t hash_value(ConvertReceiverMode mode) {
  return bit_cast<unsigned>(mode);
}

inline std::ostream& operator<<(std::ostream& os, ConvertReceiverMode mode) {
  switch (mode) {
    case ConvertReceiverMode::kNullOrUndefined:
      return os << "NULL_OR_UNDEFINED";
    case ConvertReceiverMode::kNotNullOrUndefined:
      return os << "NOT_NULL_OR_UNDEFINED";
    case ConvertReceiverMode::kAny:
      return os << "ANY";
  }
  UNREACHABLE();
}

1079 1080 1081 1082 1083 1084 1085 1086
// Valid hints for the abstract operation OrdinaryToPrimitive,
// implemented according to ES6, section 7.1.1.
enum class OrdinaryToPrimitiveHint { kNumber, kString };

// Valid hints for the abstract operation ToPrimitive,
// implemented according to ES6, section 7.1.1.
enum class ToPrimitiveHint { kDefault, kNumber, kString };

1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
// Defines specifics about arguments object or rest parameter creation.
enum class CreateArgumentsType : uint8_t {
  kMappedArguments,
  kUnmappedArguments,
  kRestParameter
};

inline size_t hash_value(CreateArgumentsType type) {
  return bit_cast<uint8_t>(type);
}

inline std::ostream& operator<<(std::ostream& os, CreateArgumentsType type) {
  switch (type) {
    case CreateArgumentsType::kMappedArguments:
      return os << "MAPPED_ARGUMENTS";
    case CreateArgumentsType::kUnmappedArguments:
      return os << "UNMAPPED_ARGUMENTS";
    case CreateArgumentsType::kRestParameter:
      return os << "REST_PARAMETER";
  }
  UNREACHABLE();
}

1110
enum ScopeType : uint8_t {
1111
  CLASS_SCOPE,     // The scope introduced by a class.
1112 1113 1114
  EVAL_SCOPE,      // The top-level scope for an eval source.
  FUNCTION_SCOPE,  // The top-level scope for a function.
  MODULE_SCOPE,    // The scope introduced by a module literal
1115
  SCRIPT_SCOPE,    // The top-level scope for a script or a top-level eval.
1116 1117
  CATCH_SCOPE,     // The scope introduced by catch.
  BLOCK_SCOPE,     // The scope introduced by a new block.
1118
  WITH_SCOPE       // The scope introduced by with.
1119 1120
};

1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
inline std::ostream& operator<<(std::ostream& os, ScopeType type) {
  switch (type) {
    case ScopeType::EVAL_SCOPE:
      return os << "EVAL_SCOPE";
    case ScopeType::FUNCTION_SCOPE:
      return os << "FUNCTION_SCOPE";
    case ScopeType::MODULE_SCOPE:
      return os << "MODULE_SCOPE";
    case ScopeType::SCRIPT_SCOPE:
      return os << "SCRIPT_SCOPE";
    case ScopeType::CATCH_SCOPE:
      return os << "CATCH_SCOPE";
    case ScopeType::BLOCK_SCOPE:
      return os << "BLOCK_SCOPE";
1135 1136
    case ScopeType::CLASS_SCOPE:
      return os << "CLASS_SCOPE";
1137 1138 1139 1140 1141 1142
    case ScopeType::WITH_SCOPE:
      return os << "WITH_SCOPE";
  }
  UNREACHABLE();
}

1143 1144 1145 1146 1147 1148 1149 1150
// AllocationSiteMode controls whether allocations are tracked by an allocation
// site.
enum AllocationSiteMode {
  DONT_TRACK_ALLOCATION_SITE,
  TRACK_ALLOCATION_SITE,
  LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
};

1151 1152
enum class AllocationSiteUpdateMode { kUpdate, kCheckOnly };

1153
// The mips architecture prior to revision 5 has inverted encoding for sNaN.
1154 1155 1156
#if (V8_TARGET_ARCH_MIPS && !defined(_MIPS_ARCH_MIPS32R6) &&           \
     (!defined(USE_SIMULATOR) || !defined(_MIPS_TARGET_SIMULATOR))) || \
    (V8_TARGET_ARCH_MIPS64 && !defined(_MIPS_ARCH_MIPS64R6) &&         \
Jakob Kummerow's avatar
Jakob Kummerow committed
1157
     (!defined(USE_SIMULATOR) || !defined(_MIPS_TARGET_SIMULATOR)))
1158 1159
constexpr uint32_t kHoleNanUpper32 = 0xFFFF7FFF;
constexpr uint32_t kHoleNanLower32 = 0xFFFF7FFF;
1160
#else
1161 1162
constexpr uint32_t kHoleNanUpper32 = 0xFFF7FFFF;
constexpr uint32_t kHoleNanLower32 = 0xFFF7FFFF;
1163
#endif
1164

1165
constexpr uint64_t kHoleNanInt64 =
1166 1167
    (static_cast<uint64_t>(kHoleNanUpper32) << 32) | kHoleNanLower32;

1168
// ES6 section 20.1.2.6 Number.MAX_SAFE_INTEGER
1169 1170
constexpr uint64_t kMaxSafeIntegerUint64 = 9007199254740991;  // 2^53-1
constexpr double kMaxSafeInteger = static_cast<double>(kMaxSafeIntegerUint64);
1171 1172
// ES6 section 21.1.2.8 Number.MIN_SAFE_INTEGER
constexpr double kMinSafeInteger = -kMaxSafeInteger;
1173

1174 1175
constexpr double kMaxUInt32Double = double{kMaxUInt32};

1176
// The order of this enum has to be kept in sync with the predicates below.
1177
enum class VariableMode : uint8_t {
1178
  // User declared variables:
1179
  kLet,  // declared via 'let' declarations (first lexical)
1180

1181
  kConst,  // declared via 'const' declarations (last lexical)
1182

1183
  kVar,  // declared via 'var', and 'function' declarations
1184

1185
  // Variables introduced by the compiler:
1186 1187
  kTemporary,  // temporary variables (not user-visible), stack-allocated
               // unless the scope as a whole has forced context allocation
1188

1189 1190
  kDynamic,  // always require dynamic lookup (we don't know
             // the declaration)
1191

1192
  kDynamicGlobal,  // requires dynamic lookup, but we know that the
1193 1194 1195
                   // variable is global unless it has been shadowed
                   // by an eval-introduced variable

1196 1197 1198 1199 1200
  kDynamicLocal,  // requires dynamic lookup, but we know that the
                  // variable is local and where it is unless it
                  // has been shadowed by an eval-introduced
                  // variable

1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
  // Variables for private methods or accessors whose access require
  // brand check. Declared only in class scopes by the compiler
  // and allocated only in class contexts:
  kPrivateMethod,  // Does not coexist with any other variable with the same
                   // name in the same scope.

  kPrivateSetterOnly,  // Incompatible with variables with the same name but
                       // any mode other than kPrivateGetterOnly. Transition to
                       // kPrivateGetterAndSetter if a later declaration for the
                       // same name with kPrivateGetterOnly is made.

  kPrivateGetterOnly,  // Incompatible with variables with the same name but
                       // any mode other than kPrivateSetterOnly. Transition to
                       // kPrivateGetterAndSetter if a later declaration for the
                       // same name with kPrivateSetterOnly is made.

  kPrivateGetterAndSetter,  // Does not coexist with any other variable with the
                            // same name in the same scope.

1220
  kLastLexicalVariableMode = kConst,
1221 1222
};

1223 1224 1225 1226
// Printing support
#ifdef DEBUG
inline const char* VariableMode2String(VariableMode mode) {
  switch (mode) {
1227
    case VariableMode::kVar:
1228
      return "VAR";
1229
    case VariableMode::kLet:
1230
      return "LET";
1231 1232 1233 1234 1235 1236 1237 1238
    case VariableMode::kPrivateGetterOnly:
      return "PRIVATE_GETTER_ONLY";
    case VariableMode::kPrivateSetterOnly:
      return "PRIVATE_SETTER_ONLY";
    case VariableMode::kPrivateMethod:
      return "PRIVATE_METHOD";
    case VariableMode::kPrivateGetterAndSetter:
      return "PRIVATE_GETTER_AND_SETTER";
1239
    case VariableMode::kConst:
1240
      return "CONST";
1241
    case VariableMode::kDynamic:
1242
      return "DYNAMIC";
1243
    case VariableMode::kDynamicGlobal:
1244
      return "DYNAMIC_GLOBAL";
1245
    case VariableMode::kDynamicLocal:
1246
      return "DYNAMIC_LOCAL";
1247
    case VariableMode::kTemporary:
1248 1249 1250 1251 1252 1253 1254 1255
      return "TEMPORARY";
  }
  UNREACHABLE();
}
#endif

enum VariableKind : uint8_t {
  NORMAL_VARIABLE,
1256
  PARAMETER_VARIABLE,
1257
  THIS_VARIABLE,
1258
  SLOPPY_BLOCK_FUNCTION_VARIABLE,
1259
  SLOPPY_FUNCTION_NAME_VARIABLE
1260 1261
};

1262
inline bool IsDynamicVariableMode(VariableMode mode) {
1263
  return mode >= VariableMode::kDynamic && mode <= VariableMode::kDynamicLocal;
1264 1265 1266
}

inline bool IsDeclaredVariableMode(VariableMode mode) {
1267 1268 1269
  STATIC_ASSERT(static_cast<uint8_t>(VariableMode::kLet) ==
                0);  // Implies that mode >= VariableMode::kLet.
  return mode <= VariableMode::kVar;
1270 1271
}

1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
inline bool IsPrivateMethodOrAccessorVariableMode(VariableMode mode) {
  return mode >= VariableMode::kPrivateMethod &&
         mode <= VariableMode::kPrivateGetterAndSetter;
}

inline bool IsSerializableVariableMode(VariableMode mode) {
  return IsDeclaredVariableMode(mode) ||
         IsPrivateMethodOrAccessorVariableMode(mode);
}

inline bool IsConstVariableMode(VariableMode mode) {
  return mode == VariableMode::kConst ||
         IsPrivateMethodOrAccessorVariableMode(mode);
}

1287
inline bool IsLexicalVariableMode(VariableMode mode) {
1288 1289
  STATIC_ASSERT(static_cast<uint8_t>(VariableMode::kLet) ==
                0);  // Implies that mode >= VariableMode::kLet.
1290
  return mode <= VariableMode::kLastLexicalVariableMode;
1291 1292
}

1293
enum VariableLocation : uint8_t {
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316
  // Before and during variable allocation, a variable whose location is
  // not yet determined.  After allocation, a variable looked up as a
  // property on the global object (and possibly absent).  name() is the
  // variable name, index() is invalid.
  UNALLOCATED,

  // A slot in the parameter section on the stack.  index() is the
  // parameter index, counting left-to-right.  The receiver is index -1;
  // the first parameter is index 0.
  PARAMETER,

  // A slot in the local section on the stack.  index() is the variable
  // index in the stack frame, starting at 0.
  LOCAL,

  // An indexed slot in a heap context.  index() is the variable index in
  // the context object on the heap, starting at 0.  scope() is the
  // corresponding scope.
  CONTEXT,

  // A named slot in a heap context.  name() is the variable name in the
  // context object on the heap, with lookup starting at the current
  // context.  index() is invalid.
1317
  LOOKUP,
1318

1319
  // A named slot in a module's export table.
1320 1321
  MODULE,

Simon Zünd's avatar
Simon Zünd committed
1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
  // An indexed slot in a script context. index() is the variable
  // index in the context object on the heap, starting at 0.
  // Important: REPL_GLOBAL variables from different scripts with the
  //            same name share a single script context slot. Every
  //            script context will reserve a slot, but only one will be used.
  // REPL_GLOBAL variables are stored in script contexts, but accessed like
  // globals, i.e. they always require a lookup at runtime to find the right
  // script context.
  REPL_GLOBAL,

  kLastVariableLocation = REPL_GLOBAL
1333
};
1334

1335 1336 1337 1338 1339 1340
// ES6 specifies declarative environment records with mutable and immutable
// bindings that can be in two states: initialized and uninitialized.
// When accessing a binding, it needs to be checked for initialization.
// However in the following cases the binding is initialized immediately
// after creation so the initialization check can always be skipped:
//
1341 1342 1343 1344 1345 1346 1347 1348
// 1. Var declared local variables.
//      var foo;
// 2. A local variable introduced by a function declaration.
//      function foo() {}
// 3. Parameters
//      function x(foo) {}
// 4. Catch bound variables.
//      try {} catch (foo) {}
1349
// 6. Function name variables of named function expressions.
1350 1351 1352 1353 1354 1355 1356
//      var x = function foo() {}
// 7. Implicit binding of 'this'.
// 8. Implicit binding of 'arguments' in functions.
//
// The following enum specifies a flag that indicates if the binding needs a
// distinct initialization step (kNeedsInitialization) or if the binding is
// immediately initialized upon creation (kCreatedInitialized).
1357
enum InitializationFlag : uint8_t { kNeedsInitialization, kCreatedInitialized };
1358

1359 1360 1361 1362
// Static variables can only be used with the class in the closest
// class scope as receivers.
enum class IsStaticFlag : uint8_t { kNotStatic, kStatic };

1363
enum MaybeAssignedFlag : uint8_t { kNotAssigned, kMaybeAssigned };
1364

1365
enum class InterpreterPushArgsMode : unsigned {
1366
  kArrayFunction,
1367 1368 1369 1370
  kWithFinalSpread,
  kOther
};

1371
inline size_t hash_value(InterpreterPushArgsMode mode) {
1372 1373 1374
  return bit_cast<unsigned>(mode);
}

1375 1376
inline std::ostream& operator<<(std::ostream& os,
                                InterpreterPushArgsMode mode) {
1377
  switch (mode) {
1378 1379
    case InterpreterPushArgsMode::kArrayFunction:
      return os << "ArrayFunction";
1380
    case InterpreterPushArgsMode::kWithFinalSpread:
1381
      return os << "WithFinalSpread";
1382
    case InterpreterPushArgsMode::kOther:
1383 1384 1385 1386 1387
      return os << "Other";
  }
  UNREACHABLE();
}

1388 1389 1390
inline uint32_t ObjectHash(Address address) {
  // All objects are at least pointer aligned, so we can remove the trailing
  // zeros.
1391
  return static_cast<uint32_t>(address >> kTaggedSizeLog2);
1392 1393
}

1394
// Type feedback is encoded in such a way that, we can combine the feedback
1395 1396
// at different points by performing an 'OR' operation. Type feedback moves
// to a more generic type when we combine feedback.
1397 1398
//
//   kSignedSmall -> kSignedSmallInputs -> kNumber  -> kNumberOrOddball -> kAny
1399
//                                                     kString          -> kAny
1400 1401 1402 1403 1404 1405 1406 1407
//                                                     kBigInt          -> kAny
//
// Technically we wouldn't need the separation between the kNumber and the
// kNumberOrOddball values here, since for binary operations, we always
// truncate oddballs to numbers. In practice though it causes TurboFan to
// generate quite a lot of unused code though if we always handle numbers
// and oddballs everywhere, although in 99% of the use sites they are only
// used with numbers.
1408 1409
class BinaryOperationFeedback {
 public:
1410 1411 1412
  enum {
    kNone = 0x0,
    kSignedSmall = 0x1,
1413
    kSignedSmallInputs = 0x3,
1414 1415
    kNumber = 0x7,
    kNumberOrOddball = 0xF,
1416 1417 1418
    kString = 0x10,
    kBigInt = 0x20,
    kAny = 0x7F
1419
  };
1420 1421
};

1422
// Type feedback is encoded in such a way that, we can combine the feedback
1423
// at different points by performing an 'OR' operation.
1424 1425
// This is distinct from BinaryOperationFeedback on purpose, because the
// feedback that matters differs greatly as well as the way it is consumed.
1426
class CompareOperationFeedback {
1427
  enum {
1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
    kSignedSmallFlag = 1 << 0,
    kOtherNumberFlag = 1 << 1,
    kBooleanFlag = 1 << 2,
    kNullOrUndefinedFlag = 1 << 3,
    kInternalizedStringFlag = 1 << 4,
    kOtherStringFlag = 1 << 5,
    kSymbolFlag = 1 << 6,
    kBigIntFlag = 1 << 7,
    kReceiverFlag = 1 << 8,
    kAnyMask = 0x1FF,
  };

 public:
  enum Type {
    kNone = 0,

    kBoolean = kBooleanFlag,
    kNullOrUndefined = kNullOrUndefinedFlag,
    kOddball = kBoolean | kNullOrUndefined,

    kSignedSmall = kSignedSmallFlag,
    kNumber = kSignedSmall | kOtherNumberFlag,
    kNumberOrBoolean = kNumber | kBoolean,
    kNumberOrOddball = kNumber | kOddball,

    kInternalizedString = kInternalizedStringFlag,
    kString = kInternalizedString | kOtherStringFlag,

    kReceiver = kReceiverFlag,
    kReceiverOrNullOrUndefined = kReceiver | kNullOrUndefined,

    kBigInt = kBigIntFlag,
    kSymbol = kSymbolFlag,

    kAny = kAnyMask,
1463
  };
1464 1465
};

1466 1467 1468 1469 1470 1471 1472
enum class Operation {
  // Binary operations.
  kAdd,
  kSubtract,
  kMultiply,
  kDivide,
  kModulus,
1473
  kExponentiate,
1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493
  kBitwiseAnd,
  kBitwiseOr,
  kBitwiseXor,
  kShiftLeft,
  kShiftRight,
  kShiftRightLogical,
  // Unary operations.
  kBitwiseNot,
  kNegate,
  kIncrement,
  kDecrement,
  // Compare operations.
  kEqual,
  kStrictEqual,
  kLessThan,
  kLessThanOrEqual,
  kGreaterThan,
  kGreaterThanOrEqual,
};

1494 1495 1496 1497
// Type feedback is encoded in such a way that, we can combine the feedback
// at different points by performing an 'OR' operation. Type feedback moves
// to a more generic type when we combine feedback.
// kNone -> kEnumCacheKeysAndIndices -> kEnumCacheKeys -> kAny
1498 1499 1500 1501 1502
enum class ForInFeedback : uint8_t {
  kNone = 0x0,
  kEnumCacheKeysAndIndices = 0x1,
  kEnumCacheKeys = 0x3,
  kAny = 0x7
1503
};
1504 1505 1506 1507 1508 1509 1510 1511 1512
STATIC_ASSERT((static_cast<int>(ForInFeedback::kNone) |
               static_cast<int>(ForInFeedback::kEnumCacheKeysAndIndices)) ==
              static_cast<int>(ForInFeedback::kEnumCacheKeysAndIndices));
STATIC_ASSERT((static_cast<int>(ForInFeedback::kEnumCacheKeysAndIndices) |
               static_cast<int>(ForInFeedback::kEnumCacheKeys)) ==
              static_cast<int>(ForInFeedback::kEnumCacheKeys));
STATIC_ASSERT((static_cast<int>(ForInFeedback::kEnumCacheKeys) |
               static_cast<int>(ForInFeedback::kAny)) ==
              static_cast<int>(ForInFeedback::kAny));
1513

1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533
enum class UnicodeEncoding : uint8_t {
  // Different unicode encodings in a |word32|:
  UTF16,  // hi 16bits -> trailing surrogate or 0, low 16bits -> lead surrogate
  UTF32,  // full UTF32 code unit / Unicode codepoint
};

inline size_t hash_value(UnicodeEncoding encoding) {
  return static_cast<uint8_t>(encoding);
}

inline std::ostream& operator<<(std::ostream& os, UnicodeEncoding encoding) {
  switch (encoding) {
    case UnicodeEncoding::UTF16:
      return os << "UTF16";
    case UnicodeEncoding::UTF32:
      return os << "UTF32";
  }
  UNREACHABLE();
}

1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
enum class IterationKind { kKeys, kValues, kEntries };

inline std::ostream& operator<<(std::ostream& os, IterationKind kind) {
  switch (kind) {
    case IterationKind::kKeys:
      return os << "IterationKind::kKeys";
    case IterationKind::kValues:
      return os << "IterationKind::kValues";
    case IterationKind::kEntries:
      return os << "IterationKind::kEntries";
  }
  UNREACHABLE();
}

1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559
enum class CollectionKind { kMap, kSet };

inline std::ostream& operator<<(std::ostream& os, CollectionKind kind) {
  switch (kind) {
    case CollectionKind::kMap:
      return os << "CollectionKind::kMap";
    case CollectionKind::kSet:
      return os << "CollectionKind::kSet";
  }
  UNREACHABLE();
}

1560 1561 1562 1563 1564 1565 1566 1567
// Flags for the runtime function kDefineDataPropertyInLiteral. A property can
// be enumerable or not, and, in case of functions, the function name
// can be set or not.
enum class DataPropertyInLiteralFlag {
  kNoFlags = 0,
  kDontEnum = 1 << 0,
  kSetFunctionName = 1 << 1
};
1568
using DataPropertyInLiteralFlags = base::Flags<DataPropertyInLiteralFlag>;
1569 1570
DEFINE_OPERATORS_FOR_FLAGS(DataPropertyInLiteralFlags)

1571 1572 1573 1574 1575 1576 1577 1578 1579 1580
enum ExternalArrayType {
  kExternalInt8Array = 1,
  kExternalUint8Array,
  kExternalInt16Array,
  kExternalUint16Array,
  kExternalInt32Array,
  kExternalUint32Array,
  kExternalFloat32Array,
  kExternalFloat64Array,
  kExternalUint8ClampedArray,
1581 1582
  kExternalBigInt64Array,
  kExternalBigUint64Array,
1583 1584
};

1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
struct AssemblerDebugInfo {
  AssemblerDebugInfo(const char* name, const char* file, int line)
      : name(name), file(file), line(line) {}
  const char* name;
  const char* file;
  int line;
};

inline std::ostream& operator<<(std::ostream& os,
                                const AssemblerDebugInfo& info) {
  os << "(" << info.name << ":" << info.file << ":" << info.line << ")";
  return os;
}

1599 1600
using FileAndLine = std::pair<const char*, int>;

1601 1602 1603 1604 1605 1606 1607 1608 1609
enum OptimizationMarker : int32_t {
  // These values are set so that it is easy to check if there is a marker where
  // some processing needs to be done.
  kNone = 0b000,
  kInOptimizationQueue = 0b001,
  kCompileOptimized = 0b010,
  kCompileOptimizedConcurrent = 0b011,
  kLogFirstExecution = 0b100,
  kLastOptimizationMarker = kLogFirstExecution
1610
};
1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
// For kNone or kInOptimizationQueue we don't need any special processing.
// To check both cases using a single mask, we expect the kNone to be 0 and
// kInOptimizationQueue to be 1 so that we can mask off the lsb for checking.
STATIC_ASSERT(kNone == 0b000 && kInOptimizationQueue == 0b001);
STATIC_ASSERT(kLastOptimizationMarker <= 0b111);
static constexpr uint32_t kNoneOrInOptimizationQueueMask = 0b110;

inline bool IsInOptimizationQueueMarker(OptimizationMarker marker) {
  return marker == OptimizationMarker::kInOptimizationQueue;
}

inline bool IsCompileOptimizedMarker(OptimizationMarker marker) {
  return marker == OptimizationMarker::kCompileOptimized ||
         marker == OptimizationMarker::kCompileOptimizedConcurrent;
}
1626 1627 1628 1629

inline std::ostream& operator<<(std::ostream& os,
                                const OptimizationMarker& marker) {
  switch (marker) {
1630 1631
    case OptimizationMarker::kLogFirstExecution:
      return os << "OptimizationMarker::kLogFirstExecution";
1632 1633 1634 1635 1636 1637 1638 1639 1640
    case OptimizationMarker::kNone:
      return os << "OptimizationMarker::kNone";
    case OptimizationMarker::kCompileOptimized:
      return os << "OptimizationMarker::kCompileOptimized";
    case OptimizationMarker::kCompileOptimizedConcurrent:
      return os << "OptimizationMarker::kCompileOptimizedConcurrent";
    case OptimizationMarker::kInOptimizationQueue:
      return os << "OptimizationMarker::kInOptimizationQueue";
  }
1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661
}

enum class OptimizationTier {
  kNone = 0b00,
  kMidTier = 0b01,
  kTopTier = 0b10,
  kLastOptimizationTier = kTopTier
};
static constexpr uint32_t kNoneOrMidTierMask = 0b10;
static constexpr uint32_t kNoneMask = 0b11;

inline std::ostream& operator<<(std::ostream& os,
                                const OptimizationTier& tier) {
  switch (tier) {
    case OptimizationTier::kNone:
      return os << "OptimizationTier::kNone";
    case OptimizationTier::kMidTier:
      return os << "OptimizationTier::kMidTier";
    case OptimizationTier::kTopTier:
      return os << "OptimizationTier::kTopTier";
  }
1662 1663
}

1664
enum class SpeculationMode { kAllowSpeculation, kDisallowSpeculation };
1665
enum class CallFeedbackContent { kTarget, kReceiver };
1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678

inline std::ostream& operator<<(std::ostream& os,
                                SpeculationMode speculation_mode) {
  switch (speculation_mode) {
    case SpeculationMode::kAllowSpeculation:
      return os << "SpeculationMode::kAllowSpeculation";
    case SpeculationMode::kDisallowSpeculation:
      return os << "SpeculationMode::kDisallowSpeculation";
  }
  UNREACHABLE();
  return os;
}

1679 1680
enum class BlockingBehavior { kBlock, kDontBlock };

1681 1682
enum class ConcurrencyMode { kNotConcurrent, kConcurrent };

1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694
#define FOR_EACH_ISOLATE_ADDRESS_NAME(C)                       \
  C(Handler, handler)                                          \
  C(CEntryFP, c_entry_fp)                                      \
  C(CFunction, c_function)                                     \
  C(Context, context)                                          \
  C(PendingException, pending_exception)                       \
  C(PendingHandlerContext, pending_handler_context)            \
  C(PendingHandlerEntrypoint, pending_handler_entrypoint)      \
  C(PendingHandlerConstantPool, pending_handler_constant_pool) \
  C(PendingHandlerFP, pending_handler_fp)                      \
  C(PendingHandlerSP, pending_handler_sp)                      \
  C(ExternalCaughtException, external_caught_exception)        \
1695
  C(JSEntrySP, js_entry_sp)
1696 1697 1698 1699 1700 1701 1702 1703

enum IsolateAddressId {
#define DECLARE_ENUM(CamelName, hacker_name) k##CamelName##Address,
  FOR_EACH_ISOLATE_ADDRESS_NAME(DECLARE_ENUM)
#undef DECLARE_ENUM
      kIsolateAddressCount
};

1704 1705 1706 1707 1708
enum class PoisoningMitigationLevel {
  kPoisonAll,
  kDontPoison,
  kPoisonCriticalOnly
};
1709

1710 1711 1712 1713 1714 1715 1716
enum class LoadSensitivity {
  kCritical,  // Critical loads are poisoned whenever we can run untrusted
              // code (i.e., when --untrusted-code-mitigations is on).
  kUnsafe,    // Unsafe loads are poisoned when full poisoning is on
              // (--branch-load-poisoning).
  kSafe       // Safe loads are never poisoned.
};
1717

1718 1719 1720 1721
// The reason for a WebAssembly trap.
#define FOREACH_WASM_TRAPREASON(V) \
  V(TrapUnreachable)               \
  V(TrapMemOutOfBounds)            \
1722
  V(TrapUnalignedAccess)           \
1723 1724 1725 1726
  V(TrapDivByZero)                 \
  V(TrapDivUnrepresentable)        \
  V(TrapRemByZero)                 \
  V(TrapFloatUnrepresentable)      \
1727
  V(TrapFuncSigMismatch)           \
1728
  V(TrapDataSegmentDropped)        \
1729
  V(TrapElemSegmentDropped)        \
1730
  V(TrapTableOutOfBounds)          \
1731
  V(TrapRethrowNull)               \
1732
  V(TrapNullDereference)           \
1733
  V(TrapIllegalCast)               \
1734 1735
  V(TrapArrayOutOfBounds)          \
  V(TrapArrayTooLarge)
1736

1737 1738
enum WasmRttSubMode { kCanonicalize, kFresh };

1739 1740 1741 1742 1743 1744 1745
enum KeyedAccessLoadMode {
  STANDARD_LOAD,
  LOAD_IGNORE_OUT_OF_BOUNDS,
};

enum KeyedAccessStoreMode {
  STANDARD_STORE,
1746 1747 1748
  STORE_AND_GROW_HANDLE_COW,
  STORE_IGNORE_OUT_OF_BOUNDS,
  STORE_HANDLE_COW
1749 1750 1751 1752
};

enum MutableMode { MUTABLE, IMMUTABLE };

1753
inline bool IsCOWHandlingStoreMode(KeyedAccessStoreMode store_mode) {
1754 1755
  return store_mode == STORE_HANDLE_COW ||
         store_mode == STORE_AND_GROW_HANDLE_COW;
1756 1757
}

1758
inline bool IsGrowStoreMode(KeyedAccessStoreMode store_mode) {
1759
  return store_mode == STORE_AND_GROW_HANDLE_COW;
1760 1761 1762
}

enum IcCheckType { ELEMENT, PROPERTY };
1763 1764 1765

// Helper stubs can be called in different ways depending on where the target
// code is located and how the call sequence is expected to look like:
1766
//  - CodeObject: Call on-heap {Code} object via {RelocInfo::CODE_TARGET}.
1767 1768 1769 1770 1771 1772
//  - WasmRuntimeStub: Call native {WasmCode} stub via
//    {RelocInfo::WASM_STUB_CALL}.
//  - BuiltinPointer: Call a builtin based on a builtin pointer with dynamic
//    contents. If builtins are embedded, we call directly into off-heap code
//    without going through the on-heap Code trampoline.
enum class StubCallMode {
1773
  kCallCodeObject,
1774
#if V8_ENABLE_WEBASSEMBLY
1775
  kCallWasmRuntimeStub,
1776
#endif  // V8_ENABLE_WEBASSEMBLY
1777 1778
  kCallBuiltinPointer,
};
1779

1780 1781 1782
constexpr int kFunctionLiteralIdInvalid = -1;
constexpr int kFunctionLiteralIdTopLevel = 0;

1783 1784
constexpr int kSwissNameDictionaryInitialCapacity = 4;

1785 1786 1787
constexpr int kSmallOrderedHashSetMinCapacity = 4;
constexpr int kSmallOrderedHashMapMinCapacity = 4;

1788 1789
static const uint16_t kDontAdaptArgumentsSentinel = static_cast<uint16_t>(-1);

1790 1791 1792 1793 1794 1795
// Opaque data type for identifying stack frames. Used extensively
// by the debugger.
// ID_MIN_VALUE and ID_MAX_VALUE are specified to ensure that enumeration type
// has correct value range (see Issue 830 for more details).
enum StackFrameId { ID_MIN_VALUE = kMinInt, ID_MAX_VALUE = kMaxInt, NO_ID = 0 };

1796 1797 1798 1799 1800
enum class ExceptionStatus : bool { kException = false, kSuccess = true };
V8_INLINE bool operator!(ExceptionStatus status) {
  return !static_cast<bool>(status);
}

1801 1802
enum class TraceRetainingPathMode { kEnabled, kDisabled };

1803 1804 1805 1806 1807
// Used in the ScopeInfo flags fields for the function name variable for named
// function expressions, and for the receiver. Must be declared here so that it
// can be used in Torque.
enum class VariableAllocationInfo { NONE, STACK, CONTEXT, UNUSED };

1808
enum class DynamicCheckMapsStatus : uint8_t {
1809 1810 1811 1812 1813
  kSuccess = 0,
  kBailout = 1,
  kDeopt = 2
};

1814
#ifdef V8_COMPRESS_POINTERS
1815
class PtrComprCageBase {
1816
 public:
1817
  explicit constexpr PtrComprCageBase(Address address) : address_(address) {}
1818
  // NOLINTNEXTLINE
1819
  inline PtrComprCageBase(const Isolate* isolate);
1820
  // NOLINTNEXTLINE
1821
  inline PtrComprCageBase(const LocalIsolate* isolate);
1822 1823 1824

  inline Address address() const;

1825 1826 1827 1828
  bool operator==(const PtrComprCageBase& other) const {
    return address_ == other.address_;
  }

1829 1830 1831 1832
 private:
  Address address_;
};
#else
1833
class PtrComprCageBase {
1834
 public:
1835
  PtrComprCageBase() = default;
1836
  // NOLINTNEXTLINE
1837
  PtrComprCageBase(const Isolate* isolate) {}
1838
  // NOLINTNEXTLINE
1839
  PtrComprCageBase(const LocalIsolate* isolate) {}
1840 1841 1842
};
#endif

1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860
class int31_t {
 public:
  constexpr int31_t() : value_(0) {}
  constexpr int31_t(int value) : value_(value) {  // NOLINT(runtime/explicit)
    DCHECK_EQ((value & 0x80000000) != 0, (value & 0x40000000) != 0);
  }
  int31_t& operator=(int value) {
    DCHECK_EQ((value & 0x80000000) != 0, (value & 0x40000000) != 0);
    value_ = value;
    return *this;
  }
  int32_t value() const { return value_; }
  operator int32_t() const { return value_; }

 private:
  int32_t value_;
};

1861 1862 1863 1864 1865 1866 1867 1868
enum PropertiesEnumerationMode {
  // String and then Symbol properties according to the spec
  // ES#sec-object.assign
  kEnumerationOrder,
  // Order of property addition
  kPropertyAdditionOrder,
};

1869
}  // namespace internal
1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880

// Tag dispatching support for acquire loads and release stores.
struct AcquireLoadTag {};
struct RelaxedLoadTag {};
struct ReleaseStoreTag {};
struct RelaxedStoreTag {};
static constexpr AcquireLoadTag kAcquireLoad;
static constexpr RelaxedLoadTag kRelaxedLoad;
static constexpr ReleaseStoreTag kReleaseStore;
static constexpr RelaxedStoreTag kRelaxedStore;

1881
}  // namespace v8
1882

1883 1884
namespace i = v8::internal;

1885
#endif  // V8_COMMON_GLOBALS_H_