1 // Copyright 2012 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.
10 #include "src/allocation.h"
11 #include "src/assert-scope.h"
12 #include "src/bailout-reason.h"
13 #include "src/base/bits.h"
14 #include "src/base/smart-pointers.h"
15 #include "src/builtins.h"
16 #include "src/checks.h"
17 #include "src/elements-kind.h"
18 #include "src/field-index.h"
19 #include "src/flags.h"
21 #include "src/property-details.h"
22 #include "src/unicode.h"
23 #include "src/unicode-decoder.h"
26 #if V8_TARGET_ARCH_ARM
27 #include "src/arm/constants-arm.h" // NOLINT
28 #elif V8_TARGET_ARCH_ARM64
29 #include "src/arm64/constants-arm64.h" // NOLINT
30 #elif V8_TARGET_ARCH_MIPS
31 #include "src/mips/constants-mips.h" // NOLINT
32 #elif V8_TARGET_ARCH_MIPS64
33 #include "src/mips64/constants-mips64.h" // NOLINT
34 #elif V8_TARGET_ARCH_PPC
35 #include "src/ppc/constants-ppc.h" // NOLINT
40 // Most object types in the V8 JavaScript are described in this file.
42 // Inheritance hierarchy:
44 // - Smi (immediate small integer)
45 // - HeapObject (superclass for everything allocated in the heap)
46 // - JSReceiver (suitable for property access)
50 // - JSArrayBufferView
63 // - JSGeneratorObject
82 // - CompilationCacheTable
83 // - CodeCacheHashTable
89 // - TypeFeedbackVector
92 // - ScriptContextTable
103 // - ExternalOneByteString
104 // - ExternalTwoByteString
105 // - InternalizedString
106 // - SeqInternalizedString
107 // - SeqOneByteInternalizedString
108 // - SeqTwoByteInternalizedString
109 // - ConsInternalizedString
110 // - ExternalInternalizedString
111 // - ExternalOneByteInternalizedString
112 // - ExternalTwoByteInternalizedString
132 // - SharedFunctionInfo
136 // - ExecutableAccessorInfo
142 // - FunctionTemplateInfo
143 // - ObjectTemplateInfo
152 // Formats of Object*:
153 // Smi: [31 bit signed int] 0
154 // HeapObject: [32 bit direct pointer] (4 byte aligned) | 01
159 enum KeyedAccessStoreMode {
161 STORE_TRANSITION_TO_OBJECT,
162 STORE_TRANSITION_TO_DOUBLE,
163 STORE_AND_GROW_NO_TRANSITION,
164 STORE_AND_GROW_TRANSITION_TO_OBJECT,
165 STORE_AND_GROW_TRANSITION_TO_DOUBLE,
166 STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS,
167 STORE_NO_TRANSITION_HANDLE_COW
171 // Valid hints for the abstract operation ToPrimitive,
172 // implemented according to ES6, section 7.1.1.
173 enum class ToPrimitiveHint { kDefault, kNumber, kString };
176 // Valid hints for the abstract operation OrdinaryToPrimitive,
177 // implemented according to ES6, section 7.1.1.
178 enum class OrdinaryToPrimitiveHint { kNumber, kString };
181 enum TypeofMode { INSIDE_TYPEOF, NOT_INSIDE_TYPEOF };
190 enum ExternalArrayType {
191 kExternalInt8Array = 1,
194 kExternalUint16Array,
196 kExternalUint32Array,
197 kExternalFloat32Array,
198 kExternalFloat64Array,
199 kExternalUint8ClampedArray,
203 static inline bool IsTransitionStoreMode(KeyedAccessStoreMode store_mode) {
204 return store_mode == STORE_TRANSITION_TO_OBJECT ||
205 store_mode == STORE_TRANSITION_TO_DOUBLE ||
206 store_mode == STORE_AND_GROW_TRANSITION_TO_OBJECT ||
207 store_mode == STORE_AND_GROW_TRANSITION_TO_DOUBLE;
211 static inline KeyedAccessStoreMode GetNonTransitioningStoreMode(
212 KeyedAccessStoreMode store_mode) {
213 if (store_mode >= STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS) {
216 if (store_mode >= STORE_AND_GROW_NO_TRANSITION) {
217 return STORE_AND_GROW_NO_TRANSITION;
219 return STANDARD_STORE;
223 static inline bool IsGrowStoreMode(KeyedAccessStoreMode store_mode) {
224 return store_mode >= STORE_AND_GROW_NO_TRANSITION &&
225 store_mode <= STORE_AND_GROW_TRANSITION_TO_DOUBLE;
229 enum IcCheckType { ELEMENT, PROPERTY };
232 // SKIP_WRITE_BARRIER skips the write barrier.
233 // UPDATE_WEAK_WRITE_BARRIER skips the marking part of the write barrier and
234 // only performs the generational part.
235 // UPDATE_WRITE_BARRIER is doing the full barrier, marking and generational.
236 enum WriteBarrierMode {
238 UPDATE_WEAK_WRITE_BARRIER,
243 // Indicates whether a value can be loaded as a constant.
244 enum StoreMode { ALLOW_IN_DESCRIPTOR, FORCE_FIELD };
247 // PropertyNormalizationMode is used to specify whether to keep
248 // inobject properties when normalizing properties of a JSObject.
249 enum PropertyNormalizationMode {
250 CLEAR_INOBJECT_PROPERTIES,
251 KEEP_INOBJECT_PROPERTIES
255 // Indicates how aggressively the prototype should be optimized. FAST_PROTOTYPE
256 // will give the fastest result by tailoring the map to the prototype, but that
257 // will cause polymorphism with other objects. REGULAR_PROTOTYPE is to be used
258 // (at least for now) when dynamically modifying the prototype chain of an
259 // object using __proto__ or Object.setPrototypeOf.
260 enum PrototypeOptimizationMode { REGULAR_PROTOTYPE, FAST_PROTOTYPE };
263 // Indicates whether transitions can be added to a source map or not.
264 enum TransitionFlag {
270 // Indicates whether the transition is simple: the target map of the transition
271 // either extends the current map with a new property, or it modifies the
272 // property that was added last to the current map.
273 enum SimpleTransitionFlag {
274 SIMPLE_PROPERTY_TRANSITION,
280 // Indicates whether we are only interested in the descriptors of a particular
281 // map, or in all descriptors in the descriptor array.
282 enum DescriptorFlag {
287 // The GC maintains a bit of information, the MarkingParity, which toggles
288 // from odd to even and back every time marking is completed. Incremental
289 // marking can visit an object twice during a marking phase, so algorithms that
290 // that piggy-back on marking can use the parity to ensure that they only
291 // perform an operation on an object once per marking phase: they record the
292 // MarkingParity when they visit an object, and only re-visit the object when it
293 // is marked again and the MarkingParity changes.
300 // ICs store extra state in a Code object. The default extra state is
302 typedef int ExtraICState;
303 static const ExtraICState kNoExtraICState = 0;
305 // Instance size sentinel for objects of variable size.
306 const int kVariableSizeSentinel = 0;
308 // We may store the unsigned bit field as signed Smi value and do not
310 const int kStubMajorKeyBits = 7;
311 const int kStubMinorKeyBits = kSmiValueSize - kStubMajorKeyBits - 1;
313 // All Maps have a field instance_type containing a InstanceType.
314 // It describes the type of the instances.
316 // As an example, a JavaScript object is a heap object and its map
317 // instance_type is JS_OBJECT_TYPE.
319 // The names of the string instance types are intended to systematically
320 // mirror their encoding in the instance_type field of the map. The default
321 // encoding is considered TWO_BYTE. It is not mentioned in the name. ONE_BYTE
322 // encoding is mentioned explicitly in the name. Likewise, the default
323 // representation is considered sequential. It is not mentioned in the
324 // name. The other representations (e.g. CONS, EXTERNAL) are explicitly
325 // mentioned. Finally, the string is either a STRING_TYPE (if it is a normal
326 // string) or a INTERNALIZED_STRING_TYPE (if it is a internalized string).
328 // NOTE: The following things are some that depend on the string types having
329 // instance_types that are less than those of all other types:
330 // HeapObject::Size, HeapObject::IterateBody, the typeof operator, and
333 // NOTE: Everything following JS_VALUE_TYPE is considered a
334 // JSObject for GC purposes. The first four entries here have typeof
335 // 'object', whereas JS_FUNCTION_TYPE has typeof 'function'.
336 #define INSTANCE_TYPE_LIST(V) \
338 V(ONE_BYTE_STRING_TYPE) \
339 V(CONS_STRING_TYPE) \
340 V(CONS_ONE_BYTE_STRING_TYPE) \
341 V(SLICED_STRING_TYPE) \
342 V(SLICED_ONE_BYTE_STRING_TYPE) \
343 V(EXTERNAL_STRING_TYPE) \
344 V(EXTERNAL_ONE_BYTE_STRING_TYPE) \
345 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
346 V(SHORT_EXTERNAL_STRING_TYPE) \
347 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE) \
348 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
350 V(INTERNALIZED_STRING_TYPE) \
351 V(ONE_BYTE_INTERNALIZED_STRING_TYPE) \
352 V(EXTERNAL_INTERNALIZED_STRING_TYPE) \
353 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
354 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
355 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE) \
356 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
357 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
360 V(SIMD128_VALUE_TYPE) \
366 V(PROPERTY_CELL_TYPE) \
368 V(HEAP_NUMBER_TYPE) \
369 V(MUTABLE_HEAP_NUMBER_TYPE) \
372 V(BYTECODE_ARRAY_TYPE) \
375 V(FIXED_INT8_ARRAY_TYPE) \
376 V(FIXED_UINT8_ARRAY_TYPE) \
377 V(FIXED_INT16_ARRAY_TYPE) \
378 V(FIXED_UINT16_ARRAY_TYPE) \
379 V(FIXED_INT32_ARRAY_TYPE) \
380 V(FIXED_UINT32_ARRAY_TYPE) \
381 V(FIXED_FLOAT32_ARRAY_TYPE) \
382 V(FIXED_FLOAT64_ARRAY_TYPE) \
383 V(FIXED_UINT8_CLAMPED_ARRAY_TYPE) \
387 V(DECLARED_ACCESSOR_DESCRIPTOR_TYPE) \
388 V(DECLARED_ACCESSOR_INFO_TYPE) \
389 V(EXECUTABLE_ACCESSOR_INFO_TYPE) \
390 V(ACCESSOR_PAIR_TYPE) \
391 V(ACCESS_CHECK_INFO_TYPE) \
392 V(INTERCEPTOR_INFO_TYPE) \
393 V(CALL_HANDLER_INFO_TYPE) \
394 V(FUNCTION_TEMPLATE_INFO_TYPE) \
395 V(OBJECT_TEMPLATE_INFO_TYPE) \
396 V(SIGNATURE_INFO_TYPE) \
397 V(TYPE_SWITCH_INFO_TYPE) \
398 V(ALLOCATION_MEMENTO_TYPE) \
399 V(ALLOCATION_SITE_TYPE) \
402 V(POLYMORPHIC_CODE_CACHE_TYPE) \
403 V(TYPE_FEEDBACK_INFO_TYPE) \
404 V(ALIASED_ARGUMENTS_ENTRY_TYPE) \
406 V(PROTOTYPE_INFO_TYPE) \
407 V(SLOPPY_BLOCK_WITH_EVAL_CONTEXT_EXTENSION_TYPE) \
409 V(FIXED_ARRAY_TYPE) \
410 V(FIXED_DOUBLE_ARRAY_TYPE) \
411 V(SHARED_FUNCTION_INFO_TYPE) \
414 V(JS_MESSAGE_OBJECT_TYPE) \
419 V(JS_CONTEXT_EXTENSION_OBJECT_TYPE) \
420 V(JS_GENERATOR_OBJECT_TYPE) \
422 V(JS_GLOBAL_OBJECT_TYPE) \
423 V(JS_BUILTINS_OBJECT_TYPE) \
424 V(JS_GLOBAL_PROXY_TYPE) \
426 V(JS_ARRAY_BUFFER_TYPE) \
427 V(JS_TYPED_ARRAY_TYPE) \
428 V(JS_DATA_VIEW_TYPE) \
432 V(JS_SET_ITERATOR_TYPE) \
433 V(JS_MAP_ITERATOR_TYPE) \
434 V(JS_WEAK_MAP_TYPE) \
435 V(JS_WEAK_SET_TYPE) \
438 V(JS_FUNCTION_TYPE) \
439 V(JS_FUNCTION_PROXY_TYPE) \
441 V(BREAK_POINT_INFO_TYPE)
444 // Since string types are not consecutive, this macro is used to
445 // iterate over them.
446 #define STRING_TYPE_LIST(V) \
447 V(STRING_TYPE, kVariableSizeSentinel, string, String) \
448 V(ONE_BYTE_STRING_TYPE, kVariableSizeSentinel, one_byte_string, \
450 V(CONS_STRING_TYPE, ConsString::kSize, cons_string, ConsString) \
451 V(CONS_ONE_BYTE_STRING_TYPE, ConsString::kSize, cons_one_byte_string, \
453 V(SLICED_STRING_TYPE, SlicedString::kSize, sliced_string, SlicedString) \
454 V(SLICED_ONE_BYTE_STRING_TYPE, SlicedString::kSize, sliced_one_byte_string, \
455 SlicedOneByteString) \
456 V(EXTERNAL_STRING_TYPE, ExternalTwoByteString::kSize, external_string, \
458 V(EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kSize, \
459 external_one_byte_string, ExternalOneByteString) \
460 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, ExternalTwoByteString::kSize, \
461 external_string_with_one_byte_data, ExternalStringWithOneByteData) \
462 V(SHORT_EXTERNAL_STRING_TYPE, ExternalTwoByteString::kShortSize, \
463 short_external_string, ShortExternalString) \
464 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kShortSize, \
465 short_external_one_byte_string, ShortExternalOneByteString) \
466 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, \
467 ExternalTwoByteString::kShortSize, \
468 short_external_string_with_one_byte_data, \
469 ShortExternalStringWithOneByteData) \
471 V(INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, internalized_string, \
472 InternalizedString) \
473 V(ONE_BYTE_INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, \
474 one_byte_internalized_string, OneByteInternalizedString) \
475 V(EXTERNAL_INTERNALIZED_STRING_TYPE, ExternalTwoByteString::kSize, \
476 external_internalized_string, ExternalInternalizedString) \
477 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, ExternalOneByteString::kSize, \
478 external_one_byte_internalized_string, ExternalOneByteInternalizedString) \
479 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
480 ExternalTwoByteString::kSize, \
481 external_internalized_string_with_one_byte_data, \
482 ExternalInternalizedStringWithOneByteData) \
483 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE, \
484 ExternalTwoByteString::kShortSize, short_external_internalized_string, \
485 ShortExternalInternalizedString) \
486 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, \
487 ExternalOneByteString::kShortSize, \
488 short_external_one_byte_internalized_string, \
489 ShortExternalOneByteInternalizedString) \
490 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
491 ExternalTwoByteString::kShortSize, \
492 short_external_internalized_string_with_one_byte_data, \
493 ShortExternalInternalizedStringWithOneByteData)
495 // A struct is a simple object a set of object-valued fields. Including an
496 // object type in this causes the compiler to generate most of the boilerplate
497 // code for the class including allocation and garbage collection routines,
498 // casts and predicates. All you need to define is the class, methods and
499 // object verification routines. Easy, no?
501 // Note that for subtle reasons related to the ordering or numerical values of
502 // type tags, elements in this list have to be added to the INSTANCE_TYPE_LIST
504 #define STRUCT_LIST(V) \
506 V(EXECUTABLE_ACCESSOR_INFO, ExecutableAccessorInfo, \
507 executable_accessor_info) \
508 V(ACCESSOR_PAIR, AccessorPair, accessor_pair) \
509 V(ACCESS_CHECK_INFO, AccessCheckInfo, access_check_info) \
510 V(INTERCEPTOR_INFO, InterceptorInfo, interceptor_info) \
511 V(CALL_HANDLER_INFO, CallHandlerInfo, call_handler_info) \
512 V(FUNCTION_TEMPLATE_INFO, FunctionTemplateInfo, function_template_info) \
513 V(OBJECT_TEMPLATE_INFO, ObjectTemplateInfo, object_template_info) \
514 V(TYPE_SWITCH_INFO, TypeSwitchInfo, type_switch_info) \
515 V(SCRIPT, Script, script) \
516 V(ALLOCATION_SITE, AllocationSite, allocation_site) \
517 V(ALLOCATION_MEMENTO, AllocationMemento, allocation_memento) \
518 V(CODE_CACHE, CodeCache, code_cache) \
519 V(POLYMORPHIC_CODE_CACHE, PolymorphicCodeCache, polymorphic_code_cache) \
520 V(TYPE_FEEDBACK_INFO, TypeFeedbackInfo, type_feedback_info) \
521 V(ALIASED_ARGUMENTS_ENTRY, AliasedArgumentsEntry, aliased_arguments_entry) \
522 V(DEBUG_INFO, DebugInfo, debug_info) \
523 V(BREAK_POINT_INFO, BreakPointInfo, break_point_info) \
524 V(PROTOTYPE_INFO, PrototypeInfo, prototype_info) \
525 V(SLOPPY_BLOCK_WITH_EVAL_CONTEXT_EXTENSION, \
526 SloppyBlockWithEvalContextExtension, \
527 sloppy_block_with_eval_context_extension)
529 // We use the full 8 bits of the instance_type field to encode heap object
530 // instance types. The high-order bit (bit 7) is set if the object is not a
531 // string, and cleared if it is a string.
532 const uint32_t kIsNotStringMask = 0x80;
533 const uint32_t kStringTag = 0x0;
534 const uint32_t kNotStringTag = 0x80;
536 // Bit 6 indicates that the object is an internalized string (if set) or not.
537 // Bit 7 has to be clear as well.
538 const uint32_t kIsNotInternalizedMask = 0x40;
539 const uint32_t kNotInternalizedTag = 0x40;
540 const uint32_t kInternalizedTag = 0x0;
542 // If bit 7 is clear then bit 2 indicates whether the string consists of
543 // two-byte characters or one-byte characters.
544 const uint32_t kStringEncodingMask = 0x4;
545 const uint32_t kTwoByteStringTag = 0x0;
546 const uint32_t kOneByteStringTag = 0x4;
548 // If bit 7 is clear, the low-order 2 bits indicate the representation
550 const uint32_t kStringRepresentationMask = 0x03;
551 enum StringRepresentationTag {
553 kConsStringTag = 0x1,
554 kExternalStringTag = 0x2,
555 kSlicedStringTag = 0x3
557 const uint32_t kIsIndirectStringMask = 0x1;
558 const uint32_t kIsIndirectStringTag = 0x1;
559 STATIC_ASSERT((kSeqStringTag & kIsIndirectStringMask) == 0); // NOLINT
560 STATIC_ASSERT((kExternalStringTag & kIsIndirectStringMask) == 0); // NOLINT
561 STATIC_ASSERT((kConsStringTag &
562 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
563 STATIC_ASSERT((kSlicedStringTag &
564 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
566 // Use this mask to distinguish between cons and slice only after making
567 // sure that the string is one of the two (an indirect string).
568 const uint32_t kSlicedNotConsMask = kSlicedStringTag & ~kConsStringTag;
569 STATIC_ASSERT(IS_POWER_OF_TWO(kSlicedNotConsMask));
571 // If bit 7 is clear, then bit 3 indicates whether this two-byte
572 // string actually contains one byte data.
573 const uint32_t kOneByteDataHintMask = 0x08;
574 const uint32_t kOneByteDataHintTag = 0x08;
576 // If bit 7 is clear and string representation indicates an external string,
577 // then bit 4 indicates whether the data pointer is cached.
578 const uint32_t kShortExternalStringMask = 0x10;
579 const uint32_t kShortExternalStringTag = 0x10;
582 // A ConsString with an empty string as the right side is a candidate
583 // for being shortcut by the garbage collector. We don't allocate any
584 // non-flat internalized strings, so we do not shortcut them thereby
585 // avoiding turning internalized strings into strings. The bit-masks
586 // below contain the internalized bit as additional safety.
587 // See heap.cc, mark-compact.cc and objects-visiting.cc.
588 const uint32_t kShortcutTypeMask =
590 kIsNotInternalizedMask |
591 kStringRepresentationMask;
592 const uint32_t kShortcutTypeTag = kConsStringTag | kNotInternalizedTag;
594 static inline bool IsShortcutCandidate(int type) {
595 return ((type & kShortcutTypeMask) == kShortcutTypeTag);
601 INTERNALIZED_STRING_TYPE = kTwoByteStringTag | kSeqStringTag |
602 kInternalizedTag, // FIRST_PRIMITIVE_TYPE
603 ONE_BYTE_INTERNALIZED_STRING_TYPE =
604 kOneByteStringTag | kSeqStringTag | kInternalizedTag,
605 EXTERNAL_INTERNALIZED_STRING_TYPE =
606 kTwoByteStringTag | kExternalStringTag | kInternalizedTag,
607 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
608 kOneByteStringTag | kExternalStringTag | kInternalizedTag,
609 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
610 EXTERNAL_INTERNALIZED_STRING_TYPE | kOneByteDataHintTag |
612 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE = EXTERNAL_INTERNALIZED_STRING_TYPE |
613 kShortExternalStringTag |
615 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
616 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kShortExternalStringTag |
618 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
619 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
620 kShortExternalStringTag | kInternalizedTag,
621 STRING_TYPE = INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
622 ONE_BYTE_STRING_TYPE =
623 ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
624 CONS_STRING_TYPE = kTwoByteStringTag | kConsStringTag | kNotInternalizedTag,
625 CONS_ONE_BYTE_STRING_TYPE =
626 kOneByteStringTag | kConsStringTag | kNotInternalizedTag,
628 kTwoByteStringTag | kSlicedStringTag | kNotInternalizedTag,
629 SLICED_ONE_BYTE_STRING_TYPE =
630 kOneByteStringTag | kSlicedStringTag | kNotInternalizedTag,
631 EXTERNAL_STRING_TYPE =
632 EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
633 EXTERNAL_ONE_BYTE_STRING_TYPE =
634 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
635 EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
636 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
638 SHORT_EXTERNAL_STRING_TYPE =
639 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
640 SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE =
641 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
642 SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
643 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
647 SYMBOL_TYPE = kNotStringTag, // FIRST_NONSTRING_TYPE, LAST_NAME_TYPE
649 // Other primitives (cannot contain non-map-word pointers to heap objects).
652 ODDBALL_TYPE, // LAST_PRIMITIVE_TYPE
654 // Objects allocated in their own spaces (never in new space).
658 // "Data", objects that cannot contain non-map-word pointers to heap
660 MUTABLE_HEAP_NUMBER_TYPE,
665 FIXED_INT8_ARRAY_TYPE, // FIRST_FIXED_TYPED_ARRAY_TYPE
666 FIXED_UINT8_ARRAY_TYPE,
667 FIXED_INT16_ARRAY_TYPE,
668 FIXED_UINT16_ARRAY_TYPE,
669 FIXED_INT32_ARRAY_TYPE,
670 FIXED_UINT32_ARRAY_TYPE,
671 FIXED_FLOAT32_ARRAY_TYPE,
672 FIXED_FLOAT64_ARRAY_TYPE,
673 FIXED_UINT8_CLAMPED_ARRAY_TYPE, // LAST_FIXED_TYPED_ARRAY_TYPE
674 FIXED_DOUBLE_ARRAY_TYPE,
675 FILLER_TYPE, // LAST_DATA_TYPE
678 DECLARED_ACCESSOR_DESCRIPTOR_TYPE,
679 DECLARED_ACCESSOR_INFO_TYPE,
680 EXECUTABLE_ACCESSOR_INFO_TYPE,
682 ACCESS_CHECK_INFO_TYPE,
683 INTERCEPTOR_INFO_TYPE,
684 CALL_HANDLER_INFO_TYPE,
685 FUNCTION_TEMPLATE_INFO_TYPE,
686 OBJECT_TEMPLATE_INFO_TYPE,
688 TYPE_SWITCH_INFO_TYPE,
689 ALLOCATION_SITE_TYPE,
690 ALLOCATION_MEMENTO_TYPE,
693 POLYMORPHIC_CODE_CACHE_TYPE,
694 TYPE_FEEDBACK_INFO_TYPE,
695 ALIASED_ARGUMENTS_ENTRY_TYPE,
698 BREAK_POINT_INFO_TYPE,
700 SHARED_FUNCTION_INFO_TYPE,
705 SLOPPY_BLOCK_WITH_EVAL_CONTEXT_EXTENSION_TYPE,
707 // All the following types are subtypes of JSReceiver, which corresponds to
708 // objects in the JS sense. The first and the last type in this range are
709 // the two forms of function. This organization enables using the same
710 // compares for checking the JS_RECEIVER/SPEC_OBJECT range and the
711 // NONCALLABLE_JS_OBJECT range.
712 JS_FUNCTION_PROXY_TYPE, // FIRST_JS_RECEIVER_TYPE, FIRST_JS_PROXY_TYPE
713 JS_PROXY_TYPE, // LAST_JS_PROXY_TYPE
714 JS_VALUE_TYPE, // FIRST_JS_OBJECT_TYPE
715 JS_MESSAGE_OBJECT_TYPE,
718 JS_CONTEXT_EXTENSION_OBJECT_TYPE,
719 JS_GENERATOR_OBJECT_TYPE,
721 JS_GLOBAL_OBJECT_TYPE,
722 JS_BUILTINS_OBJECT_TYPE,
723 JS_GLOBAL_PROXY_TYPE,
725 JS_ARRAY_BUFFER_TYPE,
730 JS_SET_ITERATOR_TYPE,
731 JS_MAP_ITERATOR_TYPE,
735 JS_FUNCTION_TYPE, // LAST_JS_OBJECT_TYPE, LAST_JS_RECEIVER_TYPE
739 LAST_TYPE = JS_FUNCTION_TYPE,
740 FIRST_NAME_TYPE = FIRST_TYPE,
741 LAST_NAME_TYPE = SYMBOL_TYPE,
742 FIRST_UNIQUE_NAME_TYPE = INTERNALIZED_STRING_TYPE,
743 LAST_UNIQUE_NAME_TYPE = SYMBOL_TYPE,
744 FIRST_NONSTRING_TYPE = SYMBOL_TYPE,
745 FIRST_PRIMITIVE_TYPE = FIRST_NAME_TYPE,
746 LAST_PRIMITIVE_TYPE = ODDBALL_TYPE,
747 // Boundaries for testing for a fixed typed array.
748 FIRST_FIXED_TYPED_ARRAY_TYPE = FIXED_INT8_ARRAY_TYPE,
749 LAST_FIXED_TYPED_ARRAY_TYPE = FIXED_UINT8_CLAMPED_ARRAY_TYPE,
750 // Boundary for promotion to old space.
751 LAST_DATA_TYPE = FILLER_TYPE,
752 // Boundary for objects represented as JSReceiver (i.e. JSObject or JSProxy).
753 // Note that there is no range for JSObject or JSProxy, since their subtypes
754 // are not continuous in this enum! The enum ranges instead reflect the
755 // external class names, where proxies are treated as either ordinary objects,
757 FIRST_JS_RECEIVER_TYPE = JS_FUNCTION_PROXY_TYPE,
758 LAST_JS_RECEIVER_TYPE = LAST_TYPE,
759 // Boundaries for testing the types represented as JSObject
760 FIRST_JS_OBJECT_TYPE = JS_VALUE_TYPE,
761 LAST_JS_OBJECT_TYPE = LAST_TYPE,
762 // Boundaries for testing the types represented as JSProxy
763 FIRST_JS_PROXY_TYPE = JS_FUNCTION_PROXY_TYPE,
764 LAST_JS_PROXY_TYPE = JS_PROXY_TYPE,
765 // Boundaries for testing whether the type is a JavaScript object.
766 FIRST_SPEC_OBJECT_TYPE = FIRST_JS_RECEIVER_TYPE,
767 LAST_SPEC_OBJECT_TYPE = LAST_JS_RECEIVER_TYPE,
768 // Boundaries for testing the types for which typeof is "object".
769 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_PROXY_TYPE,
770 LAST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_REGEXP_TYPE,
771 // Note that the types for which typeof is "function" are not continuous.
772 // Define this so that we can put assertions on discrete checks.
773 NUM_OF_CALLABLE_SPEC_OBJECT_TYPES = 2
776 STATIC_ASSERT(JS_OBJECT_TYPE == Internals::kJSObjectType);
777 STATIC_ASSERT(FIRST_NONSTRING_TYPE == Internals::kFirstNonstringType);
778 STATIC_ASSERT(ODDBALL_TYPE == Internals::kOddballType);
779 STATIC_ASSERT(FOREIGN_TYPE == Internals::kForeignType);
782 #define FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(V) \
783 V(FAST_ELEMENTS_SUB_TYPE) \
784 V(DICTIONARY_ELEMENTS_SUB_TYPE) \
785 V(FAST_PROPERTIES_SUB_TYPE) \
786 V(DICTIONARY_PROPERTIES_SUB_TYPE) \
787 V(MAP_CODE_CACHE_SUB_TYPE) \
788 V(SCOPE_INFO_SUB_TYPE) \
789 V(STRING_TABLE_SUB_TYPE) \
790 V(DESCRIPTOR_ARRAY_SUB_TYPE) \
791 V(TRANSITION_ARRAY_SUB_TYPE)
793 enum FixedArraySubInstanceType {
794 #define DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE(name) name,
795 FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE)
796 #undef DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE
797 LAST_FIXED_ARRAY_SUB_TYPE = TRANSITION_ARRAY_SUB_TYPE
810 #define DECL_BOOLEAN_ACCESSORS(name) \
811 inline bool name() const; \
812 inline void set_##name(bool value); \
815 #define DECL_ACCESSORS(name, type) \
816 inline type* name() const; \
817 inline void set_##name(type* value, \
818 WriteBarrierMode mode = UPDATE_WRITE_BARRIER); \
821 #define DECLARE_CAST(type) \
822 INLINE(static type* cast(Object* object)); \
823 INLINE(static const type* cast(const Object* object));
827 class AllocationSite;
828 class AllocationSiteCreationContext;
829 class AllocationSiteUsageContext;
832 class ElementsAccessor;
833 class FixedArrayBase;
834 class FunctionLiteral;
836 class JSBuiltinsObject;
837 class LayoutDescriptor;
838 class LookupIterator;
839 class ObjectHashTable;
842 class SafepointEntry;
843 class SharedFunctionInfo;
845 class TypeFeedbackInfo;
846 class TypeFeedbackVector;
849 // We cannot just say "class HeapType;" if it is created from a template... =8-?
850 template<class> class TypeImpl;
851 struct HeapTypeConfig;
852 typedef TypeImpl<HeapTypeConfig> HeapType;
855 // A template-ized version of the IsXXX functions.
856 template <class C> inline bool Is(Object* obj);
859 #define DECLARE_VERIFIER(Name) void Name##Verify();
861 #define DECLARE_VERIFIER(Name)
865 #define DECLARE_PRINTER(Name) void Name##Print(std::ostream& os); // NOLINT
867 #define DECLARE_PRINTER(Name)
871 #define OBJECT_TYPE_LIST(V) \
876 #define HEAP_OBJECT_TYPE_LIST(V) \
878 V(MutableHeapNumber) \
897 V(ExternalTwoByteString) \
898 V(ExternalOneByteString) \
899 V(SeqTwoByteString) \
900 V(SeqOneByteString) \
901 V(InternalizedString) \
904 V(FixedTypedArrayBase) \
907 V(FixedUint16Array) \
909 V(FixedUint32Array) \
911 V(FixedFloat32Array) \
912 V(FixedFloat64Array) \
913 V(FixedUint8ClampedArray) \
919 V(JSContextExtensionObject) \
920 V(JSGeneratorObject) \
922 V(LayoutDescriptor) \
926 V(TypeFeedbackVector) \
927 V(DeoptimizationInputData) \
928 V(DeoptimizationOutputData) \
932 V(FixedDoubleArray) \
936 V(ScriptContextTable) \
942 V(SharedFunctionInfo) \
951 V(JSArrayBufferView) \
960 V(JSWeakCollection) \
967 V(NormalizedMapCache) \
968 V(CompilationCacheTable) \
969 V(CodeCacheHashTable) \
970 V(PolymorphicCodeCacheHashTable) \
975 V(JSBuiltinsObject) \
977 V(UndetectableObject) \
978 V(AccessCheckNeeded) \
986 // Object is the abstract superclass for all classes in the
988 // Object does not use any virtual functions to avoid the
989 // allocation of the C++ vtable.
990 // Since both Smi and HeapObject are subclasses of Object no
991 // data members can be present in Object.
995 bool IsObject() const { return true; }
997 #define IS_TYPE_FUNCTION_DECL(type_) INLINE(bool Is##type_() const);
998 OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
999 HEAP_OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1000 #undef IS_TYPE_FUNCTION_DECL
1002 // A non-keyed store is of the form a.x = foo or a["x"] = foo whereas
1003 // a keyed store is of the form a[expression] = foo.
1004 enum StoreFromKeyed {
1005 MAY_BE_STORE_FROM_KEYED,
1006 CERTAINLY_NOT_STORE_FROM_KEYED
1009 INLINE(bool IsFixedArrayBase() const);
1010 INLINE(bool IsExternal() const);
1011 INLINE(bool IsAccessorInfo() const);
1013 INLINE(bool IsStruct() const);
1014 #define DECLARE_STRUCT_PREDICATE(NAME, Name, name) \
1015 INLINE(bool Is##Name() const);
1016 STRUCT_LIST(DECLARE_STRUCT_PREDICATE)
1017 #undef DECLARE_STRUCT_PREDICATE
1019 // ES6, section 7.2.3 IsCallable.
1020 INLINE(bool IsCallable() const);
1022 INLINE(bool IsSpecObject()) const;
1023 // TODO(rossberg): IsSpecFunction should be removed in favor of IsCallable.
1024 INLINE(bool IsSpecFunction()) const;
1025 INLINE(bool IsTemplateInfo()) const;
1026 INLINE(bool IsNameDictionary() const);
1027 INLINE(bool IsGlobalDictionary() const);
1028 INLINE(bool IsSeededNumberDictionary() const);
1029 INLINE(bool IsUnseededNumberDictionary() const);
1030 INLINE(bool IsOrderedHashSet() const);
1031 INLINE(bool IsOrderedHashMap() const);
1032 static bool IsPromise(Handle<Object> object);
1035 INLINE(bool IsUndefined() const);
1036 INLINE(bool IsNull() const);
1037 INLINE(bool IsTheHole() const);
1038 INLINE(bool IsException() const);
1039 INLINE(bool IsUninitialized() const);
1040 INLINE(bool IsTrue() const);
1041 INLINE(bool IsFalse() const);
1042 INLINE(bool IsArgumentsMarker() const);
1044 // Filler objects (fillers and free space objects).
1045 INLINE(bool IsFiller() const);
1047 // Extract the number.
1048 inline double Number();
1049 INLINE(bool IsNaN() const);
1050 INLINE(bool IsMinusZero() const);
1051 bool ToInt32(int32_t* value);
1052 bool ToUint32(uint32_t* value);
1054 inline Representation OptimalRepresentation();
1056 inline ElementsKind OptimalElementsKind();
1058 inline bool FitsRepresentation(Representation representation);
1060 // Checks whether two valid primitive encodings of a property name resolve to
1061 // the same logical property. E.g., the smi 1, the string "1" and the double
1062 // 1 all refer to the same property, so this helper will return true.
1063 inline bool KeyEquals(Object* other);
1065 Handle<HeapType> OptimalType(Isolate* isolate, Representation representation);
1067 inline static Handle<Object> NewStorageFor(Isolate* isolate,
1068 Handle<Object> object,
1069 Representation representation);
1071 inline static Handle<Object> WrapForRead(Isolate* isolate,
1072 Handle<Object> object,
1073 Representation representation);
1075 // Returns true if the object is of the correct type to be used as a
1076 // implementation of a JSObject's elements.
1077 inline bool HasValidElements();
1079 inline bool HasSpecificClassOf(String* name);
1081 bool BooleanValue(); // ECMA-262 9.2.
1083 // ES6 section 7.2.13 Strict Equality Comparison
1084 bool StrictEquals(Object* that);
1086 // Convert to a JSObject if needed.
1087 // native_context is used when creating wrapper object.
1088 static inline MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1089 Handle<Object> object);
1090 MUST_USE_RESULT static MaybeHandle<JSReceiver> ToObject(
1091 Isolate* isolate, Handle<Object> object, Handle<Context> context);
1093 // ES6 section 7.1.14 ToPropertyKey
1094 MUST_USE_RESULT static inline MaybeHandle<Name> ToName(Isolate* isolate,
1095 Handle<Object> input);
1097 // ES6 section 7.1.1 ToPrimitive
1098 MUST_USE_RESULT static inline MaybeHandle<Object> ToPrimitive(
1099 Handle<Object> input, ToPrimitiveHint hint = ToPrimitiveHint::kDefault);
1101 // ES6 section 7.1.3 ToNumber
1102 MUST_USE_RESULT static MaybeHandle<Object> ToNumber(Isolate* isolate,
1103 Handle<Object> input);
1105 // ES6 section 7.1.12 ToString
1106 MUST_USE_RESULT static MaybeHandle<String> ToString(Isolate* isolate,
1107 Handle<Object> input);
1109 // ES6 section 7.3.9 GetMethod
1110 MUST_USE_RESULT static MaybeHandle<Object> GetMethod(
1111 Handle<JSReceiver> receiver, Handle<Name> name);
1113 // ES6 section 12.5.6 The typeof Operator
1114 static Handle<String> TypeOf(Isolate* isolate, Handle<Object> object);
1116 MUST_USE_RESULT static MaybeHandle<Object> GetProperty(
1117 LookupIterator* it, LanguageMode language_mode = SLOPPY);
1119 // Implementation of [[Put]], ECMA-262 5th edition, section 8.12.5.
1120 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1121 Handle<Object> object, Handle<Name> name, Handle<Object> value,
1122 LanguageMode language_mode,
1123 StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
1125 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1126 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1127 StoreFromKeyed store_mode);
1129 MUST_USE_RESULT static MaybeHandle<Object> SetSuperProperty(
1130 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1131 StoreFromKeyed store_mode);
1133 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1134 LookupIterator* it, LanguageMode language_mode);
1135 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1136 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1137 LanguageMode language_mode);
1138 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1139 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1140 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1141 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1142 Handle<Object> value, LanguageMode language_mode);
1143 MUST_USE_RESULT static MaybeHandle<Object> RedefineNonconfigurableProperty(
1144 Isolate* isolate, Handle<Object> name, Handle<Object> value,
1145 LanguageMode language_mode);
1146 MUST_USE_RESULT static MaybeHandle<Object> SetDataProperty(
1147 LookupIterator* it, Handle<Object> value);
1148 MUST_USE_RESULT static MaybeHandle<Object> AddDataProperty(
1149 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1150 LanguageMode language_mode, StoreFromKeyed store_mode);
1151 MUST_USE_RESULT static inline MaybeHandle<Object> GetPropertyOrElement(
1152 Handle<Object> object, Handle<Name> name,
1153 LanguageMode language_mode = SLOPPY);
1154 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1155 Isolate* isolate, Handle<Object> object, const char* key,
1156 LanguageMode language_mode = SLOPPY);
1157 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1158 Handle<Object> object, Handle<Name> name,
1159 LanguageMode language_mode = SLOPPY);
1161 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithAccessor(
1162 LookupIterator* it, LanguageMode language_mode);
1163 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithAccessor(
1164 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1166 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithDefinedGetter(
1167 Handle<Object> receiver,
1168 Handle<JSReceiver> getter);
1169 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithDefinedSetter(
1170 Handle<Object> receiver,
1171 Handle<JSReceiver> setter,
1172 Handle<Object> value);
1174 MUST_USE_RESULT static inline MaybeHandle<Object> GetElement(
1175 Isolate* isolate, Handle<Object> object, uint32_t index,
1176 LanguageMode language_mode = SLOPPY);
1178 MUST_USE_RESULT static inline MaybeHandle<Object> SetElement(
1179 Isolate* isolate, Handle<Object> object, uint32_t index,
1180 Handle<Object> value, LanguageMode language_mode);
1182 static inline Handle<Object> GetPrototypeSkipHiddenPrototypes(
1183 Isolate* isolate, Handle<Object> receiver);
1185 bool HasInPrototypeChain(Isolate* isolate, Object* object);
1187 // Returns the permanent hash code associated with this object. May return
1188 // undefined if not yet created.
1191 // Returns undefined for JSObjects, but returns the hash code for simple
1192 // objects. This avoids a double lookup in the cases where we know we will
1193 // add the hash to the JSObject if it does not already exist.
1194 Object* GetSimpleHash();
1196 // Returns the permanent hash code associated with this object depending on
1197 // the actual object type. May create and store a hash code if needed and none
1199 static Handle<Smi> GetOrCreateHash(Isolate* isolate, Handle<Object> object);
1201 // Checks whether this object has the same value as the given one. This
1202 // function is implemented according to ES5, section 9.12 and can be used
1203 // to implement the Harmony "egal" function.
1204 bool SameValue(Object* other);
1206 // Checks whether this object has the same value as the given one.
1207 // +0 and -0 are treated equal. Everything else is the same as SameValue.
1208 // This function is implemented according to ES6, section 7.2.4 and is used
1209 // by ES6 Map and Set.
1210 bool SameValueZero(Object* other);
1212 // Tries to convert an object to an array length. Returns true and sets the
1213 // output parameter if it succeeds.
1214 inline bool ToArrayLength(uint32_t* index);
1216 // Tries to convert an object to an array index. Returns true and sets the
1217 // output parameter if it succeeds. Equivalent to ToArrayLength, but does not
1218 // allow kMaxUInt32.
1219 inline bool ToArrayIndex(uint32_t* index);
1221 // Returns true if this is a JSValue containing a string and the index is
1222 // < the length of the string. Used to implement [] on strings.
1223 inline bool IsStringObjectWithCharacterAt(uint32_t index);
1225 DECLARE_VERIFIER(Object)
1227 // Verify a pointer is a valid object pointer.
1228 static void VerifyPointer(Object* p);
1231 inline void VerifyApiCallResultType();
1233 // Prints this object without details.
1234 void ShortPrint(FILE* out = stdout);
1236 // Prints this object without details to a message accumulator.
1237 void ShortPrint(StringStream* accumulator);
1239 void ShortPrint(std::ostream& os); // NOLINT
1241 DECLARE_CAST(Object)
1243 // Layout description.
1244 static const int kHeaderSize = 0; // Object does not take up any space.
1247 // For our gdb macros, we should perhaps change these in the future.
1250 // Prints this object with details.
1251 void Print(std::ostream& os); // NOLINT
1253 void Print() { ShortPrint(); }
1254 void Print(std::ostream& os) { ShortPrint(os); } // NOLINT
1258 friend class LookupIterator;
1259 friend class PrototypeIterator;
1261 // Return the map of the root of object's prototype chain.
1262 Map* GetRootMap(Isolate* isolate);
1264 // Helper for SetProperty and SetSuperProperty.
1265 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyInternal(
1266 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1267 StoreFromKeyed store_mode, bool* found);
1269 DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
1273 // In objects.h to be usable without objects-inl.h inclusion.
1274 bool Object::IsSmi() const { return HAS_SMI_TAG(this); }
1275 bool Object::IsHeapObject() const { return Internals::HasHeapObjectTag(this); }
1279 explicit Brief(const Object* const v) : value(v) {}
1280 const Object* value;
1284 std::ostream& operator<<(std::ostream& os, const Brief& v);
1287 // Smi represents integer Numbers that can be stored in 31 bits.
1288 // Smis are immediate which means they are NOT allocated in the heap.
1289 // The this pointer has the following format: [31 bit signed int] 0
1290 // For long smis it has the following format:
1291 // [32 bit signed int] [31 bits zero padding] 0
1292 // Smi stands for small integer.
1293 class Smi: public Object {
1295 // Returns the integer value.
1296 inline int value() const { return Internals::SmiValue(this); }
1298 // Convert a value to a Smi object.
1299 static inline Smi* FromInt(int value) {
1300 DCHECK(Smi::IsValid(value));
1301 return reinterpret_cast<Smi*>(Internals::IntToSmi(value));
1304 static inline Smi* FromIntptr(intptr_t value) {
1305 DCHECK(Smi::IsValid(value));
1306 int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
1307 return reinterpret_cast<Smi*>((value << smi_shift_bits) | kSmiTag);
1310 // Returns whether value can be represented in a Smi.
1311 static inline bool IsValid(intptr_t value) {
1312 bool result = Internals::IsValidSmi(value);
1313 DCHECK_EQ(result, value >= kMinValue && value <= kMaxValue);
1319 // Dispatched behavior.
1320 void SmiPrint(std::ostream& os) const; // NOLINT
1321 DECLARE_VERIFIER(Smi)
1323 static const int kMinValue =
1324 (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1325 static const int kMaxValue = -(kMinValue + 1);
1328 DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1332 // Heap objects typically have a map pointer in their first word. However,
1333 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1334 // encoded in the first word. The class MapWord is an abstraction of the
1335 // value in a heap object's first word.
1336 class MapWord BASE_EMBEDDED {
1338 // Normal state: the map word contains a map pointer.
1340 // Create a map word from a map pointer.
1341 static inline MapWord FromMap(const Map* map);
1343 // View this map word as a map pointer.
1344 inline Map* ToMap();
1347 // Scavenge collection: the map word of live objects in the from space
1348 // contains a forwarding address (a heap object pointer in the to space).
1350 // True if this map word is a forwarding address for a scavenge
1351 // collection. Only valid during a scavenge collection (specifically,
1352 // when all map words are heap object pointers, i.e. not during a full GC).
1353 inline bool IsForwardingAddress();
1355 // Create a map word from a forwarding address.
1356 static inline MapWord FromForwardingAddress(HeapObject* object);
1358 // View this map word as a forwarding address.
1359 inline HeapObject* ToForwardingAddress();
1361 static inline MapWord FromRawValue(uintptr_t value) {
1362 return MapWord(value);
1365 inline uintptr_t ToRawValue() {
1370 // HeapObject calls the private constructor and directly reads the value.
1371 friend class HeapObject;
1373 explicit MapWord(uintptr_t value) : value_(value) {}
1379 // The content of an heap object (except for the map pointer). kTaggedValues
1380 // objects can contain both heap pointers and Smis, kMixedValues can contain
1381 // heap pointers, Smis, and raw values (e.g. doubles or strings), and kRawValues
1382 // objects can contain raw values and Smis.
1383 enum class HeapObjectContents { kTaggedValues, kMixedValues, kRawValues };
1386 // HeapObject is the superclass for all classes describing heap allocated
1388 class HeapObject: public Object {
1390 // [map]: Contains a map which contains the object's reflective
1392 inline Map* map() const;
1393 inline void set_map(Map* value);
1394 // The no-write-barrier version. This is OK if the object is white and in
1395 // new space, or if the value is an immortal immutable object, like the maps
1396 // of primitive (non-JS) objects like strings, heap numbers etc.
1397 inline void set_map_no_write_barrier(Map* value);
1399 // Get the map using acquire load.
1400 inline Map* synchronized_map();
1401 inline MapWord synchronized_map_word() const;
1403 // Set the map using release store
1404 inline void synchronized_set_map(Map* value);
1405 inline void synchronized_set_map_no_write_barrier(Map* value);
1406 inline void synchronized_set_map_word(MapWord map_word);
1408 // During garbage collection, the map word of a heap object does not
1409 // necessarily contain a map pointer.
1410 inline MapWord map_word() const;
1411 inline void set_map_word(MapWord map_word);
1413 // The Heap the object was allocated in. Used also to access Isolate.
1414 inline Heap* GetHeap() const;
1416 // Convenience method to get current isolate.
1417 inline Isolate* GetIsolate() const;
1419 // Converts an address to a HeapObject pointer.
1420 static inline HeapObject* FromAddress(Address address) {
1421 DCHECK_TAG_ALIGNED(address);
1422 return reinterpret_cast<HeapObject*>(address + kHeapObjectTag);
1425 // Returns the address of this HeapObject.
1426 inline Address address() {
1427 return reinterpret_cast<Address>(this) - kHeapObjectTag;
1430 // Iterates over pointers contained in the object (including the Map)
1431 void Iterate(ObjectVisitor* v);
1433 // Iterates over all pointers contained in the object except the
1434 // first map pointer. The object type is given in the first
1435 // parameter. This function does not access the map pointer in the
1436 // object, and so is safe to call while the map pointer is modified.
1437 void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1439 // Returns the heap object's size in bytes
1442 // Indicates what type of values this heap object may contain.
1443 inline HeapObjectContents ContentType();
1445 // Given a heap object's map pointer, returns the heap size in bytes
1446 // Useful when the map pointer field is used for other purposes.
1448 inline int SizeFromMap(Map* map);
1450 // Returns the field at offset in obj, as a read/write Object* reference.
1451 // Does no checking, and is safe to use during GC, while maps are invalid.
1452 // Does not invoke write barrier, so should only be assigned to
1453 // during marking GC.
1454 static inline Object** RawField(HeapObject* obj, int offset);
1456 // Adds the |code| object related to |name| to the code cache of this map. If
1457 // this map is a dictionary map that is shared, the map copied and installed
1459 static void UpdateMapCodeCache(Handle<HeapObject> object,
1463 DECLARE_CAST(HeapObject)
1465 // Return the write barrier mode for this. Callers of this function
1466 // must be able to present a reference to an DisallowHeapAllocation
1467 // object as a sign that they are not going to use this function
1468 // from code that allocates and thus invalidates the returned write
1470 inline WriteBarrierMode GetWriteBarrierMode(
1471 const DisallowHeapAllocation& promise);
1473 // Dispatched behavior.
1474 void HeapObjectShortPrint(std::ostream& os); // NOLINT
1476 void PrintHeader(std::ostream& os, const char* id); // NOLINT
1478 DECLARE_PRINTER(HeapObject)
1479 DECLARE_VERIFIER(HeapObject)
1481 inline void VerifyObjectField(int offset);
1482 inline void VerifySmiField(int offset);
1484 // Verify a pointer is a valid HeapObject pointer that points to object
1485 // areas in the heap.
1486 static void VerifyHeapPointer(Object* p);
1489 inline AllocationAlignment RequiredAlignment();
1491 // Layout description.
1492 // First field in a heap object is map.
1493 static const int kMapOffset = Object::kHeaderSize;
1494 static const int kHeaderSize = kMapOffset + kPointerSize;
1496 STATIC_ASSERT(kMapOffset == Internals::kHeapObjectMapOffset);
1499 // helpers for calling an ObjectVisitor to iterate over pointers in the
1500 // half-open range [start, end) specified as integer offsets
1501 inline void IteratePointers(ObjectVisitor* v, int start, int end);
1502 // as above, for the single element at "offset"
1503 inline void IteratePointer(ObjectVisitor* v, int offset);
1504 // as above, for the next code link of a code object.
1505 inline void IterateNextCodeLink(ObjectVisitor* v, int offset);
1508 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1512 // This class describes a body of an object of a fixed size
1513 // in which all pointer fields are located in the [start_offset, end_offset)
1515 template<int start_offset, int end_offset, int size>
1516 class FixedBodyDescriptor {
1518 static const int kStartOffset = start_offset;
1519 static const int kEndOffset = end_offset;
1520 static const int kSize = size;
1522 static inline void IterateBody(HeapObject* obj, ObjectVisitor* v);
1524 template<typename StaticVisitor>
1525 static inline void IterateBody(HeapObject* obj) {
1526 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1527 HeapObject::RawField(obj, end_offset));
1532 // This class describes a body of an object of a variable size
1533 // in which all pointer fields are located in the [start_offset, object_size)
1535 template<int start_offset>
1536 class FlexibleBodyDescriptor {
1538 static const int kStartOffset = start_offset;
1540 static inline void IterateBody(HeapObject* obj,
1544 template<typename StaticVisitor>
1545 static inline void IterateBody(HeapObject* obj, int object_size) {
1546 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1547 HeapObject::RawField(obj, object_size));
1552 // The HeapNumber class describes heap allocated numbers that cannot be
1553 // represented in a Smi (small integer)
1554 class HeapNumber: public HeapObject {
1556 // [value]: number value.
1557 inline double value() const;
1558 inline void set_value(double value);
1560 DECLARE_CAST(HeapNumber)
1562 // Dispatched behavior.
1563 bool HeapNumberBooleanValue();
1565 void HeapNumberPrint(std::ostream& os); // NOLINT
1566 DECLARE_VERIFIER(HeapNumber)
1568 inline int get_exponent();
1569 inline int get_sign();
1571 // Layout description.
1572 static const int kValueOffset = HeapObject::kHeaderSize;
1573 // IEEE doubles are two 32 bit words. The first is just mantissa, the second
1574 // is a mixture of sign, exponent and mantissa. The offsets of two 32 bit
1575 // words within double numbers are endian dependent and they are set
1577 #if defined(V8_TARGET_LITTLE_ENDIAN)
1578 static const int kMantissaOffset = kValueOffset;
1579 static const int kExponentOffset = kValueOffset + 4;
1580 #elif defined(V8_TARGET_BIG_ENDIAN)
1581 static const int kMantissaOffset = kValueOffset + 4;
1582 static const int kExponentOffset = kValueOffset;
1584 #error Unknown byte ordering
1587 static const int kSize = kValueOffset + kDoubleSize;
1588 static const uint32_t kSignMask = 0x80000000u;
1589 static const uint32_t kExponentMask = 0x7ff00000u;
1590 static const uint32_t kMantissaMask = 0xfffffu;
1591 static const int kMantissaBits = 52;
1592 static const int kExponentBits = 11;
1593 static const int kExponentBias = 1023;
1594 static const int kExponentShift = 20;
1595 static const int kInfinityOrNanExponent =
1596 (kExponentMask >> kExponentShift) - kExponentBias;
1597 static const int kMantissaBitsInTopWord = 20;
1598 static const int kNonMantissaBitsInTopWord = 12;
1601 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
1605 // The Simd128Value class describes heap allocated 128 bit SIMD values.
1606 class Simd128Value : public HeapObject {
1608 DECLARE_CAST(Simd128Value)
1610 DECLARE_PRINTER(Simd128Value)
1611 DECLARE_VERIFIER(Simd128Value)
1613 static Handle<String> ToString(Handle<Simd128Value> input);
1615 // Equality operations.
1616 inline bool Equals(Simd128Value* that);
1618 // Checks that another instance is bit-wise equal.
1619 bool BitwiseEquals(const Simd128Value* other) const;
1620 // Computes a hash from the 128 bit value, viewed as 4 32-bit integers.
1621 uint32_t Hash() const;
1622 // Copies the 16 bytes of SIMD data to the destination address.
1623 void CopyBits(void* destination) const;
1625 // Layout description.
1626 static const int kValueOffset = HeapObject::kHeaderSize;
1627 static const int kSize = kValueOffset + kSimd128Size;
1630 DISALLOW_IMPLICIT_CONSTRUCTORS(Simd128Value);
1634 // V has parameters (TYPE, Type, type, lane count, lane type)
1635 #define SIMD128_TYPES(V) \
1636 V(FLOAT32X4, Float32x4, float32x4, 4, float) \
1637 V(INT32X4, Int32x4, int32x4, 4, int32_t) \
1638 V(UINT32X4, Uint32x4, uint32x4, 4, uint32_t) \
1639 V(BOOL32X4, Bool32x4, bool32x4, 4, bool) \
1640 V(INT16X8, Int16x8, int16x8, 8, int16_t) \
1641 V(UINT16X8, Uint16x8, uint16x8, 8, uint16_t) \
1642 V(BOOL16X8, Bool16x8, bool16x8, 8, bool) \
1643 V(INT8X16, Int8x16, int8x16, 16, int8_t) \
1644 V(UINT8X16, Uint8x16, uint8x16, 16, uint8_t) \
1645 V(BOOL8X16, Bool8x16, bool8x16, 16, bool)
1647 #define SIMD128_VALUE_CLASS(TYPE, Type, type, lane_count, lane_type) \
1648 class Type final : public Simd128Value { \
1650 inline lane_type get_lane(int lane) const; \
1651 inline void set_lane(int lane, lane_type value); \
1653 DECLARE_CAST(Type) \
1655 DECLARE_PRINTER(Type) \
1657 static Handle<String> ToString(Handle<Type> input); \
1659 inline bool Equals(Type* that); \
1662 DISALLOW_IMPLICIT_CONSTRUCTORS(Type); \
1664 SIMD128_TYPES(SIMD128_VALUE_CLASS)
1665 #undef SIMD128_VALUE_CLASS
1668 enum EnsureElementsMode {
1669 DONT_ALLOW_DOUBLE_ELEMENTS,
1670 ALLOW_COPIED_DOUBLE_ELEMENTS,
1671 ALLOW_CONVERTED_DOUBLE_ELEMENTS
1675 // Indicator for one component of an AccessorPair.
1676 enum AccessorComponent {
1682 // JSReceiver includes types on which properties can be defined, i.e.,
1683 // JSObject and JSProxy.
1684 class JSReceiver: public HeapObject {
1686 DECLARE_CAST(JSReceiver)
1688 // ES6 section 7.1.1 ToPrimitive
1689 MUST_USE_RESULT static MaybeHandle<Object> ToPrimitive(
1690 Handle<JSReceiver> receiver,
1691 ToPrimitiveHint hint = ToPrimitiveHint::kDefault);
1692 MUST_USE_RESULT static MaybeHandle<Object> OrdinaryToPrimitive(
1693 Handle<JSReceiver> receiver, OrdinaryToPrimitiveHint hint);
1695 // Implementation of [[HasProperty]], ECMA-262 5th edition, section 8.12.6.
1696 MUST_USE_RESULT static inline Maybe<bool> HasProperty(
1697 Handle<JSReceiver> object, Handle<Name> name);
1698 MUST_USE_RESULT static inline Maybe<bool> HasOwnProperty(Handle<JSReceiver>,
1700 MUST_USE_RESULT static inline Maybe<bool> HasElement(
1701 Handle<JSReceiver> object, uint32_t index);
1702 MUST_USE_RESULT static inline Maybe<bool> HasOwnElement(
1703 Handle<JSReceiver> object, uint32_t index);
1705 // Implementation of [[Delete]], ECMA-262 5th edition, section 8.12.7.
1706 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyOrElement(
1707 Handle<JSReceiver> object, Handle<Name> name,
1708 LanguageMode language_mode = SLOPPY);
1709 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1710 Handle<JSReceiver> object, Handle<Name> name,
1711 LanguageMode language_mode = SLOPPY);
1712 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1713 LookupIterator* it, LanguageMode language_mode);
1714 MUST_USE_RESULT static MaybeHandle<Object> DeleteElement(
1715 Handle<JSReceiver> object, uint32_t index,
1716 LanguageMode language_mode = SLOPPY);
1718 // Tests for the fast common case for property enumeration.
1719 bool IsSimpleEnum();
1721 // Returns the class name ([[Class]] property in the specification).
1722 String* class_name();
1724 // Returns the constructor name (the name (possibly, inferred name) of the
1725 // function that was used to instantiate the object).
1726 String* constructor_name();
1728 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetPropertyAttributes(
1729 Handle<JSReceiver> object, Handle<Name> name);
1730 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1731 GetOwnPropertyAttributes(Handle<JSReceiver> object, Handle<Name> name);
1733 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetElementAttributes(
1734 Handle<JSReceiver> object, uint32_t index);
1735 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1736 GetOwnElementAttributes(Handle<JSReceiver> object, uint32_t index);
1738 MUST_USE_RESULT static Maybe<PropertyAttributes> GetPropertyAttributes(
1739 LookupIterator* it);
1742 static Handle<Object> GetDataProperty(Handle<JSReceiver> object,
1744 static Handle<Object> GetDataProperty(LookupIterator* it);
1747 // Retrieves a permanent object identity hash code. The undefined value might
1748 // be returned in case no hash was created yet.
1749 inline Object* GetIdentityHash();
1751 // Retrieves a permanent object identity hash code. May create and store a
1752 // hash code if needed and none exists.
1753 inline static Handle<Smi> GetOrCreateIdentityHash(
1754 Handle<JSReceiver> object);
1756 enum KeyCollectionType { OWN_ONLY, INCLUDE_PROTOS };
1758 // Computes the enumerable keys for a JSObject. Used for implementing
1759 // "for (n in object) { }".
1760 MUST_USE_RESULT static MaybeHandle<FixedArray> GetKeys(
1761 Handle<JSReceiver> object,
1762 KeyCollectionType type);
1765 DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
1769 // The JSObject describes real heap allocated JavaScript objects with
1771 // Note that the map of JSObject changes during execution to enable inline
1773 class JSObject: public JSReceiver {
1775 // [properties]: Backing storage for properties.
1776 // properties is a FixedArray in the fast case and a Dictionary in the
1778 DECL_ACCESSORS(properties, FixedArray) // Get and set fast properties.
1779 inline void initialize_properties();
1780 inline bool HasFastProperties();
1781 // Gets slow properties for non-global objects.
1782 inline NameDictionary* property_dictionary();
1783 // Gets global object properties.
1784 inline GlobalDictionary* global_dictionary();
1786 // [elements]: The elements (properties with names that are integers).
1788 // Elements can be in two general modes: fast and slow. Each mode
1789 // corrensponds to a set of object representations of elements that
1790 // have something in common.
1792 // In the fast mode elements is a FixedArray and so each element can
1793 // be quickly accessed. This fact is used in the generated code. The
1794 // elements array can have one of three maps in this mode:
1795 // fixed_array_map, sloppy_arguments_elements_map or
1796 // fixed_cow_array_map (for copy-on-write arrays). In the latter case
1797 // the elements array may be shared by a few objects and so before
1798 // writing to any element the array must be copied. Use
1799 // EnsureWritableFastElements in this case.
1801 // In the slow mode the elements is either a NumberDictionary, a
1802 // FixedArray parameter map for a (sloppy) arguments object.
1803 DECL_ACCESSORS(elements, FixedArrayBase)
1804 inline void initialize_elements();
1805 static void ResetElements(Handle<JSObject> object);
1806 static inline void SetMapAndElements(Handle<JSObject> object,
1808 Handle<FixedArrayBase> elements);
1809 inline ElementsKind GetElementsKind();
1810 ElementsAccessor* GetElementsAccessor();
1811 // Returns true if an object has elements of FAST_SMI_ELEMENTS ElementsKind.
1812 inline bool HasFastSmiElements();
1813 // Returns true if an object has elements of FAST_ELEMENTS ElementsKind.
1814 inline bool HasFastObjectElements();
1815 // Returns true if an object has elements of FAST_ELEMENTS or
1816 // FAST_SMI_ONLY_ELEMENTS.
1817 inline bool HasFastSmiOrObjectElements();
1818 // Returns true if an object has any of the fast elements kinds.
1819 inline bool HasFastElements();
1820 // Returns true if an object has elements of FAST_DOUBLE_ELEMENTS
1822 inline bool HasFastDoubleElements();
1823 // Returns true if an object has elements of FAST_HOLEY_*_ELEMENTS
1825 inline bool HasFastHoleyElements();
1826 inline bool HasSloppyArgumentsElements();
1827 inline bool HasDictionaryElements();
1829 inline bool HasFixedTypedArrayElements();
1831 inline bool HasFixedUint8ClampedElements();
1832 inline bool HasFixedArrayElements();
1833 inline bool HasFixedInt8Elements();
1834 inline bool HasFixedUint8Elements();
1835 inline bool HasFixedInt16Elements();
1836 inline bool HasFixedUint16Elements();
1837 inline bool HasFixedInt32Elements();
1838 inline bool HasFixedUint32Elements();
1839 inline bool HasFixedFloat32Elements();
1840 inline bool HasFixedFloat64Elements();
1842 inline bool HasFastArgumentsElements();
1843 inline bool HasSlowArgumentsElements();
1844 inline SeededNumberDictionary* element_dictionary(); // Gets slow elements.
1846 // Requires: HasFastElements().
1847 static Handle<FixedArray> EnsureWritableFastElements(
1848 Handle<JSObject> object);
1850 // Collects elements starting at index 0.
1851 // Undefined values are placed after non-undefined values.
1852 // Returns the number of non-undefined values.
1853 static Handle<Object> PrepareElementsForSort(Handle<JSObject> object,
1855 // As PrepareElementsForSort, but only on objects where elements is
1856 // a dictionary, and it will stay a dictionary. Collates undefined and
1857 // unexisting elements below limit from position zero of the elements.
1858 static Handle<Object> PrepareSlowElementsForSort(Handle<JSObject> object,
1861 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithInterceptor(
1862 LookupIterator* it, Handle<Object> value);
1864 // SetLocalPropertyIgnoreAttributes converts callbacks to fields. We need to
1865 // grant an exemption to ExecutableAccessor callbacks in some cases.
1866 enum ExecutableAccessorInfoHandling { DEFAULT_HANDLING, DONT_FORCE_FIELD };
1868 MUST_USE_RESULT static MaybeHandle<Object> DefineOwnPropertyIgnoreAttributes(
1869 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1870 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1872 MUST_USE_RESULT static MaybeHandle<Object> SetOwnPropertyIgnoreAttributes(
1873 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1874 PropertyAttributes attributes,
1875 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1877 MUST_USE_RESULT static MaybeHandle<Object> SetOwnElementIgnoreAttributes(
1878 Handle<JSObject> object, uint32_t index, Handle<Object> value,
1879 PropertyAttributes attributes,
1880 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1882 // Equivalent to one of the above depending on whether |name| can be converted
1883 // to an array index.
1884 MUST_USE_RESULT static MaybeHandle<Object>
1885 DefinePropertyOrElementIgnoreAttributes(
1886 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1887 PropertyAttributes attributes = NONE,
1888 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1890 // Adds or reconfigures a property to attributes NONE. It will fail when it
1892 MUST_USE_RESULT static Maybe<bool> CreateDataProperty(LookupIterator* it,
1893 Handle<Object> value);
1895 static void AddProperty(Handle<JSObject> object, Handle<Name> name,
1896 Handle<Object> value, PropertyAttributes attributes);
1898 MUST_USE_RESULT static MaybeHandle<Object> AddDataElement(
1899 Handle<JSObject> receiver, uint32_t index, Handle<Object> value,
1900 PropertyAttributes attributes);
1902 // Extend the receiver with a single fast property appeared first in the
1903 // passed map. This also extends the property backing store if necessary.
1904 static void AllocateStorageForMap(Handle<JSObject> object, Handle<Map> map);
1906 // Migrates the given object to a map whose field representations are the
1907 // lowest upper bound of all known representations for that field.
1908 static void MigrateInstance(Handle<JSObject> instance);
1910 // Migrates the given object only if the target map is already available,
1911 // or returns false if such a map is not yet available.
1912 static bool TryMigrateInstance(Handle<JSObject> instance);
1914 // Sets the property value in a normalized object given (key, value, details).
1915 // Handles the special representation of JS global objects.
1916 static void SetNormalizedProperty(Handle<JSObject> object, Handle<Name> name,
1917 Handle<Object> value,
1918 PropertyDetails details);
1919 static void SetDictionaryElement(Handle<JSObject> object, uint32_t index,
1920 Handle<Object> value,
1921 PropertyAttributes attributes);
1922 static void SetDictionaryArgumentsElement(Handle<JSObject> object,
1924 Handle<Object> value,
1925 PropertyAttributes attributes);
1927 static void OptimizeAsPrototype(Handle<JSObject> object,
1928 PrototypeOptimizationMode mode);
1929 static void ReoptimizeIfPrototype(Handle<JSObject> object);
1930 static void LazyRegisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1931 static bool UnregisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1932 static void InvalidatePrototypeChains(Map* map);
1934 // Alternative implementation of WeakFixedArray::NullCallback.
1935 class PrototypeRegistryCompactionCallback {
1937 static void Callback(Object* value, int old_index, int new_index);
1940 // Retrieve interceptors.
1941 InterceptorInfo* GetNamedInterceptor();
1942 InterceptorInfo* GetIndexedInterceptor();
1944 // Used from JSReceiver.
1945 MUST_USE_RESULT static Maybe<PropertyAttributes>
1946 GetPropertyAttributesWithInterceptor(LookupIterator* it);
1947 MUST_USE_RESULT static Maybe<PropertyAttributes>
1948 GetPropertyAttributesWithFailedAccessCheck(LookupIterator* it);
1950 // Retrieves an AccessorPair property from the given object. Might return
1951 // undefined if the property doesn't exist or is of a different kind.
1952 MUST_USE_RESULT static MaybeHandle<Object> GetAccessor(
1953 Handle<JSObject> object,
1955 AccessorComponent component);
1957 // Defines an AccessorPair property on the given object.
1958 // TODO(mstarzinger): Rename to SetAccessor().
1959 static MaybeHandle<Object> DefineAccessor(Handle<JSObject> object,
1961 Handle<Object> getter,
1962 Handle<Object> setter,
1963 PropertyAttributes attributes);
1965 // Defines an AccessorInfo property on the given object.
1966 MUST_USE_RESULT static MaybeHandle<Object> SetAccessor(
1967 Handle<JSObject> object,
1968 Handle<AccessorInfo> info);
1970 // The result must be checked first for exceptions. If there's no exception,
1971 // the output parameter |done| indicates whether the interceptor has a result
1973 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithInterceptor(
1974 LookupIterator* it, bool* done);
1976 // Accessors for hidden properties object.
1978 // Hidden properties are not own properties of the object itself.
1979 // Instead they are stored in an auxiliary structure kept as an own
1980 // property with a special name Heap::hidden_string(). But if the
1981 // receiver is a JSGlobalProxy then the auxiliary object is a property
1982 // of its prototype, and if it's a detached proxy, then you can't have
1983 // hidden properties.
1985 // Sets a hidden property on this object. Returns this object if successful,
1986 // undefined if called on a detached proxy.
1987 static Handle<Object> SetHiddenProperty(Handle<JSObject> object,
1989 Handle<Object> value);
1990 // Gets the value of a hidden property with the given key. Returns the hole
1991 // if the property doesn't exist (or if called on a detached proxy),
1992 // otherwise returns the value set for the key.
1993 Object* GetHiddenProperty(Handle<Name> key);
1994 // Deletes a hidden property. Deleting a non-existing property is
1995 // considered successful.
1996 static void DeleteHiddenProperty(Handle<JSObject> object,
1998 // Returns true if the object has a property with the hidden string as name.
1999 static bool HasHiddenProperties(Handle<JSObject> object);
2001 static void SetIdentityHash(Handle<JSObject> object, Handle<Smi> hash);
2003 static void ValidateElements(Handle<JSObject> object);
2005 // Makes sure that this object can contain HeapObject as elements.
2006 static inline void EnsureCanContainHeapObjectElements(Handle<JSObject> obj);
2008 // Makes sure that this object can contain the specified elements.
2009 static inline void EnsureCanContainElements(
2010 Handle<JSObject> object,
2013 EnsureElementsMode mode);
2014 static inline void EnsureCanContainElements(
2015 Handle<JSObject> object,
2016 Handle<FixedArrayBase> elements,
2018 EnsureElementsMode mode);
2019 static void EnsureCanContainElements(
2020 Handle<JSObject> object,
2021 Arguments* arguments,
2024 EnsureElementsMode mode);
2026 // Would we convert a fast elements array to dictionary mode given
2027 // an access at key?
2028 bool WouldConvertToSlowElements(uint32_t index);
2030 // Computes the new capacity when expanding the elements of a JSObject.
2031 static uint32_t NewElementsCapacity(uint32_t old_capacity) {
2032 // (old_capacity + 50%) + 16
2033 return old_capacity + (old_capacity >> 1) + 16;
2036 // These methods do not perform access checks!
2037 static void UpdateAllocationSite(Handle<JSObject> object,
2038 ElementsKind to_kind);
2040 // Lookup interceptors are used for handling properties controlled by host
2042 inline bool HasNamedInterceptor();
2043 inline bool HasIndexedInterceptor();
2045 // Computes the enumerable keys from interceptors. Used for debug mirrors and
2046 // by JSReceiver::GetKeys.
2047 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForNamedInterceptor(
2048 Handle<JSObject> object,
2049 Handle<JSReceiver> receiver);
2050 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForIndexedInterceptor(
2051 Handle<JSObject> object,
2052 Handle<JSReceiver> receiver);
2054 // Support functions for v8 api (needed for correct interceptor behavior).
2055 MUST_USE_RESULT static Maybe<bool> HasRealNamedProperty(
2056 Handle<JSObject> object, Handle<Name> name);
2057 MUST_USE_RESULT static Maybe<bool> HasRealElementProperty(
2058 Handle<JSObject> object, uint32_t index);
2059 MUST_USE_RESULT static Maybe<bool> HasRealNamedCallbackProperty(
2060 Handle<JSObject> object, Handle<Name> name);
2062 // Get the header size for a JSObject. Used to compute the index of
2063 // internal fields as well as the number of internal fields.
2064 inline int GetHeaderSize();
2066 inline int GetInternalFieldCount();
2067 inline int GetInternalFieldOffset(int index);
2068 inline Object* GetInternalField(int index);
2069 inline void SetInternalField(int index, Object* value);
2070 inline void SetInternalField(int index, Smi* value);
2072 // Returns the number of properties on this object filtering out properties
2073 // with the specified attributes (ignoring interceptors).
2074 int NumberOfOwnProperties(PropertyAttributes filter = NONE);
2075 // Fill in details for properties into storage starting at the specified
2076 // index. Returns the number of properties added.
2077 int GetOwnPropertyNames(FixedArray* storage, int index,
2078 PropertyAttributes filter = NONE);
2080 // Returns the number of properties on this object filtering out properties
2081 // with the specified attributes (ignoring interceptors).
2082 int NumberOfOwnElements(PropertyAttributes filter);
2083 // Returns the number of enumerable elements (ignoring interceptors).
2084 int NumberOfEnumElements();
2085 // Returns the number of elements on this object filtering out elements
2086 // with the specified attributes (ignoring interceptors).
2087 int GetOwnElementKeys(FixedArray* storage, PropertyAttributes filter);
2088 // Count and fill in the enumerable elements into storage.
2089 // (storage->length() == NumberOfEnumElements()).
2090 // If storage is NULL, will count the elements without adding
2091 // them to any storage.
2092 // Returns the number of enumerable elements.
2093 int GetEnumElementKeys(FixedArray* storage);
2095 static Handle<FixedArray> GetEnumPropertyKeys(Handle<JSObject> object,
2098 // Returns a new map with all transitions dropped from the object's current
2099 // map and the ElementsKind set.
2100 static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
2101 ElementsKind to_kind);
2102 static void TransitionElementsKind(Handle<JSObject> object,
2103 ElementsKind to_kind);
2105 // Always use this to migrate an object to a new map.
2106 // |expected_additional_properties| is only used for fast-to-slow transitions
2107 // and ignored otherwise.
2108 static void MigrateToMap(Handle<JSObject> object, Handle<Map> new_map,
2109 int expected_additional_properties = 0);
2111 // Convert the object to use the canonical dictionary
2112 // representation. If the object is expected to have additional properties
2113 // added this number can be indicated to have the backing store allocated to
2114 // an initial capacity for holding these properties.
2115 static void NormalizeProperties(Handle<JSObject> object,
2116 PropertyNormalizationMode mode,
2117 int expected_additional_properties,
2118 const char* reason);
2120 // Convert and update the elements backing store to be a
2121 // SeededNumberDictionary dictionary. Returns the backing after conversion.
2122 static Handle<SeededNumberDictionary> NormalizeElements(
2123 Handle<JSObject> object);
2125 void RequireSlowElements(SeededNumberDictionary* dictionary);
2127 // Transform slow named properties to fast variants.
2128 static void MigrateSlowToFast(Handle<JSObject> object,
2129 int unused_property_fields, const char* reason);
2131 inline bool IsUnboxedDoubleField(FieldIndex index);
2133 // Access fast-case object properties at index.
2134 static Handle<Object> FastPropertyAt(Handle<JSObject> object,
2135 Representation representation,
2137 inline Object* RawFastPropertyAt(FieldIndex index);
2138 inline double RawFastDoublePropertyAt(FieldIndex index);
2140 inline void FastPropertyAtPut(FieldIndex index, Object* value);
2141 inline void RawFastPropertyAtPut(FieldIndex index, Object* value);
2142 inline void RawFastDoublePropertyAtPut(FieldIndex index, double value);
2143 inline void WriteToField(int descriptor, Object* value);
2145 // Access to in object properties.
2146 inline int GetInObjectPropertyOffset(int index);
2147 inline Object* InObjectPropertyAt(int index);
2148 inline Object* InObjectPropertyAtPut(int index,
2150 WriteBarrierMode mode
2151 = UPDATE_WRITE_BARRIER);
2153 // Set the object's prototype (only JSReceiver and null are allowed values).
2154 MUST_USE_RESULT static MaybeHandle<Object> SetPrototype(
2155 Handle<JSObject> object, Handle<Object> value, bool from_javascript);
2157 // Initializes the body after properties slot, properties slot is
2158 // initialized by set_properties. Fill the pre-allocated fields with
2159 // pre_allocated_value and the rest with filler_value.
2160 // Note: this call does not update write barrier, the caller is responsible
2161 // to ensure that |filler_value| can be collected without WB here.
2162 inline void InitializeBody(Map* map,
2163 Object* pre_allocated_value,
2164 Object* filler_value);
2166 // Check whether this object references another object
2167 bool ReferencesObject(Object* obj);
2169 // Disalow further properties to be added to the oject.
2170 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensions(
2171 Handle<JSObject> object);
2173 bool IsExtensible();
2176 MUST_USE_RESULT static MaybeHandle<Object> Seal(Handle<JSObject> object);
2178 // ES5 Object.freeze
2179 MUST_USE_RESULT static MaybeHandle<Object> Freeze(Handle<JSObject> object);
2181 // Called the first time an object is observed with ES7 Object.observe.
2182 static void SetObserved(Handle<JSObject> object);
2185 enum DeepCopyHints { kNoHints = 0, kObjectIsShallow = 1 };
2187 MUST_USE_RESULT static MaybeHandle<JSObject> DeepCopy(
2188 Handle<JSObject> object,
2189 AllocationSiteUsageContext* site_context,
2190 DeepCopyHints hints = kNoHints);
2191 MUST_USE_RESULT static MaybeHandle<JSObject> DeepWalk(
2192 Handle<JSObject> object,
2193 AllocationSiteCreationContext* site_context);
2195 DECLARE_CAST(JSObject)
2197 // Dispatched behavior.
2198 void JSObjectShortPrint(StringStream* accumulator);
2199 DECLARE_PRINTER(JSObject)
2200 DECLARE_VERIFIER(JSObject)
2202 void PrintProperties(std::ostream& os); // NOLINT
2203 void PrintElements(std::ostream& os); // NOLINT
2205 #if defined(DEBUG) || defined(OBJECT_PRINT)
2206 void PrintTransitions(std::ostream& os); // NOLINT
2209 static void PrintElementsTransition(
2210 FILE* file, Handle<JSObject> object,
2211 ElementsKind from_kind, Handle<FixedArrayBase> from_elements,
2212 ElementsKind to_kind, Handle<FixedArrayBase> to_elements);
2214 void PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map);
2217 // Structure for collecting spill information about JSObjects.
2218 class SpillInformation {
2222 int number_of_objects_;
2223 int number_of_objects_with_fast_properties_;
2224 int number_of_objects_with_fast_elements_;
2225 int number_of_fast_used_fields_;
2226 int number_of_fast_unused_fields_;
2227 int number_of_slow_used_properties_;
2228 int number_of_slow_unused_properties_;
2229 int number_of_fast_used_elements_;
2230 int number_of_fast_unused_elements_;
2231 int number_of_slow_used_elements_;
2232 int number_of_slow_unused_elements_;
2235 void IncrementSpillStatistics(SpillInformation* info);
2239 // If a GC was caused while constructing this object, the elements pointer
2240 // may point to a one pointer filler map. The object won't be rooted, but
2241 // our heap verification code could stumble across it.
2242 bool ElementsAreSafeToExamine();
2245 Object* SlowReverseLookup(Object* value);
2247 // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2248 // Also maximal value of JSArray's length property.
2249 static const uint32_t kMaxElementCount = 0xffffffffu;
2251 // Constants for heuristics controlling conversion of fast elements
2252 // to slow elements.
2254 // Maximal gap that can be introduced by adding an element beyond
2255 // the current elements length.
2256 static const uint32_t kMaxGap = 1024;
2258 // Maximal length of fast elements array that won't be checked for
2259 // being dense enough on expansion.
2260 static const int kMaxUncheckedFastElementsLength = 5000;
2262 // Same as above but for old arrays. This limit is more strict. We
2263 // don't want to be wasteful with long lived objects.
2264 static const int kMaxUncheckedOldFastElementsLength = 500;
2266 // Note that Page::kMaxRegularHeapObjectSize puts a limit on
2267 // permissible values (see the DCHECK in heap.cc).
2268 static const int kInitialMaxFastElementArray = 100000;
2270 // This constant applies only to the initial map of "global.Object" and
2271 // not to arbitrary other JSObject maps.
2272 static const int kInitialGlobalObjectUnusedPropertiesCount = 4;
2274 static const int kMaxInstanceSize = 255 * kPointerSize;
2275 // When extending the backing storage for property values, we increase
2276 // its size by more than the 1 entry necessary, so sequentially adding fields
2277 // to the same object requires fewer allocations and copies.
2278 static const int kFieldsAdded = 3;
2280 // Layout description.
2281 static const int kPropertiesOffset = HeapObject::kHeaderSize;
2282 static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2283 static const int kHeaderSize = kElementsOffset + kPointerSize;
2285 STATIC_ASSERT(kHeaderSize == Internals::kJSObjectHeaderSize);
2287 class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2289 static inline int SizeOf(Map* map, HeapObject* object);
2292 Context* GetCreationContext();
2294 // Enqueue change record for Object.observe. May cause GC.
2295 MUST_USE_RESULT static MaybeHandle<Object> EnqueueChangeRecord(
2296 Handle<JSObject> object, const char* type, Handle<Name> name,
2297 Handle<Object> old_value);
2299 // Gets the number of currently used elements.
2300 int GetFastElementsUsage();
2302 // Deletes an existing named property in a normalized object.
2303 static void DeleteNormalizedProperty(Handle<JSObject> object,
2304 Handle<Name> name, int entry);
2306 static bool AllCanRead(LookupIterator* it);
2307 static bool AllCanWrite(LookupIterator* it);
2310 friend class JSReceiver;
2311 friend class Object;
2313 static void MigrateFastToFast(Handle<JSObject> object, Handle<Map> new_map);
2314 static void MigrateFastToSlow(Handle<JSObject> object,
2315 Handle<Map> new_map,
2316 int expected_additional_properties);
2318 // Used from Object::GetProperty().
2319 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithFailedAccessCheck(
2320 LookupIterator* it);
2322 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithFailedAccessCheck(
2323 LookupIterator* it, Handle<Object> value);
2325 // Add a property to a slow-case object.
2326 static void AddSlowProperty(Handle<JSObject> object,
2328 Handle<Object> value,
2329 PropertyAttributes attributes);
2331 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithInterceptor(
2332 LookupIterator* it);
2334 bool ReferencesObjectFromElements(FixedArray* elements,
2338 // Return the hash table backing store or the inline stored identity hash,
2339 // whatever is found.
2340 MUST_USE_RESULT Object* GetHiddenPropertiesHashTable();
2342 // Return the hash table backing store for hidden properties. If there is no
2343 // backing store, allocate one.
2344 static Handle<ObjectHashTable> GetOrCreateHiddenPropertiesHashtable(
2345 Handle<JSObject> object);
2347 // Set the hidden property backing store to either a hash table or
2348 // the inline-stored identity hash.
2349 static Handle<Object> SetHiddenPropertiesHashTable(
2350 Handle<JSObject> object,
2351 Handle<Object> value);
2353 MUST_USE_RESULT Object* GetIdentityHash();
2355 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSObject> object);
2357 static Handle<SeededNumberDictionary> GetNormalizedElementDictionary(
2358 Handle<JSObject> object, Handle<FixedArrayBase> elements);
2360 // Helper for fast versions of preventExtensions, seal, and freeze.
2361 // attrs is one of NONE, SEALED, or FROZEN (depending on the operation).
2362 template <PropertyAttributes attrs>
2363 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensionsWithTransition(
2364 Handle<JSObject> object);
2366 DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
2370 // Common superclass for FixedArrays that allow implementations to share
2371 // common accessors and some code paths.
2372 class FixedArrayBase: public HeapObject {
2374 // [length]: length of the array.
2375 inline int length() const;
2376 inline void set_length(int value);
2378 // Get and set the length using acquire loads and release stores.
2379 inline int synchronized_length() const;
2380 inline void synchronized_set_length(int value);
2382 DECLARE_CAST(FixedArrayBase)
2384 // Layout description.
2385 // Length is smi tagged when it is stored.
2386 static const int kLengthOffset = HeapObject::kHeaderSize;
2387 static const int kHeaderSize = kLengthOffset + kPointerSize;
2391 class FixedDoubleArray;
2392 class IncrementalMarking;
2395 // FixedArray describes fixed-sized arrays with element type Object*.
2396 class FixedArray: public FixedArrayBase {
2398 // Setter and getter for elements.
2399 inline Object* get(int index) const;
2400 static inline Handle<Object> get(Handle<FixedArray> array, int index);
2401 // Setter that uses write barrier.
2402 inline void set(int index, Object* value);
2403 inline bool is_the_hole(int index);
2405 // Setter that doesn't need write barrier.
2406 inline void set(int index, Smi* value);
2407 // Setter with explicit barrier mode.
2408 inline void set(int index, Object* value, WriteBarrierMode mode);
2410 // Setters for frequently used oddballs located in old space.
2411 inline void set_undefined(int index);
2412 inline void set_null(int index);
2413 inline void set_the_hole(int index);
2415 inline Object** GetFirstElementAddress();
2416 inline bool ContainsOnlySmisOrHoles();
2418 // Gives access to raw memory which stores the array's data.
2419 inline Object** data_start();
2421 inline void FillWithHoles(int from, int to);
2423 // Shrink length and insert filler objects.
2424 void Shrink(int length);
2426 enum KeyFilter { ALL_KEYS, NON_SYMBOL_KEYS };
2428 // Add the elements of a JSArray to this FixedArray.
2429 MUST_USE_RESULT static MaybeHandle<FixedArray> AddKeysFromArrayLike(
2430 Handle<FixedArray> content, Handle<JSObject> array,
2431 KeyFilter filter = ALL_KEYS);
2433 // Computes the union of keys and return the result.
2434 // Used for implementing "for (n in object) { }"
2435 MUST_USE_RESULT static MaybeHandle<FixedArray> UnionOfKeys(
2436 Handle<FixedArray> first,
2437 Handle<FixedArray> second);
2439 // Copy a sub array from the receiver to dest.
2440 void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
2442 // Garbage collection support.
2443 static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
2445 // Code Generation support.
2446 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2448 // Garbage collection support.
2449 inline Object** RawFieldOfElementAt(int index);
2451 DECLARE_CAST(FixedArray)
2453 // Maximal allowed size, in bytes, of a single FixedArray.
2454 // Prevents overflowing size computations, as well as extreme memory
2456 static const int kMaxSize = 128 * MB * kPointerSize;
2457 // Maximally allowed length of a FixedArray.
2458 static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
2460 // Dispatched behavior.
2461 DECLARE_PRINTER(FixedArray)
2462 DECLARE_VERIFIER(FixedArray)
2464 // Checks if two FixedArrays have identical contents.
2465 bool IsEqualTo(FixedArray* other);
2468 // Swap two elements in a pair of arrays. If this array and the
2469 // numbers array are the same object, the elements are only swapped
2471 void SwapPairs(FixedArray* numbers, int i, int j);
2473 // Sort prefix of this array and the numbers array as pairs wrt. the
2474 // numbers. If the numbers array and the this array are the same
2475 // object, the prefix of this array is sorted.
2476 void SortPairs(FixedArray* numbers, uint32_t len);
2478 class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
2480 static inline int SizeOf(Map* map, HeapObject* object);
2484 // Set operation on FixedArray without using write barriers. Can
2485 // only be used for storing old space objects or smis.
2486 static inline void NoWriteBarrierSet(FixedArray* array,
2490 // Set operation on FixedArray without incremental write barrier. Can
2491 // only be used if the object is guaranteed to be white (whiteness witness
2493 static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
2498 STATIC_ASSERT(kHeaderSize == Internals::kFixedArrayHeaderSize);
2500 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
2504 // FixedDoubleArray describes fixed-sized arrays with element type double.
2505 class FixedDoubleArray: public FixedArrayBase {
2507 // Setter and getter for elements.
2508 inline double get_scalar(int index);
2509 inline uint64_t get_representation(int index);
2510 static inline Handle<Object> get(Handle<FixedDoubleArray> array, int index);
2511 inline void set(int index, double value);
2512 inline void set_the_hole(int index);
2514 // Checking for the hole.
2515 inline bool is_the_hole(int index);
2517 // Garbage collection support.
2518 inline static int SizeFor(int length) {
2519 return kHeaderSize + length * kDoubleSize;
2522 // Gives access to raw memory which stores the array's data.
2523 inline double* data_start();
2525 inline void FillWithHoles(int from, int to);
2527 // Code Generation support.
2528 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2530 DECLARE_CAST(FixedDoubleArray)
2532 // Maximal allowed size, in bytes, of a single FixedDoubleArray.
2533 // Prevents overflowing size computations, as well as extreme memory
2535 static const int kMaxSize = 512 * MB;
2536 // Maximally allowed length of a FixedArray.
2537 static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
2539 // Dispatched behavior.
2540 DECLARE_PRINTER(FixedDoubleArray)
2541 DECLARE_VERIFIER(FixedDoubleArray)
2544 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
2548 class WeakFixedArray : public FixedArray {
2550 // If |maybe_array| is not a WeakFixedArray, a fresh one will be allocated.
2551 // This function does not check if the value exists already, callers must
2552 // ensure this themselves if necessary.
2553 static Handle<WeakFixedArray> Add(Handle<Object> maybe_array,
2554 Handle<HeapObject> value,
2555 int* assigned_index = NULL);
2557 // Returns true if an entry was found and removed.
2558 bool Remove(Handle<HeapObject> value);
2560 class NullCallback {
2562 static void Callback(Object* value, int old_index, int new_index) {}
2565 template <class CompactionCallback>
2568 inline Object* Get(int index) const;
2569 inline void Clear(int index);
2570 inline int Length() const;
2572 inline bool IsEmptySlot(int index) const;
2573 static Object* Empty() { return Smi::FromInt(0); }
2577 explicit Iterator(Object* maybe_array) : list_(NULL) { Reset(maybe_array); }
2578 void Reset(Object* maybe_array);
2585 WeakFixedArray* list_;
2587 int last_used_index_;
2588 DisallowHeapAllocation no_gc_;
2590 DISALLOW_COPY_AND_ASSIGN(Iterator);
2593 DECLARE_CAST(WeakFixedArray)
2596 static const int kLastUsedIndexIndex = 0;
2597 static const int kFirstIndex = 1;
2599 static Handle<WeakFixedArray> Allocate(
2600 Isolate* isolate, int size, Handle<WeakFixedArray> initialize_from);
2602 static void Set(Handle<WeakFixedArray> array, int index,
2603 Handle<HeapObject> value);
2604 inline void clear(int index);
2606 inline int last_used_index() const;
2607 inline void set_last_used_index(int index);
2609 // Disallow inherited setters.
2610 void set(int index, Smi* value);
2611 void set(int index, Object* value);
2612 void set(int index, Object* value, WriteBarrierMode mode);
2613 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakFixedArray);
2617 // Generic array grows dynamically with O(1) amortized insertion.
2618 class ArrayList : public FixedArray {
2622 // Use this if GC can delete elements from the array.
2623 kReloadLengthAfterAllocation,
2625 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj,
2626 AddMode mode = kNone);
2627 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj1,
2628 Handle<Object> obj2, AddMode = kNone);
2629 inline int Length();
2630 inline void SetLength(int length);
2631 inline Object* Get(int index);
2632 inline Object** Slot(int index);
2633 inline void Set(int index, Object* obj);
2634 inline void Clear(int index, Object* undefined);
2635 DECLARE_CAST(ArrayList)
2638 static Handle<ArrayList> EnsureSpace(Handle<ArrayList> array, int length);
2639 static const int kLengthIndex = 0;
2640 static const int kFirstIndex = 1;
2641 DISALLOW_IMPLICIT_CONSTRUCTORS(ArrayList);
2645 // DescriptorArrays are fixed arrays used to hold instance descriptors.
2646 // The format of the these objects is:
2647 // [0]: Number of descriptors
2648 // [1]: Either Smi(0) if uninitialized, or a pointer to small fixed array:
2649 // [0]: pointer to fixed array with enum cache
2650 // [1]: either Smi(0) or pointer to fixed array with indices
2652 // [2 + number of descriptors * kDescriptorSize]: start of slack
2653 class DescriptorArray: public FixedArray {
2655 // Returns true for both shared empty_descriptor_array and for smis, which the
2656 // map uses to encode additional bit fields when the descriptor array is not
2658 inline bool IsEmpty();
2660 // Returns the number of descriptors in the array.
2661 inline int number_of_descriptors();
2663 inline int number_of_descriptors_storage();
2665 inline int NumberOfSlackDescriptors();
2667 inline void SetNumberOfDescriptors(int number_of_descriptors);
2668 inline int number_of_entries();
2670 inline bool HasEnumCache();
2672 inline void CopyEnumCacheFrom(DescriptorArray* array);
2674 inline FixedArray* GetEnumCache();
2676 inline bool HasEnumIndicesCache();
2678 inline FixedArray* GetEnumIndicesCache();
2680 inline Object** GetEnumCacheSlot();
2682 void ClearEnumCache();
2684 // Initialize or change the enum cache,
2685 // using the supplied storage for the small "bridge".
2686 void SetEnumCache(FixedArray* bridge_storage,
2687 FixedArray* new_cache,
2688 Object* new_index_cache);
2690 bool CanHoldValue(int descriptor, Object* value);
2692 // Accessors for fetching instance descriptor at descriptor number.
2693 inline Name* GetKey(int descriptor_number);
2694 inline Object** GetKeySlot(int descriptor_number);
2695 inline Object* GetValue(int descriptor_number);
2696 inline void SetValue(int descriptor_number, Object* value);
2697 inline Object** GetValueSlot(int descriptor_number);
2698 static inline int GetValueOffset(int descriptor_number);
2699 inline Object** GetDescriptorStartSlot(int descriptor_number);
2700 inline Object** GetDescriptorEndSlot(int descriptor_number);
2701 inline PropertyDetails GetDetails(int descriptor_number);
2702 inline PropertyType GetType(int descriptor_number);
2703 inline int GetFieldIndex(int descriptor_number);
2704 inline HeapType* GetFieldType(int descriptor_number);
2705 inline Object* GetConstant(int descriptor_number);
2706 inline Object* GetCallbacksObject(int descriptor_number);
2707 inline AccessorDescriptor* GetCallbacks(int descriptor_number);
2709 inline Name* GetSortedKey(int descriptor_number);
2710 inline int GetSortedKeyIndex(int descriptor_number);
2711 inline void SetSortedKey(int pointer, int descriptor_number);
2712 inline void SetRepresentation(int descriptor_number,
2713 Representation representation);
2715 // Accessor for complete descriptor.
2716 inline void Get(int descriptor_number, Descriptor* desc);
2717 inline void Set(int descriptor_number, Descriptor* desc);
2718 void Replace(int descriptor_number, Descriptor* descriptor);
2720 // Append automatically sets the enumeration index. This should only be used
2721 // to add descriptors in bulk at the end, followed by sorting the descriptor
2723 inline void Append(Descriptor* desc);
2725 static Handle<DescriptorArray> CopyUpTo(Handle<DescriptorArray> desc,
2726 int enumeration_index,
2729 static Handle<DescriptorArray> CopyUpToAddAttributes(
2730 Handle<DescriptorArray> desc,
2731 int enumeration_index,
2732 PropertyAttributes attributes,
2735 // Sort the instance descriptors by the hash codes of their keys.
2738 // Search the instance descriptors for given name.
2739 INLINE(int Search(Name* name, int number_of_own_descriptors));
2741 // As the above, but uses DescriptorLookupCache and updates it when
2743 INLINE(int SearchWithCache(Name* name, Map* map));
2745 // Allocates a DescriptorArray, but returns the singleton
2746 // empty descriptor array object if number_of_descriptors is 0.
2747 static Handle<DescriptorArray> Allocate(Isolate* isolate,
2748 int number_of_descriptors,
2751 DECLARE_CAST(DescriptorArray)
2753 // Constant for denoting key was not found.
2754 static const int kNotFound = -1;
2756 static const int kDescriptorLengthIndex = 0;
2757 static const int kEnumCacheIndex = 1;
2758 static const int kFirstIndex = 2;
2760 // The length of the "bridge" to the enum cache.
2761 static const int kEnumCacheBridgeLength = 2;
2762 static const int kEnumCacheBridgeCacheIndex = 0;
2763 static const int kEnumCacheBridgeIndicesCacheIndex = 1;
2765 // Layout description.
2766 static const int kDescriptorLengthOffset = FixedArray::kHeaderSize;
2767 static const int kEnumCacheOffset = kDescriptorLengthOffset + kPointerSize;
2768 static const int kFirstOffset = kEnumCacheOffset + kPointerSize;
2770 // Layout description for the bridge array.
2771 static const int kEnumCacheBridgeCacheOffset = FixedArray::kHeaderSize;
2773 // Layout of descriptor.
2774 static const int kDescriptorKey = 0;
2775 static const int kDescriptorDetails = 1;
2776 static const int kDescriptorValue = 2;
2777 static const int kDescriptorSize = 3;
2779 #if defined(DEBUG) || defined(OBJECT_PRINT)
2780 // For our gdb macros, we should perhaps change these in the future.
2783 // Print all the descriptors.
2784 void PrintDescriptors(std::ostream& os); // NOLINT
2788 // Is the descriptor array sorted and without duplicates?
2789 bool IsSortedNoDuplicates(int valid_descriptors = -1);
2791 // Is the descriptor array consistent with the back pointers in targets?
2792 bool IsConsistentWithBackPointers(Map* current_map);
2794 // Are two DescriptorArrays equal?
2795 bool IsEqualTo(DescriptorArray* other);
2798 // Returns the fixed array length required to hold number_of_descriptors
2800 static int LengthFor(int number_of_descriptors) {
2801 return ToKeyIndex(number_of_descriptors);
2805 // WhitenessWitness is used to prove that a descriptor array is white
2806 // (unmarked), so incremental write barriers can be skipped because the
2807 // marking invariant cannot be broken and slots pointing into evacuation
2808 // candidates will be discovered when the object is scanned. A witness is
2809 // always stack-allocated right after creating an array. By allocating a
2810 // witness, incremental marking is globally disabled. The witness is then
2811 // passed along wherever needed to statically prove that the array is known to
2813 class WhitenessWitness {
2815 inline explicit WhitenessWitness(DescriptorArray* array);
2816 inline ~WhitenessWitness();
2819 IncrementalMarking* marking_;
2822 // An entry in a DescriptorArray, represented as an (array, index) pair.
2825 inline explicit Entry(DescriptorArray* descs, int index) :
2826 descs_(descs), index_(index) { }
2828 inline PropertyType type();
2829 inline Object* GetCallbackObject();
2832 DescriptorArray* descs_;
2836 // Conversion from descriptor number to array indices.
2837 static int ToKeyIndex(int descriptor_number) {
2838 return kFirstIndex +
2839 (descriptor_number * kDescriptorSize) +
2843 static int ToDetailsIndex(int descriptor_number) {
2844 return kFirstIndex +
2845 (descriptor_number * kDescriptorSize) +
2849 static int ToValueIndex(int descriptor_number) {
2850 return kFirstIndex +
2851 (descriptor_number * kDescriptorSize) +
2855 // Transfer a complete descriptor from the src descriptor array to this
2856 // descriptor array.
2857 void CopyFrom(int index, DescriptorArray* src, const WhitenessWitness&);
2859 inline void Set(int descriptor_number,
2861 const WhitenessWitness&);
2863 // Swap first and second descriptor.
2864 inline void SwapSortedKeys(int first, int second);
2866 DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
2870 enum SearchMode { ALL_ENTRIES, VALID_ENTRIES };
2872 template <SearchMode search_mode, typename T>
2873 inline int Search(T* array, Name* name, int valid_entries = 0,
2874 int* out_insertion_index = NULL);
2877 // HashTable is a subclass of FixedArray that implements a hash table
2878 // that uses open addressing and quadratic probing.
2880 // In order for the quadratic probing to work, elements that have not
2881 // yet been used and elements that have been deleted are
2882 // distinguished. Probing continues when deleted elements are
2883 // encountered and stops when unused elements are encountered.
2885 // - Elements with key == undefined have not been used yet.
2886 // - Elements with key == the_hole have been deleted.
2888 // The hash table class is parameterized with a Shape and a Key.
2889 // Shape must be a class with the following interface:
2890 // class ExampleShape {
2892 // // Tells whether key matches other.
2893 // static bool IsMatch(Key key, Object* other);
2894 // // Returns the hash value for key.
2895 // static uint32_t Hash(Key key);
2896 // // Returns the hash value for object.
2897 // static uint32_t HashForObject(Key key, Object* object);
2898 // // Convert key to an object.
2899 // static inline Handle<Object> AsHandle(Isolate* isolate, Key key);
2900 // // The prefix size indicates number of elements in the beginning
2901 // // of the backing storage.
2902 // static const int kPrefixSize = ..;
2903 // // The Element size indicates number of elements per entry.
2904 // static const int kEntrySize = ..;
2906 // The prefix size indicates an amount of memory in the
2907 // beginning of the backing storage that can be used for non-element
2908 // information by subclasses.
2910 template<typename Key>
2913 static const bool UsesSeed = false;
2914 static uint32_t Hash(Key key) { return 0; }
2915 static uint32_t SeededHash(Key key, uint32_t seed) {
2919 static uint32_t HashForObject(Key key, Object* object) { return 0; }
2920 static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
2922 return HashForObject(key, object);
2927 class HashTableBase : public FixedArray {
2929 // Returns the number of elements in the hash table.
2930 inline int NumberOfElements();
2932 // Returns the number of deleted elements in the hash table.
2933 inline int NumberOfDeletedElements();
2935 // Returns the capacity of the hash table.
2936 inline int Capacity();
2938 // ElementAdded should be called whenever an element is added to a
2940 inline void ElementAdded();
2942 // ElementRemoved should be called whenever an element is removed from
2944 inline void ElementRemoved();
2945 inline void ElementsRemoved(int n);
2947 // Computes the required capacity for a table holding the given
2948 // number of elements. May be more than HashTable::kMaxCapacity.
2949 static inline int ComputeCapacity(int at_least_space_for);
2951 // Tells whether k is a real key. The hole and undefined are not allowed
2952 // as keys and can be used to indicate missing or deleted elements.
2953 inline bool IsKey(Object* k);
2955 // Compute the probe offset (quadratic probing).
2956 INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
2957 return (n + n * n) >> 1;
2960 static const int kNumberOfElementsIndex = 0;
2961 static const int kNumberOfDeletedElementsIndex = 1;
2962 static const int kCapacityIndex = 2;
2963 static const int kPrefixStartIndex = 3;
2965 // Constant used for denoting a absent entry.
2966 static const int kNotFound = -1;
2969 // Update the number of elements in the hash table.
2970 inline void SetNumberOfElements(int nof);
2972 // Update the number of deleted elements in the hash table.
2973 inline void SetNumberOfDeletedElements(int nod);
2975 // Returns probe entry.
2976 static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
2977 DCHECK(base::bits::IsPowerOfTwo32(size));
2978 return (hash + GetProbeOffset(number)) & (size - 1);
2981 inline static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
2982 return hash & (size - 1);
2985 inline static uint32_t NextProbe(
2986 uint32_t last, uint32_t number, uint32_t size) {
2987 return (last + number) & (size - 1);
2992 template <typename Derived, typename Shape, typename Key>
2993 class HashTable : public HashTableBase {
2996 inline uint32_t Hash(Key key) {
2997 if (Shape::UsesSeed) {
2998 return Shape::SeededHash(key, GetHeap()->HashSeed());
3000 return Shape::Hash(key);
3004 inline uint32_t HashForObject(Key key, Object* object) {
3005 if (Shape::UsesSeed) {
3006 return Shape::SeededHashForObject(key, GetHeap()->HashSeed(), object);
3008 return Shape::HashForObject(key, object);
3012 // Returns a new HashTable object.
3013 MUST_USE_RESULT static Handle<Derived> New(
3014 Isolate* isolate, int at_least_space_for,
3015 MinimumCapacity capacity_option = USE_DEFAULT_MINIMUM_CAPACITY,
3016 PretenureFlag pretenure = NOT_TENURED);
3018 DECLARE_CAST(HashTable)
3020 // Garbage collection support.
3021 void IteratePrefix(ObjectVisitor* visitor);
3022 void IterateElements(ObjectVisitor* visitor);
3024 // Find entry for key otherwise return kNotFound.
3025 inline int FindEntry(Key key);
3026 inline int FindEntry(Isolate* isolate, Key key, int32_t hash);
3027 int FindEntry(Isolate* isolate, Key key);
3029 // Rehashes the table in-place.
3030 void Rehash(Key key);
3032 // Returns the key at entry.
3033 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3035 static const int kElementsStartIndex = kPrefixStartIndex + Shape::kPrefixSize;
3036 static const int kEntrySize = Shape::kEntrySize;
3037 static const int kElementsStartOffset =
3038 kHeaderSize + kElementsStartIndex * kPointerSize;
3039 static const int kCapacityOffset =
3040 kHeaderSize + kCapacityIndex * kPointerSize;
3042 // Returns the index for an entry (of the key)
3043 static inline int EntryToIndex(int entry) {
3044 return (entry * kEntrySize) + kElementsStartIndex;
3048 friend class ObjectHashTable;
3050 // Find the entry at which to insert element with the given key that
3051 // has the given hash value.
3052 uint32_t FindInsertionEntry(uint32_t hash);
3054 // Attempt to shrink hash table after removal of key.
3055 MUST_USE_RESULT static Handle<Derived> Shrink(Handle<Derived> table, Key key);
3057 // Ensure enough space for n additional elements.
3058 MUST_USE_RESULT static Handle<Derived> EnsureCapacity(
3059 Handle<Derived> table,
3062 PretenureFlag pretenure = NOT_TENURED);
3064 // Sets the capacity of the hash table.
3065 void SetCapacity(int capacity) {
3066 // To scale a computed hash code to fit within the hash table, we
3067 // use bit-wise AND with a mask, so the capacity must be positive
3069 DCHECK(capacity > 0);
3070 DCHECK(capacity <= kMaxCapacity);
3071 set(kCapacityIndex, Smi::FromInt(capacity));
3074 // Maximal capacity of HashTable. Based on maximal length of underlying
3075 // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
3077 static const int kMaxCapacity =
3078 (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
3081 // Returns _expected_ if one of entries given by the first _probe_ probes is
3082 // equal to _expected_. Otherwise, returns the entry given by the probe
3084 uint32_t EntryForProbe(Key key, Object* k, int probe, uint32_t expected);
3086 void Swap(uint32_t entry1, uint32_t entry2, WriteBarrierMode mode);
3088 // Rehashes this hash-table into the new table.
3089 void Rehash(Handle<Derived> new_table, Key key);
3093 // HashTableKey is an abstract superclass for virtual key behavior.
3094 class HashTableKey {
3096 // Returns whether the other object matches this key.
3097 virtual bool IsMatch(Object* other) = 0;
3098 // Returns the hash value for this key.
3099 virtual uint32_t Hash() = 0;
3100 // Returns the hash value for object.
3101 virtual uint32_t HashForObject(Object* key) = 0;
3102 // Returns the key object for storing into the hash table.
3103 MUST_USE_RESULT virtual Handle<Object> AsHandle(Isolate* isolate) = 0;
3105 virtual ~HashTableKey() {}
3109 class StringTableShape : public BaseShape<HashTableKey*> {
3111 static inline bool IsMatch(HashTableKey* key, Object* value) {
3112 return key->IsMatch(value);
3115 static inline uint32_t Hash(HashTableKey* key) {
3119 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3120 return key->HashForObject(object);
3123 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3125 static const int kPrefixSize = 0;
3126 static const int kEntrySize = 1;
3129 class SeqOneByteString;
3133 // No special elements in the prefix and the element size is 1
3134 // because only the string itself (the key) needs to be stored.
3135 class StringTable: public HashTable<StringTable,
3139 // Find string in the string table. If it is not there yet, it is
3140 // added. The return value is the string found.
3141 static Handle<String> LookupString(Isolate* isolate, Handle<String> key);
3142 static Handle<String> LookupKey(Isolate* isolate, HashTableKey* key);
3143 static String* LookupKeyIfExists(Isolate* isolate, HashTableKey* key);
3145 // Tries to internalize given string and returns string handle on success
3146 // or an empty handle otherwise.
3147 MUST_USE_RESULT static MaybeHandle<String> InternalizeStringIfExists(
3149 Handle<String> string);
3151 // Looks up a string that is equal to the given string and returns
3152 // string handle if it is found, or an empty handle otherwise.
3153 MUST_USE_RESULT static MaybeHandle<String> LookupStringIfExists(
3155 Handle<String> str);
3156 MUST_USE_RESULT static MaybeHandle<String> LookupTwoCharsStringIfExists(
3161 static void EnsureCapacityForDeserialization(Isolate* isolate, int expected);
3163 DECLARE_CAST(StringTable)
3166 template <bool seq_one_byte>
3167 friend class JsonParser;
3169 DISALLOW_IMPLICIT_CONSTRUCTORS(StringTable);
3173 template <typename Derived, typename Shape, typename Key>
3174 class Dictionary: public HashTable<Derived, Shape, Key> {
3175 typedef HashTable<Derived, Shape, Key> DerivedHashTable;
3178 // Returns the value at entry.
3179 Object* ValueAt(int entry) {
3180 return this->get(Derived::EntryToIndex(entry) + 1);
3183 // Set the value for entry.
3184 void ValueAtPut(int entry, Object* value) {
3185 this->set(Derived::EntryToIndex(entry) + 1, value);
3188 // Returns the property details for the property at entry.
3189 PropertyDetails DetailsAt(int entry) {
3190 return Shape::DetailsAt(static_cast<Derived*>(this), entry);
3193 // Set the details for entry.
3194 void DetailsAtPut(int entry, PropertyDetails value) {
3195 Shape::DetailsAtPut(static_cast<Derived*>(this), entry, value);
3198 // Returns true if property at given entry is deleted.
3199 bool IsDeleted(int entry) {
3200 return Shape::IsDeleted(static_cast<Derived*>(this), entry);
3203 // Delete a property from the dictionary.
3204 static Handle<Object> DeleteProperty(Handle<Derived> dictionary, int entry);
3206 // Attempt to shrink the dictionary after deletion of key.
3207 MUST_USE_RESULT static inline Handle<Derived> Shrink(
3208 Handle<Derived> dictionary,
3210 return DerivedHashTable::Shrink(dictionary, key);
3214 // TODO(dcarney): templatize or move to SeededNumberDictionary
3215 void CopyValuesTo(FixedArray* elements);
3217 // Returns the number of elements in the dictionary filtering out properties
3218 // with the specified attributes.
3219 int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3221 // Returns the number of enumerable elements in the dictionary.
3222 int NumberOfEnumElements() {
3223 return NumberOfElementsFilterAttributes(
3224 static_cast<PropertyAttributes>(DONT_ENUM | SYMBOLIC));
3227 // Returns true if the dictionary contains any elements that are non-writable,
3228 // non-configurable, non-enumerable, or have getters/setters.
3229 bool HasComplexElements();
3231 enum SortMode { UNSORTED, SORTED };
3233 // Fill in details for properties into storage.
3234 // Returns the number of properties added.
3235 int CopyKeysTo(FixedArray* storage, int index, PropertyAttributes filter,
3236 SortMode sort_mode);
3238 // Copies enumerable keys to preallocated fixed array.
3239 void CopyEnumKeysTo(FixedArray* storage);
3241 // Accessors for next enumeration index.
3242 void SetNextEnumerationIndex(int index) {
3244 this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
3247 int NextEnumerationIndex() {
3248 return Smi::cast(this->get(kNextEnumerationIndexIndex))->value();
3251 // Creates a new dictionary.
3252 MUST_USE_RESULT static Handle<Derived> New(
3254 int at_least_space_for,
3255 PretenureFlag pretenure = NOT_TENURED);
3257 // Ensure enough space for n additional elements.
3258 static Handle<Derived> EnsureCapacity(Handle<Derived> obj, int n, Key key);
3261 void Print(std::ostream& os); // NOLINT
3263 // Returns the key (slow).
3264 Object* SlowReverseLookup(Object* value);
3266 // Sets the entry to (key, value) pair.
3267 inline void SetEntry(int entry,
3269 Handle<Object> value);
3270 inline void SetEntry(int entry,
3272 Handle<Object> value,
3273 PropertyDetails details);
3275 MUST_USE_RESULT static Handle<Derived> Add(
3276 Handle<Derived> dictionary,
3278 Handle<Object> value,
3279 PropertyDetails details);
3281 // Returns iteration indices array for the |dictionary|.
3282 // Values are direct indices in the |HashTable| array.
3283 static Handle<FixedArray> BuildIterationIndicesArray(
3284 Handle<Derived> dictionary);
3287 // Generic at put operation.
3288 MUST_USE_RESULT static Handle<Derived> AtPut(
3289 Handle<Derived> dictionary,
3291 Handle<Object> value);
3293 // Add entry to dictionary.
3294 static void AddEntry(
3295 Handle<Derived> dictionary,
3297 Handle<Object> value,
3298 PropertyDetails details,
3301 // Generate new enumeration indices to avoid enumeration index overflow.
3302 // Returns iteration indices array for the |dictionary|.
3303 static Handle<FixedArray> GenerateNewEnumerationIndices(
3304 Handle<Derived> dictionary);
3305 static const int kMaxNumberKeyIndex = DerivedHashTable::kPrefixStartIndex;
3306 static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
3310 template <typename Derived, typename Shape>
3311 class NameDictionaryBase : public Dictionary<Derived, Shape, Handle<Name> > {
3312 typedef Dictionary<Derived, Shape, Handle<Name> > DerivedDictionary;
3315 // Find entry for key, otherwise return kNotFound. Optimized version of
3316 // HashTable::FindEntry.
3317 int FindEntry(Handle<Name> key);
3321 template <typename Key>
3322 class BaseDictionaryShape : public BaseShape<Key> {
3324 template <typename Dictionary>
3325 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry) {
3326 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3327 DCHECK(entry >= 0); // Not found is -1, which is not caught by get().
3328 return PropertyDetails(
3329 Smi::cast(dict->get(Dictionary::EntryToIndex(entry) + 2)));
3332 template <typename Dictionary>
3333 static inline void DetailsAtPut(Dictionary* dict, int entry,
3334 PropertyDetails value) {
3335 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3336 dict->set(Dictionary::EntryToIndex(entry) + 2, value.AsSmi());
3339 template <typename Dictionary>
3340 static bool IsDeleted(Dictionary* dict, int entry) {
3344 template <typename Dictionary>
3345 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3346 Handle<Object> value, PropertyDetails details);
3350 class NameDictionaryShape : public BaseDictionaryShape<Handle<Name> > {
3352 static inline bool IsMatch(Handle<Name> key, Object* other);
3353 static inline uint32_t Hash(Handle<Name> key);
3354 static inline uint32_t HashForObject(Handle<Name> key, Object* object);
3355 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Name> key);
3356 static const int kPrefixSize = 2;
3357 static const int kEntrySize = 3;
3358 static const bool kIsEnumerable = true;
3362 class NameDictionary
3363 : public NameDictionaryBase<NameDictionary, NameDictionaryShape> {
3364 typedef NameDictionaryBase<NameDictionary, NameDictionaryShape>
3368 DECLARE_CAST(NameDictionary)
3370 inline static Handle<FixedArray> DoGenerateNewEnumerationIndices(
3371 Handle<NameDictionary> dictionary);
3375 class GlobalDictionaryShape : public NameDictionaryShape {
3377 static const int kEntrySize = 2; // Overrides NameDictionaryShape::kEntrySize
3379 template <typename Dictionary>
3380 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry);
3382 template <typename Dictionary>
3383 static inline void DetailsAtPut(Dictionary* dict, int entry,
3384 PropertyDetails value);
3386 template <typename Dictionary>
3387 static bool IsDeleted(Dictionary* dict, int entry);
3389 template <typename Dictionary>
3390 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3391 Handle<Object> value, PropertyDetails details);
3395 class GlobalDictionary
3396 : public NameDictionaryBase<GlobalDictionary, GlobalDictionaryShape> {
3398 DECLARE_CAST(GlobalDictionary)
3402 class NumberDictionaryShape : public BaseDictionaryShape<uint32_t> {
3404 static inline bool IsMatch(uint32_t key, Object* other);
3405 static inline Handle<Object> AsHandle(Isolate* isolate, uint32_t key);
3406 static const int kEntrySize = 3;
3407 static const bool kIsEnumerable = false;
3411 class SeededNumberDictionaryShape : public NumberDictionaryShape {
3413 static const bool UsesSeed = true;
3414 static const int kPrefixSize = 2;
3416 static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
3417 static inline uint32_t SeededHashForObject(uint32_t key,
3423 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
3425 static const int kPrefixSize = 0;
3427 static inline uint32_t Hash(uint32_t key);
3428 static inline uint32_t HashForObject(uint32_t key, Object* object);
3432 class SeededNumberDictionary
3433 : public Dictionary<SeededNumberDictionary,
3434 SeededNumberDictionaryShape,
3437 DECLARE_CAST(SeededNumberDictionary)
3439 // Type specific at put (default NONE attributes is used when adding).
3440 MUST_USE_RESULT static Handle<SeededNumberDictionary> AtNumberPut(
3441 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3442 Handle<Object> value, bool used_as_prototype);
3443 MUST_USE_RESULT static Handle<SeededNumberDictionary> AddNumberEntry(
3444 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3445 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3447 // Set an existing entry or add a new one if needed.
3448 // Return the updated dictionary.
3449 MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
3450 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3451 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3453 void UpdateMaxNumberKey(uint32_t key, bool used_as_prototype);
3455 // If slow elements are required we will never go back to fast-case
3456 // for the elements kept in this dictionary. We require slow
3457 // elements if an element has been added at an index larger than
3458 // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
3459 // when defining a getter or setter with a number key.
3460 inline bool requires_slow_elements();
3461 inline void set_requires_slow_elements();
3463 // Get the value of the max number key that has been added to this
3464 // dictionary. max_number_key can only be called if
3465 // requires_slow_elements returns false.
3466 inline uint32_t max_number_key();
3469 static const int kRequiresSlowElementsMask = 1;
3470 static const int kRequiresSlowElementsTagSize = 1;
3471 static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
3475 class UnseededNumberDictionary
3476 : public Dictionary<UnseededNumberDictionary,
3477 UnseededNumberDictionaryShape,
3480 DECLARE_CAST(UnseededNumberDictionary)
3482 // Type specific at put (default NONE attributes is used when adding).
3483 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AtNumberPut(
3484 Handle<UnseededNumberDictionary> dictionary,
3486 Handle<Object> value);
3487 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AddNumberEntry(
3488 Handle<UnseededNumberDictionary> dictionary,
3490 Handle<Object> value);
3492 // Set an existing entry or add a new one if needed.
3493 // Return the updated dictionary.
3494 MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
3495 Handle<UnseededNumberDictionary> dictionary,
3497 Handle<Object> value);
3501 class ObjectHashTableShape : public BaseShape<Handle<Object> > {
3503 static inline bool IsMatch(Handle<Object> key, Object* other);
3504 static inline uint32_t Hash(Handle<Object> key);
3505 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3506 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3507 static const int kPrefixSize = 0;
3508 static const int kEntrySize = 2;
3512 // ObjectHashTable maps keys that are arbitrary objects to object values by
3513 // using the identity hash of the key for hashing purposes.
3514 class ObjectHashTable: public HashTable<ObjectHashTable,
3515 ObjectHashTableShape,
3518 ObjectHashTable, ObjectHashTableShape, Handle<Object> > DerivedHashTable;
3520 DECLARE_CAST(ObjectHashTable)
3522 // Attempt to shrink hash table after removal of key.
3523 MUST_USE_RESULT static inline Handle<ObjectHashTable> Shrink(
3524 Handle<ObjectHashTable> table,
3525 Handle<Object> key);
3527 // Looks up the value associated with the given key. The hole value is
3528 // returned in case the key is not present.
3529 Object* Lookup(Handle<Object> key);
3530 Object* Lookup(Handle<Object> key, int32_t hash);
3531 Object* Lookup(Isolate* isolate, Handle<Object> key, int32_t hash);
3533 // Adds (or overwrites) the value associated with the given key.
3534 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3536 Handle<Object> value);
3537 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3538 Handle<Object> key, Handle<Object> value,
3541 // Returns an ObjectHashTable (possibly |table|) where |key| has been removed.
3542 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3545 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3546 Handle<Object> key, bool* was_present,
3550 friend class MarkCompactCollector;
3552 void AddEntry(int entry, Object* key, Object* value);
3553 void RemoveEntry(int entry);
3555 // Returns the index to the value of an entry.
3556 static inline int EntryToValueIndex(int entry) {
3557 return EntryToIndex(entry) + 1;
3562 // OrderedHashTable is a HashTable with Object keys that preserves
3563 // insertion order. There are Map and Set interfaces (OrderedHashMap
3564 // and OrderedHashTable, below). It is meant to be used by JSMap/JSSet.
3566 // Only Object* keys are supported, with Object::SameValueZero() used as the
3567 // equality operator and Object::GetHash() for the hash function.
3569 // Based on the "Deterministic Hash Table" as described by Jason Orendorff at
3570 // https://wiki.mozilla.org/User:Jorend/Deterministic_hash_tables
3571 // Originally attributed to Tyler Close.
3574 // [0]: bucket count
3575 // [1]: element count
3576 // [2]: deleted element count
3577 // [3..(3 + NumberOfBuckets() - 1)]: "hash table", where each item is an
3578 // offset into the data table (see below) where the
3579 // first item in this bucket is stored.
3580 // [3 + NumberOfBuckets()..length]: "data table", an array of length
3581 // Capacity() * kEntrySize, where the first entrysize
3582 // items are handled by the derived class and the
3583 // item at kChainOffset is another entry into the
3584 // data table indicating the next entry in this hash
3587 // When we transition the table to a new version we obsolete it and reuse parts
3588 // of the memory to store information how to transition an iterator to the new
3591 // Memory layout for obsolete table:
3592 // [0]: bucket count
3593 // [1]: Next newer table
3594 // [2]: Number of removed holes or -1 when the table was cleared.
3595 // [3..(3 + NumberOfRemovedHoles() - 1)]: The indexes of the removed holes.
3596 // [3 + NumberOfRemovedHoles()..length]: Not used
3598 template<class Derived, class Iterator, int entrysize>
3599 class OrderedHashTable: public FixedArray {
3601 // Returns an OrderedHashTable with a capacity of at least |capacity|.
3602 static Handle<Derived> Allocate(
3603 Isolate* isolate, int capacity, PretenureFlag pretenure = NOT_TENURED);
3605 // Returns an OrderedHashTable (possibly |table|) with enough space
3606 // to add at least one new element.
3607 static Handle<Derived> EnsureGrowable(Handle<Derived> table);
3609 // Returns an OrderedHashTable (possibly |table|) that's shrunken
3611 static Handle<Derived> Shrink(Handle<Derived> table);
3613 // Returns a new empty OrderedHashTable and records the clearing so that
3614 // exisiting iterators can be updated.
3615 static Handle<Derived> Clear(Handle<Derived> table);
3617 int NumberOfElements() {
3618 return Smi::cast(get(kNumberOfElementsIndex))->value();
3621 int NumberOfDeletedElements() {
3622 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3625 int UsedCapacity() { return NumberOfElements() + NumberOfDeletedElements(); }
3627 int NumberOfBuckets() {
3628 return Smi::cast(get(kNumberOfBucketsIndex))->value();
3631 // Returns an index into |this| for the given entry.
3632 int EntryToIndex(int entry) {
3633 return kHashTableStartIndex + NumberOfBuckets() + (entry * kEntrySize);
3636 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3639 return !get(kNextTableIndex)->IsSmi();
3642 // The next newer table. This is only valid if the table is obsolete.
3643 Derived* NextTable() {
3644 return Derived::cast(get(kNextTableIndex));
3647 // When the table is obsolete we store the indexes of the removed holes.
3648 int RemovedIndexAt(int index) {
3649 return Smi::cast(get(kRemovedHolesIndex + index))->value();
3652 static const int kNotFound = -1;
3653 static const int kMinCapacity = 4;
3655 static const int kNumberOfBucketsIndex = 0;
3656 static const int kNumberOfElementsIndex = kNumberOfBucketsIndex + 1;
3657 static const int kNumberOfDeletedElementsIndex = kNumberOfElementsIndex + 1;
3658 static const int kHashTableStartIndex = kNumberOfDeletedElementsIndex + 1;
3659 static const int kNextTableIndex = kNumberOfElementsIndex;
3661 static const int kNumberOfBucketsOffset =
3662 kHeaderSize + kNumberOfBucketsIndex * kPointerSize;
3663 static const int kNumberOfElementsOffset =
3664 kHeaderSize + kNumberOfElementsIndex * kPointerSize;
3665 static const int kNumberOfDeletedElementsOffset =
3666 kHeaderSize + kNumberOfDeletedElementsIndex * kPointerSize;
3667 static const int kHashTableStartOffset =
3668 kHeaderSize + kHashTableStartIndex * kPointerSize;
3669 static const int kNextTableOffset =
3670 kHeaderSize + kNextTableIndex * kPointerSize;
3672 static const int kEntrySize = entrysize + 1;
3673 static const int kChainOffset = entrysize;
3675 static const int kLoadFactor = 2;
3677 // NumberOfDeletedElements is set to kClearedTableSentinel when
3678 // the table is cleared, which allows iterator transitions to
3679 // optimize that case.
3680 static const int kClearedTableSentinel = -1;
3683 static Handle<Derived> Rehash(Handle<Derived> table, int new_capacity);
3685 void SetNumberOfBuckets(int num) {
3686 set(kNumberOfBucketsIndex, Smi::FromInt(num));
3689 void SetNumberOfElements(int num) {
3690 set(kNumberOfElementsIndex, Smi::FromInt(num));
3693 void SetNumberOfDeletedElements(int num) {
3694 set(kNumberOfDeletedElementsIndex, Smi::FromInt(num));
3698 return NumberOfBuckets() * kLoadFactor;
3701 void SetNextTable(Derived* next_table) {
3702 set(kNextTableIndex, next_table);
3705 void SetRemovedIndexAt(int index, int removed_index) {
3706 return set(kRemovedHolesIndex + index, Smi::FromInt(removed_index));
3709 static const int kRemovedHolesIndex = kHashTableStartIndex;
3711 static const int kMaxCapacity =
3712 (FixedArray::kMaxLength - kHashTableStartIndex)
3713 / (1 + (kEntrySize * kLoadFactor));
3717 class JSSetIterator;
3720 class OrderedHashSet: public OrderedHashTable<
3721 OrderedHashSet, JSSetIterator, 1> {
3723 DECLARE_CAST(OrderedHashSet)
3727 class JSMapIterator;
3730 class OrderedHashMap
3731 : public OrderedHashTable<OrderedHashMap, JSMapIterator, 2> {
3733 DECLARE_CAST(OrderedHashMap)
3735 inline Object* ValueAt(int entry);
3737 static const int kValueOffset = 1;
3741 template <int entrysize>
3742 class WeakHashTableShape : public BaseShape<Handle<Object> > {
3744 static inline bool IsMatch(Handle<Object> key, Object* other);
3745 static inline uint32_t Hash(Handle<Object> key);
3746 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3747 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3748 static const int kPrefixSize = 0;
3749 static const int kEntrySize = entrysize;
3753 // WeakHashTable maps keys that are arbitrary heap objects to heap object
3754 // values. The table wraps the keys in weak cells and store values directly.
3755 // Thus it references keys weakly and values strongly.
3756 class WeakHashTable: public HashTable<WeakHashTable,
3757 WeakHashTableShape<2>,
3760 WeakHashTable, WeakHashTableShape<2>, Handle<Object> > DerivedHashTable;
3762 DECLARE_CAST(WeakHashTable)
3764 // Looks up the value associated with the given key. The hole value is
3765 // returned in case the key is not present.
3766 Object* Lookup(Handle<HeapObject> key);
3768 // Adds (or overwrites) the value associated with the given key. Mapping a
3769 // key to the hole value causes removal of the whole entry.
3770 MUST_USE_RESULT static Handle<WeakHashTable> Put(Handle<WeakHashTable> table,
3771 Handle<HeapObject> key,
3772 Handle<HeapObject> value);
3774 static Handle<FixedArray> GetValues(Handle<WeakHashTable> table);
3777 friend class MarkCompactCollector;
3779 void AddEntry(int entry, Handle<WeakCell> key, Handle<HeapObject> value);
3781 // Returns the index to the value of an entry.
3782 static inline int EntryToValueIndex(int entry) {
3783 return EntryToIndex(entry) + 1;
3788 // ScopeInfo represents information about different scopes of a source
3789 // program and the allocation of the scope's variables. Scope information
3790 // is stored in a compressed form in ScopeInfo objects and is used
3791 // at runtime (stack dumps, deoptimization, etc.).
3793 // This object provides quick access to scope info details for runtime
3795 class ScopeInfo : public FixedArray {
3797 DECLARE_CAST(ScopeInfo)
3799 // Return the type of this scope.
3800 ScopeType scope_type();
3802 // Does this scope call eval?
3805 // Return the language mode of this scope.
3806 LanguageMode language_mode();
3808 // True if this scope is a (var) declaration scope.
3809 bool is_declaration_scope();
3811 // Does this scope make a sloppy eval call?
3812 bool CallsSloppyEval() { return CallsEval() && is_sloppy(language_mode()); }
3814 // Return the total number of locals allocated on the stack and in the
3815 // context. This includes the parameters that are allocated in the context.
3818 // Return the number of stack slots for code. This number consists of two
3820 // 1. One stack slot per stack allocated local.
3821 // 2. One stack slot for the function name if it is stack allocated.
3822 int StackSlotCount();
3824 // Return the number of context slots for code if a context is allocated. This
3825 // number consists of three parts:
3826 // 1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
3827 // 2. One context slot per context allocated local.
3828 // 3. One context slot for the function name if it is context allocated.
3829 // Parameters allocated in the context count as context allocated locals. If
3830 // no contexts are allocated for this scope ContextLength returns 0.
3831 int ContextLength();
3833 // Does this scope declare a "this" binding?
3836 // Does this scope declare a "this" binding, and the "this" binding is stack-
3837 // or context-allocated?
3838 bool HasAllocatedReceiver();
3840 // Is this scope the scope of a named function expression?
3841 bool HasFunctionName();
3843 // Return if this has context allocated locals.
3844 bool HasHeapAllocatedLocals();
3846 // Return if contexts are allocated for this scope.
3849 // Return if this is a function scope with "use asm".
3850 inline bool IsAsmModule();
3852 // Return if this is a nested function within an asm module scope.
3853 inline bool IsAsmFunction();
3855 inline bool HasSimpleParameters();
3857 // Return the function_name if present.
3858 String* FunctionName();
3860 // Return the name of the given parameter.
3861 String* ParameterName(int var);
3863 // Return the name of the given local.
3864 String* LocalName(int var);
3866 // Return the name of the given stack local.
3867 String* StackLocalName(int var);
3869 // Return the name of the given stack local.
3870 int StackLocalIndex(int var);
3872 // Return the name of the given context local.
3873 String* ContextLocalName(int var);
3875 // Return the mode of the given context local.
3876 VariableMode ContextLocalMode(int var);
3878 // Return the initialization flag of the given context local.
3879 InitializationFlag ContextLocalInitFlag(int var);
3881 // Return the initialization flag of the given context local.
3882 MaybeAssignedFlag ContextLocalMaybeAssignedFlag(int var);
3884 // Return true if this local was introduced by the compiler, and should not be
3885 // exposed to the user in a debugger.
3886 bool LocalIsSynthetic(int var);
3888 String* StrongModeFreeVariableName(int var);
3889 int StrongModeFreeVariableStartPosition(int var);
3890 int StrongModeFreeVariableEndPosition(int var);
3892 // Lookup support for serialized scope info. Returns the
3893 // the stack slot index for a given slot name if the slot is
3894 // present; otherwise returns a value < 0. The name must be an internalized
3896 int StackSlotIndex(String* name);
3898 // Lookup support for serialized scope info. Returns the
3899 // context slot index for a given slot name if the slot is present; otherwise
3900 // returns a value < 0. The name must be an internalized string.
3901 // If the slot is present and mode != NULL, sets *mode to the corresponding
3902 // mode for that variable.
3903 static int ContextSlotIndex(Handle<ScopeInfo> scope_info, Handle<String> name,
3904 VariableMode* mode, VariableLocation* location,
3905 InitializationFlag* init_flag,
3906 MaybeAssignedFlag* maybe_assigned_flag);
3908 // Lookup the name of a certain context slot by its index.
3909 String* ContextSlotName(int slot_index);
3911 // Lookup support for serialized scope info. Returns the
3912 // parameter index for a given parameter name if the parameter is present;
3913 // otherwise returns a value < 0. The name must be an internalized string.
3914 int ParameterIndex(String* name);
3916 // Lookup support for serialized scope info. Returns the function context
3917 // slot index if the function name is present and context-allocated (named
3918 // function expressions, only), otherwise returns a value < 0. The name
3919 // must be an internalized string.
3920 int FunctionContextSlotIndex(String* name, VariableMode* mode);
3922 // Lookup support for serialized scope info. Returns the receiver context
3923 // slot index if scope has a "this" binding, and the binding is
3924 // context-allocated. Otherwise returns a value < 0.
3925 int ReceiverContextSlotIndex();
3927 FunctionKind function_kind();
3929 static Handle<ScopeInfo> Create(Isolate* isolate, Zone* zone, Scope* scope);
3930 static Handle<ScopeInfo> CreateGlobalThisBinding(Isolate* isolate);
3932 // Serializes empty scope info.
3933 static ScopeInfo* Empty(Isolate* isolate);
3939 // The layout of the static part of a ScopeInfo is as follows. Each entry is
3940 // numeric and occupies one array slot.
3941 // 1. A set of properties of the scope
3942 // 2. The number of parameters. This only applies to function scopes. For
3943 // non-function scopes this is 0.
3944 // 3. The number of non-parameter variables allocated on the stack.
3945 // 4. The number of non-parameter and parameter variables allocated in the
3947 #define FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(V) \
3950 V(StackLocalCount) \
3951 V(ContextLocalCount) \
3952 V(ContextGlobalCount) \
3953 V(StrongModeFreeVariableCount)
3955 #define FIELD_ACCESSORS(name) \
3956 inline void Set##name(int value); \
3958 FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(FIELD_ACCESSORS)
3959 #undef FIELD_ACCESSORS
3963 #define DECL_INDEX(name) k##name,
3964 FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(DECL_INDEX)
3969 // The layout of the variable part of a ScopeInfo is as follows:
3970 // 1. ParameterEntries:
3971 // This part stores the names of the parameters for function scopes. One
3972 // slot is used per parameter, so in total this part occupies
3973 // ParameterCount() slots in the array. For other scopes than function
3974 // scopes ParameterCount() is 0.
3975 // 2. StackLocalFirstSlot:
3976 // Index of a first stack slot for stack local. Stack locals belonging to
3977 // this scope are located on a stack at slots starting from this index.
3978 // 3. StackLocalEntries:
3979 // Contains the names of local variables that are allocated on the stack,
3980 // in increasing order of the stack slot index. First local variable has
3981 // a stack slot index defined in StackLocalFirstSlot (point 2 above).
3982 // One slot is used per stack local, so in total this part occupies
3983 // StackLocalCount() slots in the array.
3984 // 4. ContextLocalNameEntries:
3985 // Contains the names of local variables and parameters that are allocated
3986 // in the context. They are stored in increasing order of the context slot
3987 // index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
3988 // context local, so in total this part occupies ContextLocalCount() slots
3990 // 5. ContextLocalInfoEntries:
3991 // Contains the variable modes and initialization flags corresponding to
3992 // the context locals in ContextLocalNameEntries. One slot is used per
3993 // context local, so in total this part occupies ContextLocalCount()
3994 // slots in the array.
3995 // 6. StrongModeFreeVariableNameEntries:
3996 // Stores the names of strong mode free variables.
3997 // 7. StrongModeFreeVariablePositionEntries:
3998 // Stores the locations (start and end position) of strong mode free
4000 // 8. RecieverEntryIndex:
4001 // If the scope binds a "this" value, one slot is reserved to hold the
4002 // context or stack slot index for the variable.
4003 // 9. FunctionNameEntryIndex:
4004 // If the scope belongs to a named function expression this part contains
4005 // information about the function variable. It always occupies two array
4006 // slots: a. The name of the function variable.
4007 // b. The context or stack slot index for the variable.
4008 int ParameterEntriesIndex();
4009 int StackLocalFirstSlotIndex();
4010 int StackLocalEntriesIndex();
4011 int ContextLocalNameEntriesIndex();
4012 int ContextGlobalNameEntriesIndex();
4013 int ContextLocalInfoEntriesIndex();
4014 int ContextGlobalInfoEntriesIndex();
4015 int StrongModeFreeVariableNameEntriesIndex();
4016 int StrongModeFreeVariablePositionEntriesIndex();
4017 int ReceiverEntryIndex();
4018 int FunctionNameEntryIndex();
4020 int Lookup(Handle<String> name, int start, int end, VariableMode* mode,
4021 VariableLocation* location, InitializationFlag* init_flag,
4022 MaybeAssignedFlag* maybe_assigned_flag);
4024 // Used for the function name variable for named function expressions, and for
4026 enum VariableAllocationInfo { NONE, STACK, CONTEXT, UNUSED };
4028 // Properties of scopes.
4029 class ScopeTypeField : public BitField<ScopeType, 0, 4> {};
4030 class CallsEvalField : public BitField<bool, ScopeTypeField::kNext, 1> {};
4031 STATIC_ASSERT(LANGUAGE_END == 3);
4032 class LanguageModeField
4033 : public BitField<LanguageMode, CallsEvalField::kNext, 2> {};
4034 class DeclarationScopeField
4035 : public BitField<bool, LanguageModeField::kNext, 1> {};
4036 class ReceiverVariableField
4037 : public BitField<VariableAllocationInfo, DeclarationScopeField::kNext,
4039 class FunctionVariableField
4040 : public BitField<VariableAllocationInfo, ReceiverVariableField::kNext,
4042 class FunctionVariableMode
4043 : public BitField<VariableMode, FunctionVariableField::kNext, 3> {};
4044 class AsmModuleField : public BitField<bool, FunctionVariableMode::kNext, 1> {
4046 class AsmFunctionField : public BitField<bool, AsmModuleField::kNext, 1> {};
4047 class HasSimpleParametersField
4048 : public BitField<bool, AsmFunctionField::kNext, 1> {};
4049 class FunctionKindField
4050 : public BitField<FunctionKind, HasSimpleParametersField::kNext, 8> {};
4052 // BitFields representing the encoded information for context locals in the
4053 // ContextLocalInfoEntries part.
4054 class ContextLocalMode: public BitField<VariableMode, 0, 3> {};
4055 class ContextLocalInitFlag: public BitField<InitializationFlag, 3, 1> {};
4056 class ContextLocalMaybeAssignedFlag
4057 : public BitField<MaybeAssignedFlag, 4, 1> {};
4059 friend class ScopeIterator;
4063 // The cache for maps used by normalized (dictionary mode) objects.
4064 // Such maps do not have property descriptors, so a typical program
4065 // needs very limited number of distinct normalized maps.
4066 class NormalizedMapCache: public FixedArray {
4068 static Handle<NormalizedMapCache> New(Isolate* isolate);
4070 MUST_USE_RESULT MaybeHandle<Map> Get(Handle<Map> fast_map,
4071 PropertyNormalizationMode mode);
4072 void Set(Handle<Map> fast_map, Handle<Map> normalized_map);
4076 DECLARE_CAST(NormalizedMapCache)
4078 static inline bool IsNormalizedMapCache(const Object* obj);
4080 DECLARE_VERIFIER(NormalizedMapCache)
4082 static const int kEntries = 64;
4084 static inline int GetIndex(Handle<Map> map);
4086 // The following declarations hide base class methods.
4087 Object* get(int index);
4088 void set(int index, Object* value);
4092 // ByteArray represents fixed sized byte arrays. Used for the relocation info
4093 // that is attached to code objects.
4094 class ByteArray: public FixedArrayBase {
4098 // Setter and getter.
4099 inline byte get(int index);
4100 inline void set(int index, byte value);
4102 // Treat contents as an int array.
4103 inline int get_int(int index);
4105 static int SizeFor(int length) {
4106 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4108 // We use byte arrays for free blocks in the heap. Given a desired size in
4109 // bytes that is a multiple of the word size and big enough to hold a byte
4110 // array, this function returns the number of elements a byte array should
4112 static int LengthFor(int size_in_bytes) {
4113 DCHECK(IsAligned(size_in_bytes, kPointerSize));
4114 DCHECK(size_in_bytes >= kHeaderSize);
4115 return size_in_bytes - kHeaderSize;
4118 // Returns data start address.
4119 inline Address GetDataStartAddress();
4121 // Returns a pointer to the ByteArray object for a given data start address.
4122 static inline ByteArray* FromDataStartAddress(Address address);
4124 DECLARE_CAST(ByteArray)
4126 // Dispatched behavior.
4127 inline int ByteArraySize();
4128 DECLARE_PRINTER(ByteArray)
4129 DECLARE_VERIFIER(ByteArray)
4131 // Layout description.
4132 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4134 // Maximal memory consumption for a single ByteArray.
4135 static const int kMaxSize = 512 * MB;
4136 // Maximal length of a single ByteArray.
4137 static const int kMaxLength = kMaxSize - kHeaderSize;
4140 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4144 // BytecodeArray represents a sequence of interpreter bytecodes.
4145 class BytecodeArray : public FixedArrayBase {
4147 static int SizeFor(int length) {
4148 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4151 // Setter and getter
4152 inline byte get(int index);
4153 inline void set(int index, byte value);
4155 // Returns data start address.
4156 inline Address GetFirstBytecodeAddress();
4158 // Accessors for frame size.
4159 inline int frame_size() const;
4160 inline void set_frame_size(int frame_size);
4162 // Accessors for parameter count (including implicit 'this' receiver).
4163 inline int parameter_count() const;
4164 inline void set_parameter_count(int number_of_parameters);
4166 // Accessors for the constant pool.
4167 DECL_ACCESSORS(constant_pool, FixedArray)
4169 DECLARE_CAST(BytecodeArray)
4171 // Dispatched behavior.
4172 inline int BytecodeArraySize();
4173 inline void BytecodeArrayIterateBody(ObjectVisitor* v);
4175 DECLARE_PRINTER(BytecodeArray)
4176 DECLARE_VERIFIER(BytecodeArray)
4178 void Disassemble(std::ostream& os);
4180 // Layout description.
4181 static const int kFrameSizeOffset = FixedArrayBase::kHeaderSize;
4182 static const int kParameterSizeOffset = kFrameSizeOffset + kIntSize;
4183 static const int kConstantPoolOffset = kParameterSizeOffset + kIntSize;
4184 static const int kHeaderSize = kConstantPoolOffset + kPointerSize;
4186 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4188 // Maximal memory consumption for a single BytecodeArray.
4189 static const int kMaxSize = 512 * MB;
4190 // Maximal length of a single BytecodeArray.
4191 static const int kMaxLength = kMaxSize - kHeaderSize;
4194 DISALLOW_IMPLICIT_CONSTRUCTORS(BytecodeArray);
4198 // FreeSpace are fixed-size free memory blocks used by the heap and GC.
4199 // They look like heap objects (are heap object tagged and have a map) so that
4200 // the heap remains iterable. They have a size and a next pointer.
4201 // The next pointer is the raw address of the next FreeSpace object (or NULL)
4202 // in the free list.
4203 class FreeSpace: public HeapObject {
4205 // [size]: size of the free space including the header.
4206 inline int size() const;
4207 inline void set_size(int value);
4209 inline int nobarrier_size() const;
4210 inline void nobarrier_set_size(int value);
4214 // Accessors for the next field.
4215 inline FreeSpace* next();
4216 inline FreeSpace** next_address();
4217 inline void set_next(FreeSpace* next);
4219 inline static FreeSpace* cast(HeapObject* obj);
4221 // Dispatched behavior.
4222 DECLARE_PRINTER(FreeSpace)
4223 DECLARE_VERIFIER(FreeSpace)
4225 // Layout description.
4226 // Size is smi tagged when it is stored.
4227 static const int kSizeOffset = HeapObject::kHeaderSize;
4228 static const int kNextOffset = POINTER_SIZE_ALIGN(kSizeOffset + kPointerSize);
4231 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
4235 // V has parameters (Type, type, TYPE, C type, element_size)
4236 #define TYPED_ARRAYS(V) \
4237 V(Uint8, uint8, UINT8, uint8_t, 1) \
4238 V(Int8, int8, INT8, int8_t, 1) \
4239 V(Uint16, uint16, UINT16, uint16_t, 2) \
4240 V(Int16, int16, INT16, int16_t, 2) \
4241 V(Uint32, uint32, UINT32, uint32_t, 4) \
4242 V(Int32, int32, INT32, int32_t, 4) \
4243 V(Float32, float32, FLOAT32, float, 4) \
4244 V(Float64, float64, FLOAT64, double, 8) \
4245 V(Uint8Clamped, uint8_clamped, UINT8_CLAMPED, uint8_t, 1)
4248 class FixedTypedArrayBase: public FixedArrayBase {
4250 // [base_pointer]: Either points to the FixedTypedArrayBase itself or nullptr.
4251 DECL_ACCESSORS(base_pointer, Object)
4253 // [external_pointer]: Contains the offset between base_pointer and the start
4254 // of the data. If the base_pointer is a nullptr, the external_pointer
4255 // therefore points to the actual backing store.
4256 DECL_ACCESSORS(external_pointer, void)
4258 // Dispatched behavior.
4259 inline void FixedTypedArrayBaseIterateBody(ObjectVisitor* v);
4261 template <typename StaticVisitor>
4262 inline void FixedTypedArrayBaseIterateBody();
4264 DECLARE_CAST(FixedTypedArrayBase)
4266 static const int kBasePointerOffset = FixedArrayBase::kHeaderSize;
4267 static const int kExternalPointerOffset = kBasePointerOffset + kPointerSize;
4268 static const int kHeaderSize =
4269 DOUBLE_POINTER_ALIGN(kExternalPointerOffset + kPointerSize);
4271 static const int kDataOffset = kHeaderSize;
4275 static inline int TypedArraySize(InstanceType type, int length);
4276 inline int TypedArraySize(InstanceType type);
4278 // Use with care: returns raw pointer into heap.
4279 inline void* DataPtr();
4281 inline int DataSize();
4284 static inline int ElementSize(InstanceType type);
4286 inline int DataSize(InstanceType type);
4288 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
4292 template <class Traits>
4293 class FixedTypedArray: public FixedTypedArrayBase {
4295 typedef typename Traits::ElementType ElementType;
4296 static const InstanceType kInstanceType = Traits::kInstanceType;
4298 DECLARE_CAST(FixedTypedArray<Traits>)
4300 inline ElementType get_scalar(int index);
4301 static inline Handle<Object> get(Handle<FixedTypedArray> array, int index);
4302 inline void set(int index, ElementType value);
4304 static inline ElementType from_int(int value);
4305 static inline ElementType from_double(double value);
4307 // This accessor applies the correct conversion from Smi, HeapNumber
4309 inline void SetValue(uint32_t index, Object* value);
4311 DECLARE_PRINTER(FixedTypedArray)
4312 DECLARE_VERIFIER(FixedTypedArray)
4315 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
4318 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size) \
4319 class Type##ArrayTraits { \
4320 public: /* NOLINT */ \
4321 typedef elementType ElementType; \
4322 static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE; \
4323 static const char* Designator() { return #type " array"; } \
4324 static inline Handle<Object> ToHandle(Isolate* isolate, \
4325 elementType scalar); \
4326 static inline elementType defaultValue(); \
4329 typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
4331 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
4333 #undef FIXED_TYPED_ARRAY_TRAITS
4336 // DeoptimizationInputData is a fixed array used to hold the deoptimization
4337 // data for code generated by the Hydrogen/Lithium compiler. It also
4338 // contains information about functions that were inlined. If N different
4339 // functions were inlined then first N elements of the literal array will
4340 // contain these functions.
4343 class DeoptimizationInputData: public FixedArray {
4345 // Layout description. Indices in the array.
4346 static const int kTranslationByteArrayIndex = 0;
4347 static const int kInlinedFunctionCountIndex = 1;
4348 static const int kLiteralArrayIndex = 2;
4349 static const int kOsrAstIdIndex = 3;
4350 static const int kOsrPcOffsetIndex = 4;
4351 static const int kOptimizationIdIndex = 5;
4352 static const int kSharedFunctionInfoIndex = 6;
4353 static const int kWeakCellCacheIndex = 7;
4354 static const int kFirstDeoptEntryIndex = 8;
4356 // Offsets of deopt entry elements relative to the start of the entry.
4357 static const int kAstIdRawOffset = 0;
4358 static const int kTranslationIndexOffset = 1;
4359 static const int kArgumentsStackHeightOffset = 2;
4360 static const int kPcOffset = 3;
4361 static const int kDeoptEntrySize = 4;
4363 // Simple element accessors.
4364 #define DECLARE_ELEMENT_ACCESSORS(name, type) \
4365 inline type* name(); \
4366 inline void Set##name(type* value);
4368 DECLARE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
4369 DECLARE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
4370 DECLARE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
4371 DECLARE_ELEMENT_ACCESSORS(OsrAstId, Smi)
4372 DECLARE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
4373 DECLARE_ELEMENT_ACCESSORS(OptimizationId, Smi)
4374 DECLARE_ELEMENT_ACCESSORS(SharedFunctionInfo, Object)
4375 DECLARE_ELEMENT_ACCESSORS(WeakCellCache, Object)
4377 #undef DECLARE_ELEMENT_ACCESSORS
4379 // Accessors for elements of the ith deoptimization entry.
4380 #define DECLARE_ENTRY_ACCESSORS(name, type) \
4381 inline type* name(int i); \
4382 inline void Set##name(int i, type* value);
4384 DECLARE_ENTRY_ACCESSORS(AstIdRaw, Smi)
4385 DECLARE_ENTRY_ACCESSORS(TranslationIndex, Smi)
4386 DECLARE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
4387 DECLARE_ENTRY_ACCESSORS(Pc, Smi)
4389 #undef DECLARE_ENTRY_ACCESSORS
4391 inline BailoutId AstId(int i);
4393 inline void SetAstId(int i, BailoutId value);
4395 inline int DeoptCount();
4397 // Allocates a DeoptimizationInputData.
4398 static Handle<DeoptimizationInputData> New(Isolate* isolate,
4399 int deopt_entry_count,
4400 PretenureFlag pretenure);
4402 DECLARE_CAST(DeoptimizationInputData)
4404 #ifdef ENABLE_DISASSEMBLER
4405 void DeoptimizationInputDataPrint(std::ostream& os); // NOLINT
4409 static int IndexForEntry(int i) {
4410 return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
4414 static int LengthFor(int entry_count) { return IndexForEntry(entry_count); }
4418 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
4419 // data for code generated by the full compiler.
4420 // The format of the these objects is
4421 // [i * 2]: Ast ID for ith deoptimization.
4422 // [i * 2 + 1]: PC and state of ith deoptimization
4423 class DeoptimizationOutputData: public FixedArray {
4425 inline int DeoptPoints();
4427 inline BailoutId AstId(int index);
4429 inline void SetAstId(int index, BailoutId id);
4431 inline Smi* PcAndState(int index);
4432 inline void SetPcAndState(int index, Smi* offset);
4434 static int LengthOfFixedArray(int deopt_points) {
4435 return deopt_points * 2;
4438 // Allocates a DeoptimizationOutputData.
4439 static Handle<DeoptimizationOutputData> New(Isolate* isolate,
4440 int number_of_deopt_points,
4441 PretenureFlag pretenure);
4443 DECLARE_CAST(DeoptimizationOutputData)
4445 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4446 void DeoptimizationOutputDataPrint(std::ostream& os); // NOLINT
4451 // HandlerTable is a fixed array containing entries for exception handlers in
4452 // the code object it is associated with. The tables comes in two flavors:
4453 // 1) Based on ranges: Used for unoptimized code. Contains one entry per
4454 // exception handler and a range representing the try-block covered by that
4455 // handler. Layout looks as follows:
4456 // [ range-start , range-end , handler-offset , stack-depth ]
4457 // 2) Based on return addresses: Used for turbofanned code. Contains one entry
4458 // per call-site that could throw an exception. Layout looks as follows:
4459 // [ return-address-offset , handler-offset ]
4460 class HandlerTable : public FixedArray {
4462 // Conservative prediction whether a given handler will locally catch an
4463 // exception or cause a re-throw to outside the code boundary. Since this is
4464 // undecidable it is merely an approximation (e.g. useful for debugger).
4465 enum CatchPrediction { UNCAUGHT, CAUGHT };
4467 // Accessors for handler table based on ranges.
4468 inline void SetRangeStart(int index, int value);
4469 inline void SetRangeEnd(int index, int value);
4470 inline void SetRangeHandler(int index, int offset, CatchPrediction pred);
4471 inline void SetRangeDepth(int index, int value);
4473 // Accessors for handler table based on return addresses.
4474 inline void SetReturnOffset(int index, int value);
4475 inline void SetReturnHandler(int index, int offset, CatchPrediction pred);
4477 // Lookup handler in a table based on ranges.
4478 int LookupRange(int pc_offset, int* stack_depth, CatchPrediction* prediction);
4480 // Lookup handler in a table based on return addresses.
4481 int LookupReturn(int pc_offset, CatchPrediction* prediction);
4483 // Returns the required length of the underlying fixed array.
4484 static int LengthForRange(int entries) { return entries * kRangeEntrySize; }
4485 static int LengthForReturn(int entries) { return entries * kReturnEntrySize; }
4487 DECLARE_CAST(HandlerTable)
4489 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4490 void HandlerTableRangePrint(std::ostream& os); // NOLINT
4491 void HandlerTableReturnPrint(std::ostream& os); // NOLINT
4495 // Layout description for handler table based on ranges.
4496 static const int kRangeStartIndex = 0;
4497 static const int kRangeEndIndex = 1;
4498 static const int kRangeHandlerIndex = 2;
4499 static const int kRangeDepthIndex = 3;
4500 static const int kRangeEntrySize = 4;
4502 // Layout description for handler table based on return addresses.
4503 static const int kReturnOffsetIndex = 0;
4504 static const int kReturnHandlerIndex = 1;
4505 static const int kReturnEntrySize = 2;
4507 // Encoding of the {handler} field.
4508 class HandlerPredictionField : public BitField<CatchPrediction, 0, 1> {};
4509 class HandlerOffsetField : public BitField<int, 1, 30> {};
4513 // Code describes objects with on-the-fly generated machine code.
4514 class Code: public HeapObject {
4516 // Opaque data type for encapsulating code flags like kind, inline
4517 // cache state, and arguments count.
4518 typedef uint32_t Flags;
4520 #define NON_IC_KIND_LIST(V) \
4522 V(OPTIMIZED_FUNCTION) \
4529 #define IC_KIND_LIST(V) \
4540 #define CODE_KIND_LIST(V) \
4541 NON_IC_KIND_LIST(V) \
4545 #define DEFINE_CODE_KIND_ENUM(name) name,
4546 CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
4547 #undef DEFINE_CODE_KIND_ENUM
4551 // No more than 16 kinds. The value is currently encoded in four bits in
4553 STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
4555 static const char* Kind2String(Kind kind);
4563 static const int kPrologueOffsetNotSet = -1;
4565 #ifdef ENABLE_DISASSEMBLER
4567 static const char* ICState2String(InlineCacheState state);
4568 static const char* StubType2String(StubType type);
4569 static void PrintExtraICState(std::ostream& os, // NOLINT
4570 Kind kind, ExtraICState extra);
4571 void Disassemble(const char* name, std::ostream& os); // NOLINT
4572 #endif // ENABLE_DISASSEMBLER
4574 // [instruction_size]: Size of the native instructions
4575 inline int instruction_size() const;
4576 inline void set_instruction_size(int value);
4578 // [relocation_info]: Code relocation information
4579 DECL_ACCESSORS(relocation_info, ByteArray)
4580 void InvalidateRelocation();
4581 void InvalidateEmbeddedObjects();
4583 // [handler_table]: Fixed array containing offsets of exception handlers.
4584 DECL_ACCESSORS(handler_table, FixedArray)
4586 // [deoptimization_data]: Array containing data for deopt.
4587 DECL_ACCESSORS(deoptimization_data, FixedArray)
4589 // [raw_type_feedback_info]: This field stores various things, depending on
4590 // the kind of the code object.
4591 // FUNCTION => type feedback information.
4592 // STUB and ICs => major/minor key as Smi.
4593 DECL_ACCESSORS(raw_type_feedback_info, Object)
4594 inline Object* type_feedback_info();
4595 inline void set_type_feedback_info(
4596 Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
4597 inline uint32_t stub_key();
4598 inline void set_stub_key(uint32_t key);
4600 // [next_code_link]: Link for lists of optimized or deoptimized code.
4601 // Note that storage for this field is overlapped with typefeedback_info.
4602 DECL_ACCESSORS(next_code_link, Object)
4604 // [gc_metadata]: Field used to hold GC related metadata. The contents of this
4605 // field does not have to be traced during garbage collection since
4606 // it is only used by the garbage collector itself.
4607 DECL_ACCESSORS(gc_metadata, Object)
4609 // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
4610 // at the moment when this object was created.
4611 inline void set_ic_age(int count);
4612 inline int ic_age() const;
4614 // [prologue_offset]: Offset of the function prologue, used for aging
4615 // FUNCTIONs and OPTIMIZED_FUNCTIONs.
4616 inline int prologue_offset() const;
4617 inline void set_prologue_offset(int offset);
4619 // [constant_pool offset]: Offset of the constant pool.
4620 // Valid for FLAG_enable_embedded_constant_pool only
4621 inline int constant_pool_offset() const;
4622 inline void set_constant_pool_offset(int offset);
4624 // Unchecked accessors to be used during GC.
4625 inline ByteArray* unchecked_relocation_info();
4627 inline int relocation_size();
4629 // [flags]: Various code flags.
4630 inline Flags flags();
4631 inline void set_flags(Flags flags);
4633 // [flags]: Access to specific code flags.
4635 inline InlineCacheState ic_state(); // Only valid for IC stubs.
4636 inline ExtraICState extra_ic_state(); // Only valid for IC stubs.
4638 inline StubType type(); // Only valid for monomorphic IC stubs.
4640 // Testers for IC stub kinds.
4641 inline bool is_inline_cache_stub();
4642 inline bool is_debug_stub();
4643 inline bool is_handler();
4644 inline bool is_load_stub();
4645 inline bool is_keyed_load_stub();
4646 inline bool is_store_stub();
4647 inline bool is_keyed_store_stub();
4648 inline bool is_call_stub();
4649 inline bool is_binary_op_stub();
4650 inline bool is_compare_ic_stub();
4651 inline bool is_compare_nil_ic_stub();
4652 inline bool is_to_boolean_ic_stub();
4653 inline bool is_keyed_stub();
4654 inline bool is_optimized_code();
4655 inline bool embeds_maps_weakly();
4657 inline bool IsCodeStubOrIC();
4658 inline bool IsJavaScriptCode();
4660 inline void set_raw_kind_specific_flags1(int value);
4661 inline void set_raw_kind_specific_flags2(int value);
4663 // [is_crankshafted]: For kind STUB or ICs, tells whether or not a code
4664 // object was generated by either the hydrogen or the TurboFan optimizing
4665 // compiler (but it may not be an optimized function).
4666 inline bool is_crankshafted();
4667 inline bool is_hydrogen_stub(); // Crankshafted, but not a function.
4668 inline void set_is_crankshafted(bool value);
4670 // [is_turbofanned]: For kind STUB or OPTIMIZED_FUNCTION, tells whether the
4671 // code object was generated by the TurboFan optimizing compiler.
4672 inline bool is_turbofanned();
4673 inline void set_is_turbofanned(bool value);
4675 // [can_have_weak_objects]: For kind OPTIMIZED_FUNCTION, tells whether the
4676 // embedded objects in code should be treated weakly.
4677 inline bool can_have_weak_objects();
4678 inline void set_can_have_weak_objects(bool value);
4680 // [has_deoptimization_support]: For FUNCTION kind, tells if it has
4681 // deoptimization support.
4682 inline bool has_deoptimization_support();
4683 inline void set_has_deoptimization_support(bool value);
4685 // [has_debug_break_slots]: For FUNCTION kind, tells if it has
4686 // been compiled with debug break slots.
4687 inline bool has_debug_break_slots();
4688 inline void set_has_debug_break_slots(bool value);
4690 // [has_reloc_info_for_serialization]: For FUNCTION kind, tells if its
4691 // reloc info includes runtime and external references to support
4692 // serialization/deserialization.
4693 inline bool has_reloc_info_for_serialization();
4694 inline void set_has_reloc_info_for_serialization(bool value);
4696 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
4697 // how long the function has been marked for OSR and therefore which
4698 // level of loop nesting we are willing to do on-stack replacement
4700 inline void set_allow_osr_at_loop_nesting_level(int level);
4701 inline int allow_osr_at_loop_nesting_level();
4703 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
4704 // the code object was seen on the stack with no IC patching going on.
4705 inline int profiler_ticks();
4706 inline void set_profiler_ticks(int ticks);
4708 // [builtin_index]: For BUILTIN kind, tells which builtin index it has.
4709 // For builtins, tells which builtin index it has.
4710 // Note that builtins can have a code kind other than BUILTIN, which means
4711 // that for arbitrary code objects, this index value may be random garbage.
4712 // To verify in that case, compare the code object to the indexed builtin.
4713 inline int builtin_index();
4714 inline void set_builtin_index(int id);
4716 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
4717 // reserved in the code prologue.
4718 inline unsigned stack_slots();
4719 inline void set_stack_slots(unsigned slots);
4721 // [safepoint_table_start]: For kind OPTIMIZED_FUNCTION, the offset in
4722 // the instruction stream where the safepoint table starts.
4723 inline unsigned safepoint_table_offset();
4724 inline void set_safepoint_table_offset(unsigned offset);
4726 // [back_edge_table_start]: For kind FUNCTION, the offset in the
4727 // instruction stream where the back edge table starts.
4728 inline unsigned back_edge_table_offset();
4729 inline void set_back_edge_table_offset(unsigned offset);
4731 inline bool back_edges_patched_for_osr();
4733 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
4734 inline uint16_t to_boolean_state();
4736 // [has_function_cache]: For kind STUB tells whether there is a function
4737 // cache is passed to the stub.
4738 inline bool has_function_cache();
4739 inline void set_has_function_cache(bool flag);
4742 // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
4743 // the code is going to be deoptimized because of dead embedded maps.
4744 inline bool marked_for_deoptimization();
4745 inline void set_marked_for_deoptimization(bool flag);
4747 // [constant_pool]: The constant pool for this function.
4748 inline Address constant_pool();
4750 // Get the safepoint entry for the given pc.
4751 SafepointEntry GetSafepointEntry(Address pc);
4753 // Find an object in a stub with a specified map
4754 Object* FindNthObject(int n, Map* match_map);
4756 // Find the first allocation site in an IC stub.
4757 AllocationSite* FindFirstAllocationSite();
4759 // Find the first map in an IC stub.
4760 Map* FindFirstMap();
4761 void FindAllMaps(MapHandleList* maps);
4763 // Find the first handler in an IC stub.
4764 Code* FindFirstHandler();
4766 // Find |length| handlers and put them into |code_list|. Returns false if not
4767 // enough handlers can be found.
4768 bool FindHandlers(CodeHandleList* code_list, int length = -1);
4770 // Find the handler for |map|.
4771 MaybeHandle<Code> FindHandlerForMap(Map* map);
4773 // Find the first name in an IC stub.
4774 Name* FindFirstName();
4776 class FindAndReplacePattern;
4777 // For each (map-to-find, object-to-replace) pair in the pattern, this
4778 // function replaces the corresponding placeholder in the code with the
4779 // object-to-replace. The function assumes that pairs in the pattern come in
4780 // the same order as the placeholders in the code.
4781 // If the placeholder is a weak cell, then the value of weak cell is matched
4782 // against the map-to-find.
4783 void FindAndReplace(const FindAndReplacePattern& pattern);
4785 // The entire code object including its header is copied verbatim to the
4786 // snapshot so that it can be written in one, fast, memcpy during
4787 // deserialization. The deserializer will overwrite some pointers, rather
4788 // like a runtime linker, but the random allocation addresses used in the
4789 // mksnapshot process would still be present in the unlinked snapshot data,
4790 // which would make snapshot production non-reproducible. This method wipes
4791 // out the to-be-overwritten header data for reproducible snapshots.
4792 inline void WipeOutHeader();
4794 // Flags operations.
4795 static inline Flags ComputeFlags(
4796 Kind kind, InlineCacheState ic_state = UNINITIALIZED,
4797 ExtraICState extra_ic_state = kNoExtraICState, StubType type = NORMAL,
4798 CacheHolderFlag holder = kCacheOnReceiver);
4800 static inline Flags ComputeMonomorphicFlags(
4801 Kind kind, ExtraICState extra_ic_state = kNoExtraICState,
4802 CacheHolderFlag holder = kCacheOnReceiver, StubType type = NORMAL);
4804 static inline Flags ComputeHandlerFlags(
4805 Kind handler_kind, StubType type = NORMAL,
4806 CacheHolderFlag holder = kCacheOnReceiver);
4808 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
4809 static inline StubType ExtractTypeFromFlags(Flags flags);
4810 static inline CacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
4811 static inline Kind ExtractKindFromFlags(Flags flags);
4812 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
4814 static inline Flags RemoveTypeFromFlags(Flags flags);
4815 static inline Flags RemoveTypeAndHolderFromFlags(Flags flags);
4817 // Convert a target address into a code object.
4818 static inline Code* GetCodeFromTargetAddress(Address address);
4820 // Convert an entry address into an object.
4821 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
4823 // Returns the address of the first instruction.
4824 inline byte* instruction_start();
4826 // Returns the address right after the last instruction.
4827 inline byte* instruction_end();
4829 // Returns the size of the instructions, padding, and relocation information.
4830 inline int body_size();
4832 // Returns the address of the first relocation info (read backwards!).
4833 inline byte* relocation_start();
4835 // Code entry point.
4836 inline byte* entry();
4838 // Returns true if pc is inside this object's instructions.
4839 inline bool contains(byte* pc);
4841 // Relocate the code by delta bytes. Called to signal that this code
4842 // object has been moved by delta bytes.
4843 void Relocate(intptr_t delta);
4845 // Migrate code described by desc.
4846 void CopyFrom(const CodeDesc& desc);
4848 // Returns the object size for a given body (used for allocation).
4849 static int SizeFor(int body_size) {
4850 DCHECK_SIZE_TAG_ALIGNED(body_size);
4851 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
4854 // Calculate the size of the code object to report for log events. This takes
4855 // the layout of the code object into account.
4856 inline int ExecutableSize();
4858 // Locating source position.
4859 int SourcePosition(Address pc);
4860 int SourceStatementPosition(Address pc);
4864 // Dispatched behavior.
4865 inline int CodeSize();
4866 inline void CodeIterateBody(ObjectVisitor* v);
4868 template<typename StaticVisitor>
4869 inline void CodeIterateBody(Heap* heap);
4871 DECLARE_PRINTER(Code)
4872 DECLARE_VERIFIER(Code)
4874 void ClearInlineCaches();
4875 void ClearInlineCaches(Kind kind);
4877 BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
4878 uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
4880 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
4882 kToBeExecutedOnceCodeAge = -3,
4883 kNotExecutedCodeAge = -2,
4884 kExecutedOnceCodeAge = -1,
4886 CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
4888 kFirstCodeAge = kToBeExecutedOnceCodeAge,
4889 kLastCodeAge = kAfterLastCodeAge - 1,
4890 kCodeAgeCount = kAfterLastCodeAge - kFirstCodeAge - 1,
4891 kIsOldCodeAge = kSexagenarianCodeAge,
4892 kPreAgedCodeAge = kIsOldCodeAge - 1
4894 #undef DECLARE_CODE_AGE_ENUM
4896 // Code aging. Indicates how many full GCs this code has survived without
4897 // being entered through the prologue. Used to determine when it is
4898 // relatively safe to flush this code object and replace it with the lazy
4899 // compilation stub.
4900 static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
4901 static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
4902 void MakeYoung(Isolate* isolate);
4903 void MarkToBeExecutedOnce(Isolate* isolate);
4904 void MakeOlder(MarkingParity);
4905 static bool IsYoungSequence(Isolate* isolate, byte* sequence);
4908 static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
4909 return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
4912 void PrintDeoptLocation(FILE* out, Address pc);
4913 bool CanDeoptAt(Address pc);
4916 void VerifyEmbeddedObjectsDependency();
4920 enum VerifyMode { kNoContextSpecificPointers, kNoContextRetainingPointers };
4921 void VerifyEmbeddedObjects(VerifyMode mode = kNoContextRetainingPointers);
4922 static void VerifyRecompiledCode(Code* old_code, Code* new_code);
4925 inline bool CanContainWeakObjects();
4927 inline bool IsWeakObject(Object* object);
4929 static inline bool IsWeakObjectInOptimizedCode(Object* object);
4931 static Handle<WeakCell> WeakCellFor(Handle<Code> code);
4932 WeakCell* CachedWeakCell();
4934 // Max loop nesting marker used to postpose OSR. We don't take loop
4935 // nesting that is deeper than 5 levels into account.
4936 static const int kMaxLoopNestingMarker = 6;
4938 static const int kConstantPoolSize =
4939 FLAG_enable_embedded_constant_pool ? kIntSize : 0;
4941 // Layout description.
4942 static const int kRelocationInfoOffset = HeapObject::kHeaderSize;
4943 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
4944 static const int kDeoptimizationDataOffset =
4945 kHandlerTableOffset + kPointerSize;
4946 // For FUNCTION kind, we store the type feedback info here.
4947 static const int kTypeFeedbackInfoOffset =
4948 kDeoptimizationDataOffset + kPointerSize;
4949 static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
4950 static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
4951 static const int kInstructionSizeOffset = kGCMetadataOffset + kPointerSize;
4952 static const int kICAgeOffset = kInstructionSizeOffset + kIntSize;
4953 static const int kFlagsOffset = kICAgeOffset + kIntSize;
4954 static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
4955 static const int kKindSpecificFlags2Offset =
4956 kKindSpecificFlags1Offset + kIntSize;
4957 // Note: We might be able to squeeze this into the flags above.
4958 static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
4959 static const int kConstantPoolOffset = kPrologueOffset + kIntSize;
4960 static const int kHeaderPaddingStart =
4961 kConstantPoolOffset + kConstantPoolSize;
4963 // Add padding to align the instruction start following right after
4964 // the Code object header.
4965 static const int kHeaderSize =
4966 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
4968 // Byte offsets within kKindSpecificFlags1Offset.
4969 static const int kFullCodeFlags = kKindSpecificFlags1Offset;
4970 class FullCodeFlagsHasDeoptimizationSupportField:
4971 public BitField<bool, 0, 1> {}; // NOLINT
4972 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
4973 class FullCodeFlagsHasRelocInfoForSerialization
4974 : public BitField<bool, 2, 1> {};
4975 // Bit 3 in this bitfield is unused.
4976 class ProfilerTicksField : public BitField<int, 4, 28> {};
4978 // Flags layout. BitField<type, shift, size>.
4979 class ICStateField : public BitField<InlineCacheState, 0, 4> {};
4980 class TypeField : public BitField<StubType, 4, 1> {};
4981 class CacheHolderField : public BitField<CacheHolderFlag, 5, 2> {};
4982 class KindField : public BitField<Kind, 7, 4> {};
4983 class ExtraICStateField: public BitField<ExtraICState, 11,
4984 PlatformSmiTagging::kSmiValueSize - 11 + 1> {}; // NOLINT
4986 // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
4987 static const int kStackSlotsFirstBit = 0;
4988 static const int kStackSlotsBitCount = 24;
4989 static const int kHasFunctionCacheBit =
4990 kStackSlotsFirstBit + kStackSlotsBitCount;
4991 static const int kMarkedForDeoptimizationBit = kHasFunctionCacheBit + 1;
4992 static const int kIsTurbofannedBit = kMarkedForDeoptimizationBit + 1;
4993 static const int kCanHaveWeakObjects = kIsTurbofannedBit + 1;
4995 STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
4996 STATIC_ASSERT(kCanHaveWeakObjects + 1 <= 32);
4998 class StackSlotsField: public BitField<int,
4999 kStackSlotsFirstBit, kStackSlotsBitCount> {}; // NOLINT
5000 class HasFunctionCacheField : public BitField<bool, kHasFunctionCacheBit, 1> {
5002 class MarkedForDeoptimizationField
5003 : public BitField<bool, kMarkedForDeoptimizationBit, 1> {}; // NOLINT
5004 class IsTurbofannedField : public BitField<bool, kIsTurbofannedBit, 1> {
5006 class CanHaveWeakObjectsField
5007 : public BitField<bool, kCanHaveWeakObjects, 1> {}; // NOLINT
5009 // KindSpecificFlags2 layout (ALL)
5010 static const int kIsCrankshaftedBit = 0;
5011 class IsCrankshaftedField: public BitField<bool,
5012 kIsCrankshaftedBit, 1> {}; // NOLINT
5014 // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
5015 static const int kSafepointTableOffsetFirstBit = kIsCrankshaftedBit + 1;
5016 static const int kSafepointTableOffsetBitCount = 30;
5018 STATIC_ASSERT(kSafepointTableOffsetFirstBit +
5019 kSafepointTableOffsetBitCount <= 32);
5020 STATIC_ASSERT(1 + kSafepointTableOffsetBitCount <= 32);
5022 class SafepointTableOffsetField: public BitField<int,
5023 kSafepointTableOffsetFirstBit,
5024 kSafepointTableOffsetBitCount> {}; // NOLINT
5026 // KindSpecificFlags2 layout (FUNCTION)
5027 class BackEdgeTableOffsetField: public BitField<int,
5028 kIsCrankshaftedBit + 1, 27> {}; // NOLINT
5029 class AllowOSRAtLoopNestingLevelField: public BitField<int,
5030 kIsCrankshaftedBit + 1 + 27, 4> {}; // NOLINT
5031 STATIC_ASSERT(AllowOSRAtLoopNestingLevelField::kMax >= kMaxLoopNestingMarker);
5033 static const int kArgumentsBits = 16;
5034 static const int kMaxArguments = (1 << kArgumentsBits) - 1;
5036 // This constant should be encodable in an ARM instruction.
5037 static const int kFlagsNotUsedInLookup =
5038 TypeField::kMask | CacheHolderField::kMask;
5041 friend class RelocIterator;
5042 friend class Deoptimizer; // For FindCodeAgeSequence.
5044 void ClearInlineCaches(Kind* kind);
5047 byte* FindCodeAgeSequence();
5048 static void GetCodeAgeAndParity(Code* code, Age* age,
5049 MarkingParity* parity);
5050 static void GetCodeAgeAndParity(Isolate* isolate, byte* sequence, Age* age,
5051 MarkingParity* parity);
5052 static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
5054 // Code aging -- platform-specific
5055 static void PatchPlatformCodeAge(Isolate* isolate,
5056 byte* sequence, Age age,
5057 MarkingParity parity);
5059 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5063 // This class describes the layout of dependent codes array of a map. The
5064 // array is partitioned into several groups of dependent codes. Each group
5065 // contains codes with the same dependency on the map. The array has the
5066 // following layout for n dependency groups:
5068 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5069 // | C1 | C2 | ... | Cn | group 1 | group 2 | ... | group n | undefined |
5070 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5072 // The first n elements are Smis, each of them specifies the number of codes
5073 // in the corresponding group. The subsequent elements contain grouped code
5074 // objects in weak cells. The suffix of the array can be filled with the
5075 // undefined value if the number of codes is less than the length of the
5076 // array. The order of the code objects within a group is not preserved.
5078 // All code indexes used in the class are counted starting from the first
5079 // code object of the first group. In other words, code index 0 corresponds
5080 // to array index n = kCodesStartIndex.
5082 class DependentCode: public FixedArray {
5084 enum DependencyGroup {
5085 // Group of code that weakly embed this map and depend on being
5086 // deoptimized when the map is garbage collected.
5088 // Group of code that embed a transition to this map, and depend on being
5089 // deoptimized when the transition is replaced by a new version.
5091 // Group of code that omit run-time prototype checks for prototypes
5092 // described by this map. The group is deoptimized whenever an object
5093 // described by this map changes shape (and transitions to a new map),
5094 // possibly invalidating the assumptions embedded in the code.
5095 kPrototypeCheckGroup,
5096 // Group of code that depends on global property values in property cells
5097 // not being changed.
5098 kPropertyCellChangedGroup,
5099 // Group of code that omit run-time type checks for the field(s) introduced
5102 // Group of code that omit run-time type checks for initial maps of
5104 kInitialMapChangedGroup,
5105 // Group of code that depends on tenuring information in AllocationSites
5106 // not being changed.
5107 kAllocationSiteTenuringChangedGroup,
5108 // Group of code that depends on element transition information in
5109 // AllocationSites not being changed.
5110 kAllocationSiteTransitionChangedGroup
5113 static const int kGroupCount = kAllocationSiteTransitionChangedGroup + 1;
5115 // Array for holding the index of the first code object of each group.
5116 // The last element stores the total number of code objects.
5117 class GroupStartIndexes {
5119 explicit GroupStartIndexes(DependentCode* entries);
5120 void Recompute(DependentCode* entries);
5121 int at(int i) { return start_indexes_[i]; }
5122 int number_of_entries() { return start_indexes_[kGroupCount]; }
5124 int start_indexes_[kGroupCount + 1];
5127 bool Contains(DependencyGroup group, WeakCell* code_cell);
5129 static Handle<DependentCode> InsertCompilationDependencies(
5130 Handle<DependentCode> entries, DependencyGroup group,
5131 Handle<Foreign> info);
5133 static Handle<DependentCode> InsertWeakCode(Handle<DependentCode> entries,
5134 DependencyGroup group,
5135 Handle<WeakCell> code_cell);
5137 void UpdateToFinishedCode(DependencyGroup group, Foreign* info,
5138 WeakCell* code_cell);
5140 void RemoveCompilationDependencies(DependentCode::DependencyGroup group,
5143 void DeoptimizeDependentCodeGroup(Isolate* isolate,
5144 DependentCode::DependencyGroup group);
5146 bool MarkCodeForDeoptimization(Isolate* isolate,
5147 DependentCode::DependencyGroup group);
5149 // The following low-level accessors should only be used by this class
5150 // and the mark compact collector.
5151 inline int number_of_entries(DependencyGroup group);
5152 inline void set_number_of_entries(DependencyGroup group, int value);
5153 inline Object* object_at(int i);
5154 inline void set_object_at(int i, Object* object);
5155 inline void clear_at(int i);
5156 inline void copy(int from, int to);
5157 DECLARE_CAST(DependentCode)
5159 static const char* DependencyGroupName(DependencyGroup group);
5160 static void SetMarkedForDeoptimization(Code* code, DependencyGroup group);
5163 static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5164 DependencyGroup group,
5165 Handle<Object> object);
5166 static Handle<DependentCode> EnsureSpace(Handle<DependentCode> entries);
5167 // Make a room at the end of the given group by moving out the first
5168 // code objects of the subsequent groups.
5169 inline void ExtendGroup(DependencyGroup group);
5170 // Compact by removing cleared weak cells and return true if there was
5171 // any cleared weak cell.
5173 static int Grow(int number_of_entries) {
5174 if (number_of_entries < 5) return number_of_entries + 1;
5175 return number_of_entries * 5 / 4;
5177 static const int kCodesStartIndex = kGroupCount;
5181 class PrototypeInfo;
5184 // All heap objects have a Map that describes their structure.
5185 // A Map contains information about:
5186 // - Size information about the object
5187 // - How to iterate over an object (for garbage collection)
5188 class Map: public HeapObject {
5191 // Size in bytes or kVariableSizeSentinel if instances do not have
5193 inline int instance_size();
5194 inline void set_instance_size(int value);
5196 // Only to clear an unused byte, remove once byte is used.
5197 inline void clear_unused();
5199 // [inobject_properties_or_constructor_function_index]: Provides access
5200 // to the inobject properties in case of JSObject maps, or the constructor
5201 // function index in case of primitive maps.
5202 inline int inobject_properties_or_constructor_function_index();
5203 inline void set_inobject_properties_or_constructor_function_index(int value);
5204 // Count of properties allocated in the object (JSObject only).
5205 inline int GetInObjectProperties();
5206 inline void SetInObjectProperties(int value);
5207 // Index of the constructor function in the native context (primitives only),
5208 // or the special sentinel value to indicate that there is no object wrapper
5209 // for the primitive (i.e. in case of null or undefined).
5210 static const int kNoConstructorFunctionIndex = 0;
5211 inline int GetConstructorFunctionIndex();
5212 inline void SetConstructorFunctionIndex(int value);
5215 inline InstanceType instance_type();
5216 inline void set_instance_type(InstanceType value);
5218 // Tells how many unused property fields are available in the
5219 // instance (only used for JSObject in fast mode).
5220 inline int unused_property_fields();
5221 inline void set_unused_property_fields(int value);
5224 inline byte bit_field() const;
5225 inline void set_bit_field(byte value);
5228 inline byte bit_field2() const;
5229 inline void set_bit_field2(byte value);
5232 inline uint32_t bit_field3() const;
5233 inline void set_bit_field3(uint32_t bits);
5235 class EnumLengthBits: public BitField<int,
5236 0, kDescriptorIndexBitCount> {}; // NOLINT
5237 class NumberOfOwnDescriptorsBits: public BitField<int,
5238 kDescriptorIndexBitCount, kDescriptorIndexBitCount> {}; // NOLINT
5239 STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
5240 class DictionaryMap : public BitField<bool, 20, 1> {};
5241 class OwnsDescriptors : public BitField<bool, 21, 1> {};
5242 class IsHiddenPrototype : public BitField<bool, 22, 1> {};
5243 class Deprecated : public BitField<bool, 23, 1> {};
5244 class IsUnstable : public BitField<bool, 24, 1> {};
5245 class IsMigrationTarget : public BitField<bool, 25, 1> {};
5246 class IsStrong : public BitField<bool, 26, 1> {};
5249 // Keep this bit field at the very end for better code in
5250 // Builtins::kJSConstructStubGeneric stub.
5251 // This counter is used for in-object slack tracking and for map aging.
5252 // The in-object slack tracking is considered enabled when the counter is
5253 // in the range [kSlackTrackingCounterStart, kSlackTrackingCounterEnd].
5254 class Counter : public BitField<int, 28, 4> {};
5255 static const int kSlackTrackingCounterStart = 14;
5256 static const int kSlackTrackingCounterEnd = 8;
5257 static const int kRetainingCounterStart = kSlackTrackingCounterEnd - 1;
5258 static const int kRetainingCounterEnd = 0;
5260 // Tells whether the object in the prototype property will be used
5261 // for instances created from this function. If the prototype
5262 // property is set to a value that is not a JSObject, the prototype
5263 // property will not be used to create instances of the function.
5264 // See ECMA-262, 13.2.2.
5265 inline void set_non_instance_prototype(bool value);
5266 inline bool has_non_instance_prototype();
5268 // Tells whether function has special prototype property. If not, prototype
5269 // property will not be created when accessed (will return undefined),
5270 // and construction from this function will not be allowed.
5271 inline void set_function_with_prototype(bool value);
5272 inline bool function_with_prototype();
5274 // Tells whether the instance with this map should be ignored by the
5275 // Object.getPrototypeOf() function and the __proto__ accessor.
5276 inline void set_is_hidden_prototype();
5277 inline bool is_hidden_prototype() const;
5279 // Records and queries whether the instance has a named interceptor.
5280 inline void set_has_named_interceptor();
5281 inline bool has_named_interceptor();
5283 // Records and queries whether the instance has an indexed interceptor.
5284 inline void set_has_indexed_interceptor();
5285 inline bool has_indexed_interceptor();
5287 // Tells whether the instance is undetectable.
5288 // An undetectable object is a special class of JSObject: 'typeof' operator
5289 // returns undefined, ToBoolean returns false. Otherwise it behaves like
5290 // a normal JS object. It is useful for implementing undetectable
5291 // document.all in Firefox & Safari.
5292 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
5293 inline void set_is_undetectable();
5294 inline bool is_undetectable();
5296 // Tells whether the instance has a call-as-function handler.
5297 inline void set_is_observed();
5298 inline bool is_observed();
5300 // Tells whether the instance has a [[Call]] internal field.
5301 // This property is implemented according to ES6, section 7.2.3.
5302 inline void set_is_callable();
5303 inline bool is_callable() const;
5305 inline void set_is_strong();
5306 inline bool is_strong();
5307 inline void set_is_extensible(bool value);
5308 inline bool is_extensible();
5309 inline void set_is_prototype_map(bool value);
5310 inline bool is_prototype_map() const;
5312 inline void set_elements_kind(ElementsKind elements_kind);
5313 inline ElementsKind elements_kind();
5315 // Tells whether the instance has fast elements that are only Smis.
5316 inline bool has_fast_smi_elements();
5318 // Tells whether the instance has fast elements.
5319 inline bool has_fast_object_elements();
5320 inline bool has_fast_smi_or_object_elements();
5321 inline bool has_fast_double_elements();
5322 inline bool has_fast_elements();
5323 inline bool has_sloppy_arguments_elements();
5324 inline bool has_fixed_typed_array_elements();
5325 inline bool has_dictionary_elements();
5327 static bool IsValidElementsTransition(ElementsKind from_kind,
5328 ElementsKind to_kind);
5330 // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
5331 // map with DICTIONARY_ELEMENTS was found in the prototype chain.
5332 bool DictionaryElementsInPrototypeChainOnly();
5334 inline Map* ElementsTransitionMap();
5336 inline FixedArrayBase* GetInitialElements();
5338 // [raw_transitions]: Provides access to the transitions storage field.
5339 // Don't call set_raw_transitions() directly to overwrite transitions, use
5340 // the TransitionArray::ReplaceTransitions() wrapper instead!
5341 DECL_ACCESSORS(raw_transitions, Object)
5342 // [prototype_info]: Per-prototype metadata. Aliased with transitions
5343 // (which prototype maps don't have).
5344 DECL_ACCESSORS(prototype_info, Object)
5345 // PrototypeInfo is created lazily using this helper (which installs it on
5346 // the given prototype's map).
5347 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5348 Handle<JSObject> prototype, Isolate* isolate);
5349 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5350 Handle<Map> prototype_map, Isolate* isolate);
5352 // [prototype chain validity cell]: Associated with a prototype object,
5353 // stored in that object's map's PrototypeInfo, indicates that prototype
5354 // chains through this object are currently valid. The cell will be
5355 // invalidated and replaced when the prototype chain changes.
5356 static Handle<Cell> GetOrCreatePrototypeChainValidityCell(Handle<Map> map,
5358 static const int kPrototypeChainValid = 0;
5359 static const int kPrototypeChainInvalid = 1;
5362 Map* FindFieldOwner(int descriptor);
5364 inline int GetInObjectPropertyOffset(int index);
5366 int NumberOfFields();
5368 // TODO(ishell): candidate with JSObject::MigrateToMap().
5369 bool InstancesNeedRewriting(Map* target, int target_number_of_fields,
5370 int target_inobject, int target_unused,
5371 int* old_number_of_fields);
5372 // TODO(ishell): moveit!
5373 static Handle<Map> GeneralizeAllFieldRepresentations(Handle<Map> map);
5374 MUST_USE_RESULT static Handle<HeapType> GeneralizeFieldType(
5375 Handle<HeapType> type1,
5376 Handle<HeapType> type2,
5378 static void GeneralizeFieldType(Handle<Map> map, int modify_index,
5379 Representation new_representation,
5380 Handle<HeapType> new_field_type);
5381 static Handle<Map> ReconfigureProperty(Handle<Map> map, int modify_index,
5382 PropertyKind new_kind,
5383 PropertyAttributes new_attributes,
5384 Representation new_representation,
5385 Handle<HeapType> new_field_type,
5386 StoreMode store_mode);
5387 static Handle<Map> CopyGeneralizeAllRepresentations(
5388 Handle<Map> map, int modify_index, StoreMode store_mode,
5389 PropertyKind kind, PropertyAttributes attributes, const char* reason);
5391 static Handle<Map> PrepareForDataProperty(Handle<Map> old_map,
5392 int descriptor_number,
5393 Handle<Object> value);
5395 static Handle<Map> Normalize(Handle<Map> map, PropertyNormalizationMode mode,
5396 const char* reason);
5398 // Returns the constructor name (the name (possibly, inferred name) of the
5399 // function that was used to instantiate the object).
5400 String* constructor_name();
5402 // Tells whether the map is used for JSObjects in dictionary mode (ie
5403 // normalized objects, ie objects for which HasFastProperties returns false).
5404 // A map can never be used for both dictionary mode and fast mode JSObjects.
5405 // False by default and for HeapObjects that are not JSObjects.
5406 inline void set_dictionary_map(bool value);
5407 inline bool is_dictionary_map();
5409 // Tells whether the instance needs security checks when accessing its
5411 inline void set_is_access_check_needed(bool access_check_needed);
5412 inline bool is_access_check_needed();
5414 // Returns true if map has a non-empty stub code cache.
5415 inline bool has_code_cache();
5417 // [prototype]: implicit prototype object.
5418 DECL_ACCESSORS(prototype, Object)
5419 // TODO(jkummerow): make set_prototype private.
5420 static void SetPrototype(
5421 Handle<Map> map, Handle<Object> prototype,
5422 PrototypeOptimizationMode proto_mode = FAST_PROTOTYPE);
5424 // [constructor]: points back to the function responsible for this map.
5425 // The field overlaps with the back pointer. All maps in a transition tree
5426 // have the same constructor, so maps with back pointers can walk the
5427 // back pointer chain until they find the map holding their constructor.
5428 DECL_ACCESSORS(constructor_or_backpointer, Object)
5429 inline Object* GetConstructor() const;
5430 inline void SetConstructor(Object* constructor,
5431 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5432 // [back pointer]: points back to the parent map from which a transition
5433 // leads to this map. The field overlaps with the constructor (see above).
5434 inline Object* GetBackPointer();
5435 inline void SetBackPointer(Object* value,
5436 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5438 // [instance descriptors]: describes the object.
5439 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
5441 // [layout descriptor]: describes the object layout.
5442 DECL_ACCESSORS(layout_descriptor, LayoutDescriptor)
5443 // |layout descriptor| accessor which can be used from GC.
5444 inline LayoutDescriptor* layout_descriptor_gc_safe();
5445 inline bool HasFastPointerLayout() const;
5447 // |layout descriptor| accessor that is safe to call even when
5448 // FLAG_unbox_double_fields is disabled (in this case Map does not contain
5449 // |layout_descriptor| field at all).
5450 inline LayoutDescriptor* GetLayoutDescriptor();
5452 inline void UpdateDescriptors(DescriptorArray* descriptors,
5453 LayoutDescriptor* layout_descriptor);
5454 inline void InitializeDescriptors(DescriptorArray* descriptors,
5455 LayoutDescriptor* layout_descriptor);
5457 // [stub cache]: contains stubs compiled for this map.
5458 DECL_ACCESSORS(code_cache, Object)
5460 // [dependent code]: list of optimized codes that weakly embed this map.
5461 DECL_ACCESSORS(dependent_code, DependentCode)
5463 // [weak cell cache]: cache that stores a weak cell pointing to this map.
5464 DECL_ACCESSORS(weak_cell_cache, Object)
5466 inline PropertyDetails GetLastDescriptorDetails();
5468 inline int LastAdded();
5470 inline int NumberOfOwnDescriptors();
5471 inline void SetNumberOfOwnDescriptors(int number);
5473 inline Cell* RetrieveDescriptorsPointer();
5475 inline int EnumLength();
5476 inline void SetEnumLength(int length);
5478 inline bool owns_descriptors();
5479 inline void set_owns_descriptors(bool owns_descriptors);
5480 inline void mark_unstable();
5481 inline bool is_stable();
5482 inline void set_migration_target(bool value);
5483 inline bool is_migration_target();
5484 inline void set_counter(int value);
5485 inline int counter();
5486 inline void deprecate();
5487 inline bool is_deprecated();
5488 inline bool CanBeDeprecated();
5489 // Returns a non-deprecated version of the input. If the input was not
5490 // deprecated, it is directly returned. Otherwise, the non-deprecated version
5491 // is found by re-transitioning from the root of the transition tree using the
5492 // descriptor array of the map. Returns MaybeHandle<Map>() if no updated map
5494 static MaybeHandle<Map> TryUpdate(Handle<Map> map) WARN_UNUSED_RESULT;
5496 // Returns a non-deprecated version of the input. This method may deprecate
5497 // existing maps along the way if encodings conflict. Not for use while
5498 // gathering type feedback. Use TryUpdate in those cases instead.
5499 static Handle<Map> Update(Handle<Map> map);
5501 static Handle<Map> CopyDropDescriptors(Handle<Map> map);
5502 static Handle<Map> CopyInsertDescriptor(Handle<Map> map,
5503 Descriptor* descriptor,
5504 TransitionFlag flag);
5506 MUST_USE_RESULT static MaybeHandle<Map> CopyWithField(
5509 Handle<HeapType> type,
5510 PropertyAttributes attributes,
5511 Representation representation,
5512 TransitionFlag flag);
5514 MUST_USE_RESULT static MaybeHandle<Map> CopyWithConstant(
5517 Handle<Object> constant,
5518 PropertyAttributes attributes,
5519 TransitionFlag flag);
5521 // Returns a new map with all transitions dropped from the given map and
5522 // the ElementsKind set.
5523 static Handle<Map> TransitionElementsTo(Handle<Map> map,
5524 ElementsKind to_kind);
5526 static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
5528 static Handle<Map> CopyAsElementsKind(Handle<Map> map,
5530 TransitionFlag flag);
5532 static Handle<Map> CopyForObserved(Handle<Map> map);
5534 static Handle<Map> CopyForPreventExtensions(Handle<Map> map,
5535 PropertyAttributes attrs_to_add,
5536 Handle<Symbol> transition_marker,
5537 const char* reason);
5539 static Handle<Map> FixProxy(Handle<Map> map, InstanceType type, int size);
5542 // Maximal number of fast properties. Used to restrict the number of map
5543 // transitions to avoid an explosion in the number of maps for objects used as
5545 inline bool TooManyFastProperties(StoreFromKeyed store_mode);
5546 static Handle<Map> TransitionToDataProperty(Handle<Map> map,
5548 Handle<Object> value,
5549 PropertyAttributes attributes,
5550 StoreFromKeyed store_mode);
5551 static Handle<Map> TransitionToAccessorProperty(
5552 Handle<Map> map, Handle<Name> name, AccessorComponent component,
5553 Handle<Object> accessor, PropertyAttributes attributes);
5554 static Handle<Map> ReconfigureExistingProperty(Handle<Map> map,
5557 PropertyAttributes attributes);
5559 inline void AppendDescriptor(Descriptor* desc);
5561 // Returns a copy of the map, prepared for inserting into the transition
5562 // tree (if the |map| owns descriptors then the new one will share
5563 // descriptors with |map|).
5564 static Handle<Map> CopyForTransition(Handle<Map> map, const char* reason);
5566 // Returns a copy of the map, with all transitions dropped from the
5567 // instance descriptors.
5568 static Handle<Map> Copy(Handle<Map> map, const char* reason);
5569 static Handle<Map> Create(Isolate* isolate, int inobject_properties);
5571 // Returns the next free property index (only valid for FAST MODE).
5572 int NextFreePropertyIndex();
5574 // Returns the number of properties described in instance_descriptors
5575 // filtering out properties with the specified attributes.
5576 int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
5577 PropertyAttributes filter = NONE);
5581 // Code cache operations.
5583 // Clears the code cache.
5584 inline void ClearCodeCache(Heap* heap);
5586 // Update code cache.
5587 static void UpdateCodeCache(Handle<Map> map,
5591 // Extend the descriptor array of the map with the list of descriptors.
5592 // In case of duplicates, the latest descriptor is used.
5593 static void AppendCallbackDescriptors(Handle<Map> map,
5594 Handle<Object> descriptors);
5596 static inline int SlackForArraySize(int old_size, int size_limit);
5598 static void EnsureDescriptorSlack(Handle<Map> map, int slack);
5600 // Returns the found code or undefined if absent.
5601 Object* FindInCodeCache(Name* name, Code::Flags flags);
5603 // Returns the non-negative index of the code object if it is in the
5604 // cache and -1 otherwise.
5605 int IndexInCodeCache(Object* name, Code* code);
5607 // Removes a code object from the code cache at the given index.
5608 void RemoveFromCodeCache(Name* name, Code* code, int index);
5610 // Computes a hash value for this map, to be used in HashTables and such.
5613 // Returns the map that this map transitions to if its elements_kind
5614 // is changed to |elements_kind|, or NULL if no such map is cached yet.
5615 // |safe_to_add_transitions| is set to false if adding transitions is not
5617 Map* LookupElementsTransitionMap(ElementsKind elements_kind);
5619 // Returns the transitioned map for this map with the most generic
5620 // elements_kind that's found in |candidates|, or null handle if no match is
5622 static Handle<Map> FindTransitionedMap(Handle<Map> map,
5623 MapHandleList* candidates);
5625 inline bool CanTransition();
5627 inline bool IsPrimitiveMap();
5628 inline bool IsJSObjectMap();
5629 inline bool IsJSArrayMap();
5630 inline bool IsStringMap();
5631 inline bool IsJSProxyMap();
5632 inline bool IsJSGlobalProxyMap();
5633 inline bool IsJSGlobalObjectMap();
5634 inline bool IsGlobalObjectMap();
5636 inline bool CanOmitMapChecks();
5638 static void AddDependentCode(Handle<Map> map,
5639 DependentCode::DependencyGroup group,
5642 bool IsMapInArrayPrototypeChain();
5644 static Handle<WeakCell> WeakCellForMap(Handle<Map> map);
5646 // Dispatched behavior.
5647 DECLARE_PRINTER(Map)
5648 DECLARE_VERIFIER(Map)
5651 void DictionaryMapVerify();
5652 void VerifyOmittedMapChecks();
5655 inline int visitor_id();
5656 inline void set_visitor_id(int visitor_id);
5658 static Handle<Map> TransitionToPrototype(Handle<Map> map,
5659 Handle<Object> prototype,
5660 PrototypeOptimizationMode mode);
5662 static const int kMaxPreAllocatedPropertyFields = 255;
5664 // Layout description.
5665 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
5666 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
5667 static const int kBitField3Offset = kInstanceAttributesOffset + kIntSize;
5668 static const int kPrototypeOffset = kBitField3Offset + kPointerSize;
5669 static const int kConstructorOrBackPointerOffset =
5670 kPrototypeOffset + kPointerSize;
5671 // When there is only one transition, it is stored directly in this field;
5672 // otherwise a transition array is used.
5673 // For prototype maps, this slot is used to store this map's PrototypeInfo
5675 static const int kTransitionsOrPrototypeInfoOffset =
5676 kConstructorOrBackPointerOffset + kPointerSize;
5677 static const int kDescriptorsOffset =
5678 kTransitionsOrPrototypeInfoOffset + kPointerSize;
5679 #if V8_DOUBLE_FIELDS_UNBOXING
5680 static const int kLayoutDecriptorOffset = kDescriptorsOffset + kPointerSize;
5681 static const int kCodeCacheOffset = kLayoutDecriptorOffset + kPointerSize;
5683 static const int kLayoutDecriptorOffset = 1; // Must not be ever accessed.
5684 static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
5686 static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
5687 static const int kWeakCellCacheOffset = kDependentCodeOffset + kPointerSize;
5688 static const int kSize = kWeakCellCacheOffset + kPointerSize;
5690 // Layout of pointer fields. Heap iteration code relies on them
5691 // being continuously allocated.
5692 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
5693 static const int kPointerFieldsEndOffset = kSize;
5695 // Byte offsets within kInstanceSizesOffset.
5696 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
5697 static const int kInObjectPropertiesOrConstructorFunctionIndexByte = 1;
5698 static const int kInObjectPropertiesOrConstructorFunctionIndexOffset =
5699 kInstanceSizesOffset + kInObjectPropertiesOrConstructorFunctionIndexByte;
5700 // Note there is one byte available for use here.
5701 static const int kUnusedByte = 2;
5702 static const int kUnusedOffset = kInstanceSizesOffset + kUnusedByte;
5703 static const int kVisitorIdByte = 3;
5704 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
5706 // Byte offsets within kInstanceAttributesOffset attributes.
5707 #if V8_TARGET_LITTLE_ENDIAN
5708 // Order instance type and bit field together such that they can be loaded
5709 // together as a 16-bit word with instance type in the lower 8 bits regardless
5710 // of endianess. Also provide endian-independent offset to that 16-bit word.
5711 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
5712 static const int kBitFieldOffset = kInstanceAttributesOffset + 1;
5714 static const int kBitFieldOffset = kInstanceAttributesOffset + 0;
5715 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 1;
5717 static const int kInstanceTypeAndBitFieldOffset =
5718 kInstanceAttributesOffset + 0;
5719 static const int kBitField2Offset = kInstanceAttributesOffset + 2;
5720 static const int kUnusedPropertyFieldsByte = 3;
5721 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 3;
5723 STATIC_ASSERT(kInstanceTypeAndBitFieldOffset ==
5724 Internals::kMapInstanceTypeAndBitFieldOffset);
5726 // Bit positions for bit field.
5727 static const int kHasNonInstancePrototype = 0;
5728 static const int kIsCallable = 1;
5729 static const int kHasNamedInterceptor = 2;
5730 static const int kHasIndexedInterceptor = 3;
5731 static const int kIsUndetectable = 4;
5732 static const int kIsObserved = 5;
5733 static const int kIsAccessCheckNeeded = 6;
5734 class FunctionWithPrototype: public BitField<bool, 7, 1> {};
5736 // Bit positions for bit field 2
5737 static const int kIsExtensible = 0;
5738 static const int kStringWrapperSafeForDefaultValueOf = 1;
5739 class IsPrototypeMapBits : public BitField<bool, 2, 1> {};
5740 class ElementsKindBits: public BitField<ElementsKind, 3, 5> {};
5742 // Derived values from bit field 2
5743 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
5744 (FAST_ELEMENTS + 1) << Map::ElementsKindBits::kShift) - 1;
5745 static const int8_t kMaximumBitField2FastSmiElementValue =
5746 static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
5747 Map::ElementsKindBits::kShift) - 1;
5748 static const int8_t kMaximumBitField2FastHoleyElementValue =
5749 static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
5750 Map::ElementsKindBits::kShift) - 1;
5751 static const int8_t kMaximumBitField2FastHoleySmiElementValue =
5752 static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
5753 Map::ElementsKindBits::kShift) - 1;
5755 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
5756 kPointerFieldsEndOffset,
5757 kSize> BodyDescriptor;
5759 // Compares this map to another to see if they describe equivalent objects.
5760 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
5761 // it had exactly zero inobject properties.
5762 // The "shared" flags of both this map and |other| are ignored.
5763 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
5765 // Returns true if given field is unboxed double.
5766 inline bool IsUnboxedDoubleField(FieldIndex index);
5769 static void TraceTransition(const char* what, Map* from, Map* to, Name* name);
5770 static void TraceAllTransitions(Map* map);
5773 static inline Handle<Map> CopyInstallDescriptorsForTesting(
5774 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5775 Handle<LayoutDescriptor> layout_descriptor);
5778 static void ConnectTransition(Handle<Map> parent, Handle<Map> child,
5779 Handle<Name> name, SimpleTransitionFlag flag);
5781 bool EquivalentToForTransition(Map* other);
5782 static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
5783 static Handle<Map> ShareDescriptor(Handle<Map> map,
5784 Handle<DescriptorArray> descriptors,
5785 Descriptor* descriptor);
5786 static Handle<Map> CopyInstallDescriptors(
5787 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5788 Handle<LayoutDescriptor> layout_descriptor);
5789 static Handle<Map> CopyAddDescriptor(Handle<Map> map,
5790 Descriptor* descriptor,
5791 TransitionFlag flag);
5792 static Handle<Map> CopyReplaceDescriptors(
5793 Handle<Map> map, Handle<DescriptorArray> descriptors,
5794 Handle<LayoutDescriptor> layout_descriptor, TransitionFlag flag,
5795 MaybeHandle<Name> maybe_name, const char* reason,
5796 SimpleTransitionFlag simple_flag);
5798 static Handle<Map> CopyReplaceDescriptor(Handle<Map> map,
5799 Handle<DescriptorArray> descriptors,
5800 Descriptor* descriptor,
5802 TransitionFlag flag);
5803 static MUST_USE_RESULT MaybeHandle<Map> TryReconfigureExistingProperty(
5804 Handle<Map> map, int descriptor, PropertyKind kind,
5805 PropertyAttributes attributes, const char** reason);
5807 static Handle<Map> CopyNormalized(Handle<Map> map,
5808 PropertyNormalizationMode mode);
5810 // Fires when the layout of an object with a leaf map changes.
5811 // This includes adding transitions to the leaf map or changing
5812 // the descriptor array.
5813 inline void NotifyLeafMapLayoutChange();
5815 void DeprecateTransitionTree();
5816 bool DeprecateTarget(PropertyKind kind, Name* key,
5817 PropertyAttributes attributes,
5818 DescriptorArray* new_descriptors,
5819 LayoutDescriptor* new_layout_descriptor);
5821 Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
5823 // Update field type of the given descriptor to new representation and new
5824 // type. The type must be prepared for storing in descriptor array:
5825 // it must be either a simple type or a map wrapped in a weak cell.
5826 void UpdateFieldType(int descriptor_number, Handle<Name> name,
5827 Representation new_representation,
5828 Handle<Object> new_wrapped_type);
5830 void PrintReconfiguration(FILE* file, int modify_index, PropertyKind kind,
5831 PropertyAttributes attributes);
5832 void PrintGeneralization(FILE* file,
5837 bool constant_to_field,
5838 Representation old_representation,
5839 Representation new_representation,
5840 HeapType* old_field_type,
5841 HeapType* new_field_type);
5843 static const int kFastPropertiesSoftLimit = 12;
5844 static const int kMaxFastProperties = 128;
5846 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
5850 // An abstract superclass, a marker class really, for simple structure classes.
5851 // It doesn't carry much functionality but allows struct classes to be
5852 // identified in the type system.
5853 class Struct: public HeapObject {
5855 inline void InitializeBody(int object_size);
5856 DECLARE_CAST(Struct)
5860 // A simple one-element struct, useful where smis need to be boxed.
5861 class Box : public Struct {
5863 // [value]: the boxed contents.
5864 DECL_ACCESSORS(value, Object)
5868 // Dispatched behavior.
5869 DECLARE_PRINTER(Box)
5870 DECLARE_VERIFIER(Box)
5872 static const int kValueOffset = HeapObject::kHeaderSize;
5873 static const int kSize = kValueOffset + kPointerSize;
5876 DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
5880 // Container for metadata stored on each prototype map.
5881 class PrototypeInfo : public Struct {
5883 static const int UNREGISTERED = -1;
5885 // [prototype_users]: WeakFixedArray containing maps using this prototype,
5886 // or Smi(0) if uninitialized.
5887 DECL_ACCESSORS(prototype_users, Object)
5888 // [registry_slot]: Slot in prototype's user registry where this user
5889 // is stored. Returns UNREGISTERED if this prototype has not been registered.
5890 inline int registry_slot() const;
5891 inline void set_registry_slot(int slot);
5892 // [validity_cell]: Cell containing the validity bit for prototype chains
5893 // going through this object, or Smi(0) if uninitialized.
5894 DECL_ACCESSORS(validity_cell, Object)
5895 // [constructor_name]: User-friendly name of the original constructor.
5896 DECL_ACCESSORS(constructor_name, Object)
5898 DECLARE_CAST(PrototypeInfo)
5900 // Dispatched behavior.
5901 DECLARE_PRINTER(PrototypeInfo)
5902 DECLARE_VERIFIER(PrototypeInfo)
5904 static const int kPrototypeUsersOffset = HeapObject::kHeaderSize;
5905 static const int kRegistrySlotOffset = kPrototypeUsersOffset + kPointerSize;
5906 static const int kValidityCellOffset = kRegistrySlotOffset + kPointerSize;
5907 static const int kConstructorNameOffset = kValidityCellOffset + kPointerSize;
5908 static const int kSize = kConstructorNameOffset + kPointerSize;
5911 DISALLOW_IMPLICIT_CONSTRUCTORS(PrototypeInfo);
5915 // Pair used to store both a ScopeInfo and an extension object in the extension
5916 // slot of a block context. Needed in the rare case where a declaration block
5917 // scope (a "varblock" as used to desugar parameter destructuring) also contains
5918 // a sloppy direct eval. (In no other case both are needed at the same time.)
5919 class SloppyBlockWithEvalContextExtension : public Struct {
5921 // [scope_info]: Scope info.
5922 DECL_ACCESSORS(scope_info, ScopeInfo)
5923 // [extension]: Extension object.
5924 DECL_ACCESSORS(extension, JSObject)
5926 DECLARE_CAST(SloppyBlockWithEvalContextExtension)
5928 // Dispatched behavior.
5929 DECLARE_PRINTER(SloppyBlockWithEvalContextExtension)
5930 DECLARE_VERIFIER(SloppyBlockWithEvalContextExtension)
5932 static const int kScopeInfoOffset = HeapObject::kHeaderSize;
5933 static const int kExtensionOffset = kScopeInfoOffset + kPointerSize;
5934 static const int kSize = kExtensionOffset + kPointerSize;
5937 DISALLOW_IMPLICIT_CONSTRUCTORS(SloppyBlockWithEvalContextExtension);
5941 // Script describes a script which has been added to the VM.
5942 class Script: public Struct {
5951 // Script compilation types.
5952 enum CompilationType {
5953 COMPILATION_TYPE_HOST = 0,
5954 COMPILATION_TYPE_EVAL = 1
5957 // Script compilation state.
5958 enum CompilationState {
5959 COMPILATION_STATE_INITIAL = 0,
5960 COMPILATION_STATE_COMPILED = 1
5963 // [source]: the script source.
5964 DECL_ACCESSORS(source, Object)
5966 // [name]: the script name.
5967 DECL_ACCESSORS(name, Object)
5969 // [id]: the script id.
5970 DECL_ACCESSORS(id, Smi)
5972 // [line_offset]: script line offset in resource from where it was extracted.
5973 DECL_ACCESSORS(line_offset, Smi)
5975 // [column_offset]: script column offset in resource from where it was
5977 DECL_ACCESSORS(column_offset, Smi)
5979 // [context_data]: context data for the context this script was compiled in.
5980 DECL_ACCESSORS(context_data, Object)
5982 // [wrapper]: the wrapper cache. This is either undefined or a WeakCell.
5983 DECL_ACCESSORS(wrapper, HeapObject)
5985 // [type]: the script type.
5986 DECL_ACCESSORS(type, Smi)
5988 // [line_ends]: FixedArray of line ends positions.
5989 DECL_ACCESSORS(line_ends, Object)
5991 // [eval_from_shared]: for eval scripts the shared funcion info for the
5992 // function from which eval was called.
5993 DECL_ACCESSORS(eval_from_shared, Object)
5995 // [eval_from_instructions_offset]: the instruction offset in the code for the
5996 // function from which eval was called where eval was called.
5997 DECL_ACCESSORS(eval_from_instructions_offset, Smi)
5999 // [shared_function_infos]: weak fixed array containing all shared
6000 // function infos created from this script.
6001 DECL_ACCESSORS(shared_function_infos, Object)
6003 // [flags]: Holds an exciting bitfield.
6004 DECL_ACCESSORS(flags, Smi)
6006 // [source_url]: sourceURL from magic comment
6007 DECL_ACCESSORS(source_url, Object)
6009 // [source_url]: sourceMappingURL magic comment
6010 DECL_ACCESSORS(source_mapping_url, Object)
6012 // [compilation_type]: how the the script was compiled. Encoded in the
6014 inline CompilationType compilation_type();
6015 inline void set_compilation_type(CompilationType type);
6017 // [compilation_state]: determines whether the script has already been
6018 // compiled. Encoded in the 'flags' field.
6019 inline CompilationState compilation_state();
6020 inline void set_compilation_state(CompilationState state);
6022 // [hide_source]: determines whether the script source can be exposed as
6023 // function source. Encoded in the 'flags' field.
6024 inline bool hide_source();
6025 inline void set_hide_source(bool value);
6027 // [origin_options]: optional attributes set by the embedder via ScriptOrigin,
6028 // and used by the embedder to make decisions about the script. V8 just passes
6029 // this through. Encoded in the 'flags' field.
6030 inline v8::ScriptOriginOptions origin_options();
6031 inline void set_origin_options(ScriptOriginOptions origin_options);
6033 DECLARE_CAST(Script)
6035 // If script source is an external string, check that the underlying
6036 // resource is accessible. Otherwise, always return true.
6037 inline bool HasValidSource();
6039 // Convert code position into column number.
6040 static int GetColumnNumber(Handle<Script> script, int code_pos);
6042 // Convert code position into (zero-based) line number.
6043 // The non-handlified version does not allocate, but may be much slower.
6044 static int GetLineNumber(Handle<Script> script, int code_pos);
6045 int GetLineNumber(int code_pos);
6047 static Handle<Object> GetNameOrSourceURL(Handle<Script> script);
6049 // Init line_ends array with code positions of line ends inside script source.
6050 static void InitLineEnds(Handle<Script> script);
6052 // Get the JS object wrapping the given script; create it if none exists.
6053 static Handle<JSObject> GetWrapper(Handle<Script> script);
6055 // Look through the list of existing shared function infos to find one
6056 // that matches the function literal. Return empty handle if not found.
6057 MaybeHandle<SharedFunctionInfo> FindSharedFunctionInfo(FunctionLiteral* fun);
6059 // Iterate over all script objects on the heap.
6062 explicit Iterator(Isolate* isolate);
6066 WeakFixedArray::Iterator iterator_;
6067 DISALLOW_COPY_AND_ASSIGN(Iterator);
6070 // Dispatched behavior.
6071 DECLARE_PRINTER(Script)
6072 DECLARE_VERIFIER(Script)
6074 static const int kSourceOffset = HeapObject::kHeaderSize;
6075 static const int kNameOffset = kSourceOffset + kPointerSize;
6076 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
6077 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
6078 static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
6079 static const int kWrapperOffset = kContextOffset + kPointerSize;
6080 static const int kTypeOffset = kWrapperOffset + kPointerSize;
6081 static const int kLineEndsOffset = kTypeOffset + kPointerSize;
6082 static const int kIdOffset = kLineEndsOffset + kPointerSize;
6083 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
6084 static const int kEvalFrominstructionsOffsetOffset =
6085 kEvalFromSharedOffset + kPointerSize;
6086 static const int kSharedFunctionInfosOffset =
6087 kEvalFrominstructionsOffsetOffset + kPointerSize;
6088 static const int kFlagsOffset = kSharedFunctionInfosOffset + kPointerSize;
6089 static const int kSourceUrlOffset = kFlagsOffset + kPointerSize;
6090 static const int kSourceMappingUrlOffset = kSourceUrlOffset + kPointerSize;
6091 static const int kSize = kSourceMappingUrlOffset + kPointerSize;
6094 int GetLineNumberWithArray(int code_pos);
6096 // Bit positions in the flags field.
6097 static const int kCompilationTypeBit = 0;
6098 static const int kCompilationStateBit = 1;
6099 static const int kHideSourceBit = 2;
6100 static const int kOriginOptionsShift = 3;
6101 static const int kOriginOptionsSize = 3;
6102 static const int kOriginOptionsMask = ((1 << kOriginOptionsSize) - 1)
6103 << kOriginOptionsShift;
6105 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6109 // List of builtin functions we want to identify to improve code
6112 // Each entry has a name of a global object property holding an object
6113 // optionally followed by ".prototype", a name of a builtin function
6114 // on the object (the one the id is set for), and a label.
6116 // Installation of ids for the selected builtin functions is handled
6117 // by the bootstrapper.
6118 #define FUNCTIONS_WITH_ID_LIST(V) \
6119 V(Array.prototype, indexOf, ArrayIndexOf) \
6120 V(Array.prototype, lastIndexOf, ArrayLastIndexOf) \
6121 V(Array.prototype, push, ArrayPush) \
6122 V(Array.prototype, pop, ArrayPop) \
6123 V(Array.prototype, shift, ArrayShift) \
6124 V(Function.prototype, apply, FunctionApply) \
6125 V(Function.prototype, call, FunctionCall) \
6126 V(String.prototype, charCodeAt, StringCharCodeAt) \
6127 V(String.prototype, charAt, StringCharAt) \
6128 V(String, fromCharCode, StringFromCharCode) \
6129 V(Math, random, MathRandom) \
6130 V(Math, floor, MathFloor) \
6131 V(Math, round, MathRound) \
6132 V(Math, ceil, MathCeil) \
6133 V(Math, abs, MathAbs) \
6134 V(Math, log, MathLog) \
6135 V(Math, exp, MathExp) \
6136 V(Math, sqrt, MathSqrt) \
6137 V(Math, pow, MathPow) \
6138 V(Math, max, MathMax) \
6139 V(Math, min, MathMin) \
6140 V(Math, cos, MathCos) \
6141 V(Math, sin, MathSin) \
6142 V(Math, tan, MathTan) \
6143 V(Math, acos, MathAcos) \
6144 V(Math, asin, MathAsin) \
6145 V(Math, atan, MathAtan) \
6146 V(Math, atan2, MathAtan2) \
6147 V(Math, imul, MathImul) \
6148 V(Math, clz32, MathClz32) \
6149 V(Math, fround, MathFround)
6151 #define ATOMIC_FUNCTIONS_WITH_ID_LIST(V) \
6152 V(Atomics, load, AtomicsLoad) \
6153 V(Atomics, store, AtomicsStore)
6155 enum BuiltinFunctionId {
6157 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
6159 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6160 ATOMIC_FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6161 #undef DECLARE_FUNCTION_ID
6162 // Fake id for a special case of Math.pow. Note, it continues the
6163 // list of math functions.
6168 // Result of searching in an optimized code map of a SharedFunctionInfo. Note
6169 // that both {code} and {literals} can be NULL to pass search result status.
6170 struct CodeAndLiterals {
6171 Code* code; // Cached optimized code.
6172 FixedArray* literals; // Cached literals array.
6176 // SharedFunctionInfo describes the JSFunction information that can be
6177 // shared by multiple instances of the function.
6178 class SharedFunctionInfo: public HeapObject {
6180 // [name]: Function name.
6181 DECL_ACCESSORS(name, Object)
6183 // [code]: Function code.
6184 DECL_ACCESSORS(code, Code)
6185 inline void ReplaceCode(Code* code);
6187 // [optimized_code_map]: Map from native context to optimized code
6188 // and a shared literals array or Smi(0) if none.
6189 DECL_ACCESSORS(optimized_code_map, Object)
6191 // Returns entry from optimized code map for specified context and OSR entry.
6192 // Note that {code == nullptr} indicates no matching entry has been found,
6193 // whereas {literals == nullptr} indicates the code is context-independent.
6194 CodeAndLiterals SearchOptimizedCodeMap(Context* native_context,
6195 BailoutId osr_ast_id);
6197 // Clear optimized code map.
6198 void ClearOptimizedCodeMap();
6200 // Removed a specific optimized code object from the optimized code map.
6201 void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
6203 // Trims the optimized code map after entries have been removed.
6204 void TrimOptimizedCodeMap(int shrink_by);
6206 // Add a new entry to the optimized code map for context-independent code.
6207 static void AddSharedCodeToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6210 // Add a new entry to the optimized code map for context-dependent code.
6211 static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6212 Handle<Context> native_context,
6214 Handle<FixedArray> literals,
6215 BailoutId osr_ast_id);
6217 // Set up the link between shared function info and the script. The shared
6218 // function info is added to the list on the script.
6219 static void SetScript(Handle<SharedFunctionInfo> shared,
6220 Handle<Object> script_object);
6222 // Layout description of the optimized code map.
6223 static const int kNextMapIndex = 0;
6224 static const int kSharedCodeIndex = 1;
6225 static const int kEntriesStart = 2;
6226 static const int kContextOffset = 0;
6227 static const int kCachedCodeOffset = 1;
6228 static const int kLiteralsOffset = 2;
6229 static const int kOsrAstIdOffset = 3;
6230 static const int kEntryLength = 4;
6231 static const int kInitialLength = kEntriesStart + kEntryLength;
6233 // [scope_info]: Scope info.
6234 DECL_ACCESSORS(scope_info, ScopeInfo)
6236 // [construct stub]: Code stub for constructing instances of this function.
6237 DECL_ACCESSORS(construct_stub, Code)
6239 // Returns if this function has been compiled to native code yet.
6240 inline bool is_compiled();
6242 // [length]: The function length - usually the number of declared parameters.
6243 // Use up to 2^30 parameters.
6244 inline int length() const;
6245 inline void set_length(int value);
6247 // [internal formal parameter count]: The declared number of parameters.
6248 // For subclass constructors, also includes new.target.
6249 // The size of function's frame is internal_formal_parameter_count + 1.
6250 inline int internal_formal_parameter_count() const;
6251 inline void set_internal_formal_parameter_count(int value);
6253 // Set the formal parameter count so the function code will be
6254 // called without using argument adaptor frames.
6255 inline void DontAdaptArguments();
6257 // [expected_nof_properties]: Expected number of properties for the function.
6258 inline int expected_nof_properties() const;
6259 inline void set_expected_nof_properties(int value);
6261 // [feedback_vector] - accumulates ast node feedback from full-codegen and
6262 // (increasingly) from crankshafted code where sufficient feedback isn't
6264 DECL_ACCESSORS(feedback_vector, TypeFeedbackVector)
6266 // Unconditionally clear the type feedback vector (including vector ICs).
6267 void ClearTypeFeedbackInfo();
6269 // Clear the type feedback vector with a more subtle policy at GC time.
6270 void ClearTypeFeedbackInfoAtGCTime();
6273 // [unique_id] - For --trace-maps purposes, an identifier that's persistent
6274 // even if the GC moves this SharedFunctionInfo.
6275 inline int unique_id() const;
6276 inline void set_unique_id(int value);
6279 // [instance class name]: class name for instances.
6280 DECL_ACCESSORS(instance_class_name, Object)
6282 // [function data]: This field holds some additional data for function.
6283 // Currently it has one of:
6284 // - a FunctionTemplateInfo to make benefit the API [IsApiFunction()].
6285 // - a Smi identifying a builtin function [HasBuiltinFunctionId()].
6286 // - a BytecodeArray for the interpreter [HasBytecodeArray()].
6287 // In the long run we don't want all functions to have this field but
6288 // we can fix that when we have a better model for storing hidden data
6290 DECL_ACCESSORS(function_data, Object)
6292 inline bool IsApiFunction();
6293 inline FunctionTemplateInfo* get_api_func_data();
6294 inline bool HasBuiltinFunctionId();
6295 inline BuiltinFunctionId builtin_function_id();
6296 inline bool HasBytecodeArray();
6297 inline BytecodeArray* bytecode_array();
6299 // [script info]: Script from which the function originates.
6300 DECL_ACCESSORS(script, Object)
6302 // [num_literals]: Number of literals used by this function.
6303 inline int num_literals() const;
6304 inline void set_num_literals(int value);
6306 // [start_position_and_type]: Field used to store both the source code
6307 // position, whether or not the function is a function expression,
6308 // and whether or not the function is a toplevel function. The two
6309 // least significants bit indicates whether the function is an
6310 // expression and the rest contains the source code position.
6311 inline int start_position_and_type() const;
6312 inline void set_start_position_and_type(int value);
6314 // The function is subject to debugging if a debug info is attached.
6315 inline bool HasDebugInfo();
6316 inline DebugInfo* GetDebugInfo();
6318 // A function has debug code if the compiled code has debug break slots.
6319 inline bool HasDebugCode();
6321 // [debug info]: Debug information.
6322 DECL_ACCESSORS(debug_info, Object)
6324 // [inferred name]: Name inferred from variable or property
6325 // assignment of this function. Used to facilitate debugging and
6326 // profiling of JavaScript code written in OO style, where almost
6327 // all functions are anonymous but are assigned to object
6329 DECL_ACCESSORS(inferred_name, String)
6331 // The function's name if it is non-empty, otherwise the inferred name.
6332 String* DebugName();
6334 // Position of the 'function' token in the script source.
6335 inline int function_token_position() const;
6336 inline void set_function_token_position(int function_token_position);
6338 // Position of this function in the script source.
6339 inline int start_position() const;
6340 inline void set_start_position(int start_position);
6342 // End position of this function in the script source.
6343 inline int end_position() const;
6344 inline void set_end_position(int end_position);
6346 // Is this function a function expression in the source code.
6347 DECL_BOOLEAN_ACCESSORS(is_expression)
6349 // Is this function a top-level function (scripts, evals).
6350 DECL_BOOLEAN_ACCESSORS(is_toplevel)
6352 // Bit field containing various information collected by the compiler to
6353 // drive optimization.
6354 inline int compiler_hints() const;
6355 inline void set_compiler_hints(int value);
6357 inline int ast_node_count() const;
6358 inline void set_ast_node_count(int count);
6360 inline int profiler_ticks() const;
6361 inline void set_profiler_ticks(int ticks);
6363 // Inline cache age is used to infer whether the function survived a context
6364 // disposal or not. In the former case we reset the opt_count.
6365 inline int ic_age();
6366 inline void set_ic_age(int age);
6368 // Indicates if this function can be lazy compiled.
6369 // This is used to determine if we can safely flush code from a function
6370 // when doing GC if we expect that the function will no longer be used.
6371 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
6373 // Indicates if this function can be lazy compiled without a context.
6374 // This is used to determine if we can force compilation without reaching
6375 // the function through program execution but through other means (e.g. heap
6376 // iteration by the debugger).
6377 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
6379 // Indicates whether optimizations have been disabled for this
6380 // shared function info. If a function is repeatedly optimized or if
6381 // we cannot optimize the function we disable optimization to avoid
6382 // spending time attempting to optimize it again.
6383 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
6385 // Indicates the language mode.
6386 inline LanguageMode language_mode();
6387 inline void set_language_mode(LanguageMode language_mode);
6389 // False if the function definitely does not allocate an arguments object.
6390 DECL_BOOLEAN_ACCESSORS(uses_arguments)
6392 // Indicates that this function uses a super property (or an eval that may
6393 // use a super property).
6394 // This is needed to set up the [[HomeObject]] on the function instance.
6395 DECL_BOOLEAN_ACCESSORS(needs_home_object)
6397 // True if the function has any duplicated parameter names.
6398 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
6400 // Indicates whether the function is a native function.
6401 // These needs special treatment in .call and .apply since
6402 // null passed as the receiver should not be translated to the
6404 DECL_BOOLEAN_ACCESSORS(native)
6406 // Indicate that this function should always be inlined in optimized code.
6407 DECL_BOOLEAN_ACCESSORS(force_inline)
6409 // Indicates that the function was created by the Function function.
6410 // Though it's anonymous, toString should treat it as if it had the name
6411 // "anonymous". We don't set the name itself so that the system does not
6412 // see a binding for it.
6413 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
6415 // Indicates whether the function is a bound function created using
6416 // the bind function.
6417 DECL_BOOLEAN_ACCESSORS(bound)
6419 // Indicates that the function is anonymous (the name field can be set
6420 // through the API, which does not change this flag).
6421 DECL_BOOLEAN_ACCESSORS(is_anonymous)
6423 // Is this a function or top-level/eval code.
6424 DECL_BOOLEAN_ACCESSORS(is_function)
6426 // Indicates that code for this function cannot be compiled with Crankshaft.
6427 DECL_BOOLEAN_ACCESSORS(dont_crankshaft)
6429 // Indicates that code for this function cannot be flushed.
6430 DECL_BOOLEAN_ACCESSORS(dont_flush)
6432 // Indicates that this function is a generator.
6433 DECL_BOOLEAN_ACCESSORS(is_generator)
6435 // Indicates that this function is an arrow function.
6436 DECL_BOOLEAN_ACCESSORS(is_arrow)
6438 // Indicates that this function is a concise method.
6439 DECL_BOOLEAN_ACCESSORS(is_concise_method)
6441 // Indicates that this function is an accessor (getter or setter).
6442 DECL_BOOLEAN_ACCESSORS(is_accessor_function)
6444 // Indicates that this function is a default constructor.
6445 DECL_BOOLEAN_ACCESSORS(is_default_constructor)
6447 // Indicates that this function is an asm function.
6448 DECL_BOOLEAN_ACCESSORS(asm_function)
6450 // Indicates that the the shared function info is deserialized from cache.
6451 DECL_BOOLEAN_ACCESSORS(deserialized)
6453 // Indicates that the the shared function info has never been compiled before.
6454 DECL_BOOLEAN_ACCESSORS(never_compiled)
6456 inline FunctionKind kind();
6457 inline void set_kind(FunctionKind kind);
6459 // Indicates whether or not the code in the shared function support
6461 inline bool has_deoptimization_support();
6463 // Enable deoptimization support through recompiled code.
6464 void EnableDeoptimizationSupport(Code* recompiled);
6466 // Disable (further) attempted optimization of all functions sharing this
6467 // shared function info.
6468 void DisableOptimization(BailoutReason reason);
6470 inline BailoutReason disable_optimization_reason();
6472 // Lookup the bailout ID and DCHECK that it exists in the non-optimized
6473 // code, returns whether it asserted (i.e., always true if assertions are
6475 bool VerifyBailoutId(BailoutId id);
6477 // [source code]: Source code for the function.
6478 bool HasSourceCode() const;
6479 Handle<Object> GetSourceCode();
6481 // Number of times the function was optimized.
6482 inline int opt_count();
6483 inline void set_opt_count(int opt_count);
6485 // Number of times the function was deoptimized.
6486 inline void set_deopt_count(int value);
6487 inline int deopt_count();
6488 inline void increment_deopt_count();
6490 // Number of time we tried to re-enable optimization after it
6491 // was disabled due to high number of deoptimizations.
6492 inline void set_opt_reenable_tries(int value);
6493 inline int opt_reenable_tries();
6495 inline void TryReenableOptimization();
6497 // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
6498 inline void set_counters(int value);
6499 inline int counters() const;
6501 // Stores opt_count and bailout_reason as bit-fields.
6502 inline void set_opt_count_and_bailout_reason(int value);
6503 inline int opt_count_and_bailout_reason() const;
6505 inline void set_disable_optimization_reason(BailoutReason reason);
6507 // Tells whether this function should be subject to debugging.
6508 inline bool IsSubjectToDebugging();
6510 // Whether this function is defined in native code or extensions.
6511 inline bool IsBuiltin();
6513 // Check whether or not this function is inlineable.
6514 bool IsInlineable();
6516 // Source size of this function.
6519 // Calculate the instance size.
6520 int CalculateInstanceSize();
6522 // Calculate the number of in-object properties.
6523 int CalculateInObjectProperties();
6525 inline bool has_simple_parameters();
6527 // Initialize a SharedFunctionInfo from a parsed function literal.
6528 static void InitFromFunctionLiteral(Handle<SharedFunctionInfo> shared_info,
6529 FunctionLiteral* lit);
6531 // Dispatched behavior.
6532 DECLARE_PRINTER(SharedFunctionInfo)
6533 DECLARE_VERIFIER(SharedFunctionInfo)
6535 void ResetForNewContext(int new_ic_age);
6537 // Iterate over all shared function infos that are created from a script.
6538 // That excludes shared function infos created for API functions and C++
6542 explicit Iterator(Isolate* isolate);
6543 SharedFunctionInfo* Next();
6548 Script::Iterator script_iterator_;
6549 WeakFixedArray::Iterator sfi_iterator_;
6550 DisallowHeapAllocation no_gc_;
6551 DISALLOW_COPY_AND_ASSIGN(Iterator);
6554 DECLARE_CAST(SharedFunctionInfo)
6557 static const int kDontAdaptArgumentsSentinel = -1;
6559 // Layout description.
6561 static const int kNameOffset = HeapObject::kHeaderSize;
6562 static const int kCodeOffset = kNameOffset + kPointerSize;
6563 static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
6564 static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
6565 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
6566 static const int kInstanceClassNameOffset =
6567 kConstructStubOffset + kPointerSize;
6568 static const int kFunctionDataOffset =
6569 kInstanceClassNameOffset + kPointerSize;
6570 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
6571 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
6572 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
6573 static const int kFeedbackVectorOffset =
6574 kInferredNameOffset + kPointerSize;
6576 static const int kUniqueIdOffset = kFeedbackVectorOffset + kPointerSize;
6577 static const int kLastPointerFieldOffset = kUniqueIdOffset;
6579 // Just to not break the postmortrem support with conditional offsets
6580 static const int kUniqueIdOffset = kFeedbackVectorOffset;
6581 static const int kLastPointerFieldOffset = kFeedbackVectorOffset;
6584 #if V8_HOST_ARCH_32_BIT
6586 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6587 static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
6588 static const int kExpectedNofPropertiesOffset =
6589 kFormalParameterCountOffset + kPointerSize;
6590 static const int kNumLiteralsOffset =
6591 kExpectedNofPropertiesOffset + kPointerSize;
6592 static const int kStartPositionAndTypeOffset =
6593 kNumLiteralsOffset + kPointerSize;
6594 static const int kEndPositionOffset =
6595 kStartPositionAndTypeOffset + kPointerSize;
6596 static const int kFunctionTokenPositionOffset =
6597 kEndPositionOffset + kPointerSize;
6598 static const int kCompilerHintsOffset =
6599 kFunctionTokenPositionOffset + kPointerSize;
6600 static const int kOptCountAndBailoutReasonOffset =
6601 kCompilerHintsOffset + kPointerSize;
6602 static const int kCountersOffset =
6603 kOptCountAndBailoutReasonOffset + kPointerSize;
6604 static const int kAstNodeCountOffset =
6605 kCountersOffset + kPointerSize;
6606 static const int kProfilerTicksOffset =
6607 kAstNodeCountOffset + kPointerSize;
6610 static const int kSize = kProfilerTicksOffset + kPointerSize;
6612 // The only reason to use smi fields instead of int fields
6613 // is to allow iteration without maps decoding during
6614 // garbage collections.
6615 // To avoid wasting space on 64-bit architectures we use
6616 // the following trick: we group integer fields into pairs
6617 // The least significant integer in each pair is shifted left by 1.
6618 // By doing this we guarantee that LSB of each kPointerSize aligned
6619 // word is not set and thus this word cannot be treated as pointer
6620 // to HeapObject during old space traversal.
6621 #if V8_TARGET_LITTLE_ENDIAN
6622 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6623 static const int kFormalParameterCountOffset =
6624 kLengthOffset + kIntSize;
6626 static const int kExpectedNofPropertiesOffset =
6627 kFormalParameterCountOffset + kIntSize;
6628 static const int kNumLiteralsOffset =
6629 kExpectedNofPropertiesOffset + kIntSize;
6631 static const int kEndPositionOffset =
6632 kNumLiteralsOffset + kIntSize;
6633 static const int kStartPositionAndTypeOffset =
6634 kEndPositionOffset + kIntSize;
6636 static const int kFunctionTokenPositionOffset =
6637 kStartPositionAndTypeOffset + kIntSize;
6638 static const int kCompilerHintsOffset =
6639 kFunctionTokenPositionOffset + kIntSize;
6641 static const int kOptCountAndBailoutReasonOffset =
6642 kCompilerHintsOffset + kIntSize;
6643 static const int kCountersOffset =
6644 kOptCountAndBailoutReasonOffset + kIntSize;
6646 static const int kAstNodeCountOffset =
6647 kCountersOffset + kIntSize;
6648 static const int kProfilerTicksOffset =
6649 kAstNodeCountOffset + kIntSize;
6652 static const int kSize = kProfilerTicksOffset + kIntSize;
6654 #elif V8_TARGET_BIG_ENDIAN
6655 static const int kFormalParameterCountOffset =
6656 kLastPointerFieldOffset + kPointerSize;
6657 static const int kLengthOffset = kFormalParameterCountOffset + kIntSize;
6659 static const int kNumLiteralsOffset = kLengthOffset + kIntSize;
6660 static const int kExpectedNofPropertiesOffset = kNumLiteralsOffset + kIntSize;
6662 static const int kStartPositionAndTypeOffset =
6663 kExpectedNofPropertiesOffset + kIntSize;
6664 static const int kEndPositionOffset = kStartPositionAndTypeOffset + kIntSize;
6666 static const int kCompilerHintsOffset = kEndPositionOffset + kIntSize;
6667 static const int kFunctionTokenPositionOffset =
6668 kCompilerHintsOffset + kIntSize;
6670 static const int kCountersOffset = kFunctionTokenPositionOffset + kIntSize;
6671 static const int kOptCountAndBailoutReasonOffset = kCountersOffset + kIntSize;
6673 static const int kProfilerTicksOffset =
6674 kOptCountAndBailoutReasonOffset + kIntSize;
6675 static const int kAstNodeCountOffset = kProfilerTicksOffset + kIntSize;
6678 static const int kSize = kAstNodeCountOffset + kIntSize;
6681 #error Unknown byte ordering
6682 #endif // Big endian
6686 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
6688 typedef FixedBodyDescriptor<kNameOffset,
6689 kLastPointerFieldOffset + kPointerSize,
6690 kSize> BodyDescriptor;
6692 // Bit positions in start_position_and_type.
6693 // The source code start position is in the 30 most significant bits of
6694 // the start_position_and_type field.
6695 static const int kIsExpressionBit = 0;
6696 static const int kIsTopLevelBit = 1;
6697 static const int kStartPositionShift = 2;
6698 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
6700 // Bit positions in compiler_hints.
6701 enum CompilerHints {
6702 kAllowLazyCompilation,
6703 kAllowLazyCompilationWithoutContext,
6704 kOptimizationDisabled,
6705 kStrictModeFunction,
6706 kStrongModeFunction,
6709 kHasDuplicateParameters,
6714 kNameShouldPrintAsAnonymous,
6721 kIsAccessorFunction,
6722 kIsDefaultConstructor,
6723 kIsSubclassConstructor,
6729 kCompilerHintsCount // Pseudo entry
6731 // Add hints for other modes when they're added.
6732 STATIC_ASSERT(LANGUAGE_END == 3);
6734 class FunctionKindBits : public BitField<FunctionKind, kIsArrow, 8> {};
6736 class DeoptCountBits : public BitField<int, 0, 4> {};
6737 class OptReenableTriesBits : public BitField<int, 4, 18> {};
6738 class ICAgeBits : public BitField<int, 22, 8> {};
6740 class OptCountBits : public BitField<int, 0, 22> {};
6741 class DisabledOptimizationReasonBits : public BitField<int, 22, 8> {};
6744 #if V8_HOST_ARCH_32_BIT
6745 // On 32 bit platforms, compiler hints is a smi.
6746 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
6747 static const int kCompilerHintsSize = kPointerSize;
6749 // On 64 bit platforms, compiler hints is not a smi, see comment above.
6750 static const int kCompilerHintsSmiTagSize = 0;
6751 static const int kCompilerHintsSize = kIntSize;
6754 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
6755 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
6758 // Constants for optimizing codegen for strict mode function and
6760 // Allows to use byte-width instructions.
6761 static const int kStrictModeBitWithinByte =
6762 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6763 static const int kStrongModeBitWithinByte =
6764 (kStrongModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6766 static const int kNativeBitWithinByte =
6767 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
6769 static const int kBoundBitWithinByte =
6770 (kBoundFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6772 #if defined(V8_TARGET_LITTLE_ENDIAN)
6773 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6774 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6775 static const int kStrongModeByteOffset =
6776 kCompilerHintsOffset +
6777 (kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6778 static const int kNativeByteOffset = kCompilerHintsOffset +
6779 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
6780 static const int kBoundByteOffset =
6781 kCompilerHintsOffset +
6782 (kBoundFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6783 #elif defined(V8_TARGET_BIG_ENDIAN)
6784 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6785 (kCompilerHintsSize - 1) -
6786 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6787 static const int kStrongModeByteOffset =
6788 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6789 ((kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6790 static const int kNativeByteOffset = kCompilerHintsOffset +
6791 (kCompilerHintsSize - 1) -
6792 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
6793 static const int kBoundByteOffset =
6794 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6795 ((kBoundFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6797 #error Unknown byte ordering
6801 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
6805 // Printing support.
6806 struct SourceCodeOf {
6807 explicit SourceCodeOf(SharedFunctionInfo* v, int max = -1)
6808 : value(v), max_length(max) {}
6809 const SharedFunctionInfo* value;
6814 std::ostream& operator<<(std::ostream& os, const SourceCodeOf& v);
6817 class JSGeneratorObject: public JSObject {
6819 // [function]: The function corresponding to this generator object.
6820 DECL_ACCESSORS(function, JSFunction)
6822 // [context]: The context of the suspended computation.
6823 DECL_ACCESSORS(context, Context)
6825 // [receiver]: The receiver of the suspended computation.
6826 DECL_ACCESSORS(receiver, Object)
6828 // [continuation]: Offset into code of continuation.
6830 // A positive offset indicates a suspended generator. The special
6831 // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
6832 // cannot be resumed.
6833 inline int continuation() const;
6834 inline void set_continuation(int continuation);
6835 inline bool is_closed();
6836 inline bool is_executing();
6837 inline bool is_suspended();
6839 // [operand_stack]: Saved operand stack.
6840 DECL_ACCESSORS(operand_stack, FixedArray)
6842 DECLARE_CAST(JSGeneratorObject)
6844 // Dispatched behavior.
6845 DECLARE_PRINTER(JSGeneratorObject)
6846 DECLARE_VERIFIER(JSGeneratorObject)
6848 // Magic sentinel values for the continuation.
6849 static const int kGeneratorExecuting = -1;
6850 static const int kGeneratorClosed = 0;
6852 // Layout description.
6853 static const int kFunctionOffset = JSObject::kHeaderSize;
6854 static const int kContextOffset = kFunctionOffset + kPointerSize;
6855 static const int kReceiverOffset = kContextOffset + kPointerSize;
6856 static const int kContinuationOffset = kReceiverOffset + kPointerSize;
6857 static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
6858 static const int kSize = kOperandStackOffset + kPointerSize;
6860 // Resume mode, for use by runtime functions.
6861 enum ResumeMode { NEXT, THROW };
6863 // Yielding from a generator returns an object with the following inobject
6864 // properties. See Context::iterator_result_map() for the map.
6865 static const int kResultValuePropertyIndex = 0;
6866 static const int kResultDonePropertyIndex = 1;
6867 static const int kResultPropertyCount = 2;
6869 static const int kResultValuePropertyOffset = JSObject::kHeaderSize;
6870 static const int kResultDonePropertyOffset =
6871 kResultValuePropertyOffset + kPointerSize;
6872 static const int kResultSize = kResultDonePropertyOffset + kPointerSize;
6875 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
6879 // Representation for module instance objects.
6880 class JSModule: public JSObject {
6882 // [context]: the context holding the module's locals, or undefined if none.
6883 DECL_ACCESSORS(context, Object)
6885 // [scope_info]: Scope info.
6886 DECL_ACCESSORS(scope_info, ScopeInfo)
6888 DECLARE_CAST(JSModule)
6890 // Dispatched behavior.
6891 DECLARE_PRINTER(JSModule)
6892 DECLARE_VERIFIER(JSModule)
6894 // Layout description.
6895 static const int kContextOffset = JSObject::kHeaderSize;
6896 static const int kScopeInfoOffset = kContextOffset + kPointerSize;
6897 static const int kSize = kScopeInfoOffset + kPointerSize;
6900 DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
6904 // JSFunction describes JavaScript functions.
6905 class JSFunction: public JSObject {
6907 // [prototype_or_initial_map]:
6908 DECL_ACCESSORS(prototype_or_initial_map, Object)
6910 // [shared]: The information about the function that
6911 // can be shared by instances.
6912 DECL_ACCESSORS(shared, SharedFunctionInfo)
6914 // [context]: The context for this function.
6915 inline Context* context();
6916 inline void set_context(Object* context);
6917 inline JSObject* global_proxy();
6919 // [code]: The generated code object for this function. Executed
6920 // when the function is invoked, e.g. foo() or new foo(). See
6921 // [[Call]] and [[Construct]] description in ECMA-262, section
6923 inline Code* code();
6924 inline void set_code(Code* code);
6925 inline void set_code_no_write_barrier(Code* code);
6926 inline void ReplaceCode(Code* code);
6928 // Tells whether this function is builtin.
6929 inline bool IsBuiltin();
6931 // Tells whether this function inlines the given shared function info.
6932 bool Inlines(SharedFunctionInfo* candidate);
6934 // Tells whether this function should be subject to debugging.
6935 inline bool IsSubjectToDebugging();
6937 // Tells whether or not the function needs arguments adaption.
6938 inline bool NeedsArgumentsAdaption();
6940 // Tells whether or not this function has been optimized.
6941 inline bool IsOptimized();
6943 // Mark this function for lazy recompilation. The function will be
6944 // recompiled the next time it is executed.
6945 void MarkForOptimization();
6946 void AttemptConcurrentOptimization();
6948 // Tells whether or not the function is already marked for lazy
6950 inline bool IsMarkedForOptimization();
6951 inline bool IsMarkedForConcurrentOptimization();
6953 // Tells whether or not the function is on the concurrent recompilation queue.
6954 inline bool IsInOptimizationQueue();
6956 // Inobject slack tracking is the way to reclaim unused inobject space.
6958 // The instance size is initially determined by adding some slack to
6959 // expected_nof_properties (to allow for a few extra properties added
6960 // after the constructor). There is no guarantee that the extra space
6961 // will not be wasted.
6963 // Here is the algorithm to reclaim the unused inobject space:
6964 // - Detect the first constructor call for this JSFunction.
6965 // When it happens enter the "in progress" state: initialize construction
6966 // counter in the initial_map.
6967 // - While the tracking is in progress create objects filled with
6968 // one_pointer_filler_map instead of undefined_value. This way they can be
6969 // resized quickly and safely.
6970 // - Once enough objects have been created compute the 'slack'
6971 // (traverse the map transition tree starting from the
6972 // initial_map and find the lowest value of unused_property_fields).
6973 // - Traverse the transition tree again and decrease the instance size
6974 // of every map. Existing objects will resize automatically (they are
6975 // filled with one_pointer_filler_map). All further allocations will
6976 // use the adjusted instance size.
6977 // - SharedFunctionInfo's expected_nof_properties left unmodified since
6978 // allocations made using different closures could actually create different
6979 // kind of objects (see prototype inheritance pattern).
6981 // Important: inobject slack tracking is not attempted during the snapshot
6984 // True if the initial_map is set and the object constructions countdown
6985 // counter is not zero.
6986 static const int kGenerousAllocationCount =
6987 Map::kSlackTrackingCounterStart - Map::kSlackTrackingCounterEnd + 1;
6988 inline bool IsInobjectSlackTrackingInProgress();
6990 // Starts the tracking.
6991 // Initializes object constructions countdown counter in the initial map.
6992 void StartInobjectSlackTracking();
6994 // Completes the tracking.
6995 void CompleteInobjectSlackTracking();
6997 // [literals_or_bindings]: Fixed array holding either
6998 // the materialized literals or the bindings of a bound function.
7000 // If the function contains object, regexp or array literals, the
7001 // literals array prefix contains the object, regexp, and array
7002 // function to be used when creating these literals. This is
7003 // necessary so that we do not dynamically lookup the object, regexp
7004 // or array functions. Performing a dynamic lookup, we might end up
7005 // using the functions from a new context that we should not have
7008 // On bound functions, the array is a (copy-on-write) fixed-array containing
7009 // the function that was bound, bound this-value and any bound
7010 // arguments. Bound functions never contain literals.
7011 DECL_ACCESSORS(literals_or_bindings, FixedArray)
7013 inline FixedArray* literals();
7014 inline void set_literals(FixedArray* literals);
7016 inline FixedArray* function_bindings();
7017 inline void set_function_bindings(FixedArray* bindings);
7019 // The initial map for an object created by this constructor.
7020 inline Map* initial_map();
7021 static void SetInitialMap(Handle<JSFunction> function, Handle<Map> map,
7022 Handle<Object> prototype);
7023 inline bool has_initial_map();
7024 static void EnsureHasInitialMap(Handle<JSFunction> function);
7026 // Get and set the prototype property on a JSFunction. If the
7027 // function has an initial map the prototype is set on the initial
7028 // map. Otherwise, the prototype is put in the initial map field
7029 // until an initial map is needed.
7030 inline bool has_prototype();
7031 inline bool has_instance_prototype();
7032 inline Object* prototype();
7033 inline Object* instance_prototype();
7034 static void SetPrototype(Handle<JSFunction> function,
7035 Handle<Object> value);
7036 static void SetInstancePrototype(Handle<JSFunction> function,
7037 Handle<Object> value);
7039 // Creates a new closure for the fucntion with the same bindings,
7040 // bound values, and prototype. An equivalent of spec operations
7041 // ``CloneMethod`` and ``CloneBoundFunction``.
7042 static Handle<JSFunction> CloneClosure(Handle<JSFunction> function);
7044 // After prototype is removed, it will not be created when accessed, and
7045 // [[Construct]] from this function will not be allowed.
7046 bool RemovePrototype();
7047 inline bool should_have_prototype();
7049 // Accessor for this function's initial map's [[class]]
7050 // property. This is primarily used by ECMA native functions. This
7051 // method sets the class_name field of this function's initial map
7052 // to a given value. It creates an initial map if this function does
7053 // not have one. Note that this method does not copy the initial map
7054 // if it has one already, but simply replaces it with the new value.
7055 // Instances created afterwards will have a map whose [[class]] is
7056 // set to 'value', but there is no guarantees on instances created
7058 void SetInstanceClassName(String* name);
7060 // Returns if this function has been compiled to native code yet.
7061 inline bool is_compiled();
7063 // Returns `false` if formal parameters include rest parameters, optional
7064 // parameters, or destructuring parameters.
7065 // TODO(caitp): make this a flag set during parsing
7066 inline bool has_simple_parameters();
7068 // [next_function_link]: Links functions into various lists, e.g. the list
7069 // of optimized functions hanging off the native_context. The CodeFlusher
7070 // uses this link to chain together flushing candidates. Treated weakly
7071 // by the garbage collector.
7072 DECL_ACCESSORS(next_function_link, Object)
7074 // Prints the name of the function using PrintF.
7075 void PrintName(FILE* out = stdout);
7077 DECLARE_CAST(JSFunction)
7079 // Iterates the objects, including code objects indirectly referenced
7080 // through pointers to the first instruction in the code object.
7081 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
7083 // Dispatched behavior.
7084 DECLARE_PRINTER(JSFunction)
7085 DECLARE_VERIFIER(JSFunction)
7087 // Returns the number of allocated literals.
7088 inline int NumberOfLiterals();
7090 // Used for flags such as --hydrogen-filter.
7091 bool PassesFilter(const char* raw_filter);
7093 // The function's name if it is configured, otherwise shared function info
7095 static Handle<String> GetDebugName(Handle<JSFunction> function);
7097 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
7098 // kSize) is weak and has special handling during garbage collection.
7099 static const int kCodeEntryOffset = JSObject::kHeaderSize;
7100 static const int kPrototypeOrInitialMapOffset =
7101 kCodeEntryOffset + kPointerSize;
7102 static const int kSharedFunctionInfoOffset =
7103 kPrototypeOrInitialMapOffset + kPointerSize;
7104 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
7105 static const int kLiteralsOffset = kContextOffset + kPointerSize;
7106 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
7107 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
7108 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
7110 // Layout of the bound-function binding array.
7111 static const int kBoundFunctionIndex = 0;
7112 static const int kBoundThisIndex = 1;
7113 static const int kBoundArgumentsStartIndex = 2;
7116 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7120 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7121 // and the prototype is hidden. JSGlobalProxy always delegates
7122 // property accesses to its prototype if the prototype is not null.
7124 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7126 // Accessing a JSGlobalProxy requires security check.
7128 class JSGlobalProxy : public JSObject {
7130 // [native_context]: the owner native context of this global proxy object.
7131 // It is null value if this object is not used by any context.
7132 DECL_ACCESSORS(native_context, Object)
7134 // [hash]: The hash code property (undefined if not initialized yet).
7135 DECL_ACCESSORS(hash, Object)
7137 DECLARE_CAST(JSGlobalProxy)
7139 inline bool IsDetachedFrom(GlobalObject* global) const;
7141 // Dispatched behavior.
7142 DECLARE_PRINTER(JSGlobalProxy)
7143 DECLARE_VERIFIER(JSGlobalProxy)
7145 // Layout description.
7146 static const int kNativeContextOffset = JSObject::kHeaderSize;
7147 static const int kHashOffset = kNativeContextOffset + kPointerSize;
7148 static const int kSize = kHashOffset + kPointerSize;
7151 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7155 // Common super class for JavaScript global objects and the special
7156 // builtins global objects.
7157 class GlobalObject: public JSObject {
7159 // [builtins]: the object holding the runtime routines written in JS.
7160 DECL_ACCESSORS(builtins, JSBuiltinsObject)
7162 // [native context]: the natives corresponding to this global object.
7163 DECL_ACCESSORS(native_context, Context)
7165 // [global proxy]: the global proxy object of the context
7166 DECL_ACCESSORS(global_proxy, JSObject)
7168 DECLARE_CAST(GlobalObject)
7170 static void InvalidatePropertyCell(Handle<GlobalObject> object,
7172 // Ensure that the global object has a cell for the given property name.
7173 static Handle<PropertyCell> EnsurePropertyCell(Handle<GlobalObject> global,
7176 // Layout description.
7177 static const int kBuiltinsOffset = JSObject::kHeaderSize;
7178 static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7179 static const int kGlobalProxyOffset = kNativeContextOffset + kPointerSize;
7180 static const int kHeaderSize = kGlobalProxyOffset + kPointerSize;
7183 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7187 // JavaScript global object.
7188 class JSGlobalObject: public GlobalObject {
7190 DECLARE_CAST(JSGlobalObject)
7192 inline bool IsDetached();
7194 // Dispatched behavior.
7195 DECLARE_PRINTER(JSGlobalObject)
7196 DECLARE_VERIFIER(JSGlobalObject)
7198 // Layout description.
7199 static const int kSize = GlobalObject::kHeaderSize;
7202 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7206 // Builtins global object which holds the runtime routines written in
7208 class JSBuiltinsObject: public GlobalObject {
7210 DECLARE_CAST(JSBuiltinsObject)
7212 // Dispatched behavior.
7213 DECLARE_PRINTER(JSBuiltinsObject)
7214 DECLARE_VERIFIER(JSBuiltinsObject)
7216 // Layout description.
7217 static const int kSize = GlobalObject::kHeaderSize;
7220 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7224 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
7225 class JSValue: public JSObject {
7227 // [value]: the object being wrapped.
7228 DECL_ACCESSORS(value, Object)
7230 DECLARE_CAST(JSValue)
7232 // Dispatched behavior.
7233 DECLARE_PRINTER(JSValue)
7234 DECLARE_VERIFIER(JSValue)
7236 // Layout description.
7237 static const int kValueOffset = JSObject::kHeaderSize;
7238 static const int kSize = kValueOffset + kPointerSize;
7241 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
7247 // Representation for JS date objects.
7248 class JSDate: public JSObject {
7250 // If one component is NaN, all of them are, indicating a NaN time value.
7251 // [value]: the time value.
7252 DECL_ACCESSORS(value, Object)
7253 // [year]: caches year. Either undefined, smi, or NaN.
7254 DECL_ACCESSORS(year, Object)
7255 // [month]: caches month. Either undefined, smi, or NaN.
7256 DECL_ACCESSORS(month, Object)
7257 // [day]: caches day. Either undefined, smi, or NaN.
7258 DECL_ACCESSORS(day, Object)
7259 // [weekday]: caches day of week. Either undefined, smi, or NaN.
7260 DECL_ACCESSORS(weekday, Object)
7261 // [hour]: caches hours. Either undefined, smi, or NaN.
7262 DECL_ACCESSORS(hour, Object)
7263 // [min]: caches minutes. Either undefined, smi, or NaN.
7264 DECL_ACCESSORS(min, Object)
7265 // [sec]: caches seconds. Either undefined, smi, or NaN.
7266 DECL_ACCESSORS(sec, Object)
7267 // [cache stamp]: sample of the date cache stamp at the
7268 // moment when chached fields were cached.
7269 DECL_ACCESSORS(cache_stamp, Object)
7271 DECLARE_CAST(JSDate)
7273 // Returns the date field with the specified index.
7274 // See FieldIndex for the list of date fields.
7275 static Object* GetField(Object* date, Smi* index);
7277 void SetValue(Object* value, bool is_value_nan);
7279 // ES6 section 20.3.4.45 Date.prototype [ @@toPrimitive ]
7280 static MUST_USE_RESULT MaybeHandle<Object> ToPrimitive(
7281 Handle<JSReceiver> receiver, Handle<Object> hint);
7283 // Dispatched behavior.
7284 DECLARE_PRINTER(JSDate)
7285 DECLARE_VERIFIER(JSDate)
7287 // The order is important. It must be kept in sync with date macros
7298 kFirstUncachedField,
7299 kMillisecond = kFirstUncachedField,
7303 kYearUTC = kFirstUTCField,
7316 // Layout description.
7317 static const int kValueOffset = JSObject::kHeaderSize;
7318 static const int kYearOffset = kValueOffset + kPointerSize;
7319 static const int kMonthOffset = kYearOffset + kPointerSize;
7320 static const int kDayOffset = kMonthOffset + kPointerSize;
7321 static const int kWeekdayOffset = kDayOffset + kPointerSize;
7322 static const int kHourOffset = kWeekdayOffset + kPointerSize;
7323 static const int kMinOffset = kHourOffset + kPointerSize;
7324 static const int kSecOffset = kMinOffset + kPointerSize;
7325 static const int kCacheStampOffset = kSecOffset + kPointerSize;
7326 static const int kSize = kCacheStampOffset + kPointerSize;
7329 inline Object* DoGetField(FieldIndex index);
7331 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
7333 // Computes and caches the cacheable fields of the date.
7334 inline void SetCachedFields(int64_t local_time_ms, DateCache* date_cache);
7337 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
7341 // Representation of message objects used for error reporting through
7342 // the API. The messages are formatted in JavaScript so this object is
7343 // a real JavaScript object. The information used for formatting the
7344 // error messages are not directly accessible from JavaScript to
7345 // prevent leaking information to user code called during error
7347 class JSMessageObject: public JSObject {
7349 // [type]: the type of error message.
7350 inline int type() const;
7351 inline void set_type(int value);
7353 // [arguments]: the arguments for formatting the error message.
7354 DECL_ACCESSORS(argument, Object)
7356 // [script]: the script from which the error message originated.
7357 DECL_ACCESSORS(script, Object)
7359 // [stack_frames]: an array of stack frames for this error object.
7360 DECL_ACCESSORS(stack_frames, Object)
7362 // [start_position]: the start position in the script for the error message.
7363 inline int start_position() const;
7364 inline void set_start_position(int value);
7366 // [end_position]: the end position in the script for the error message.
7367 inline int end_position() const;
7368 inline void set_end_position(int value);
7370 DECLARE_CAST(JSMessageObject)
7372 // Dispatched behavior.
7373 DECLARE_PRINTER(JSMessageObject)
7374 DECLARE_VERIFIER(JSMessageObject)
7376 // Layout description.
7377 static const int kTypeOffset = JSObject::kHeaderSize;
7378 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
7379 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
7380 static const int kStackFramesOffset = kScriptOffset + kPointerSize;
7381 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
7382 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
7383 static const int kSize = kEndPositionOffset + kPointerSize;
7385 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
7386 kStackFramesOffset + kPointerSize,
7387 kSize> BodyDescriptor;
7391 // Regular expressions
7392 // The regular expression holds a single reference to a FixedArray in
7393 // the kDataOffset field.
7394 // The FixedArray contains the following data:
7395 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
7396 // - reference to the original source string
7397 // - reference to the original flag string
7398 // If it is an atom regexp
7399 // - a reference to a literal string to search for
7400 // If it is an irregexp regexp:
7401 // - a reference to code for Latin1 inputs (bytecode or compiled), or a smi
7402 // used for tracking the last usage (used for code flushing).
7403 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
7404 // used for tracking the last usage (used for code flushing)..
7405 // - max number of registers used by irregexp implementations.
7406 // - number of capture registers (output values) of the regexp.
7407 class JSRegExp: public JSObject {
7410 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
7411 // ATOM: A simple string to match against using an indexOf operation.
7412 // IRREGEXP: Compiled with Irregexp.
7413 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
7414 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
7421 UNICODE_ESCAPES = 16
7426 explicit Flags(uint32_t value) : value_(value) { }
7427 bool is_global() { return (value_ & GLOBAL) != 0; }
7428 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
7429 bool is_multiline() { return (value_ & MULTILINE) != 0; }
7430 bool is_sticky() { return (value_ & STICKY) != 0; }
7431 bool is_unicode() { return (value_ & UNICODE_ESCAPES) != 0; }
7432 uint32_t value() { return value_; }
7437 DECL_ACCESSORS(data, Object)
7439 inline Type TypeTag();
7440 inline int CaptureCount();
7441 inline Flags GetFlags();
7442 inline String* Pattern();
7443 inline Object* DataAt(int index);
7444 // Set implementation data after the object has been prepared.
7445 inline void SetDataAt(int index, Object* value);
7447 static int code_index(bool is_latin1) {
7449 return kIrregexpLatin1CodeIndex;
7451 return kIrregexpUC16CodeIndex;
7455 static int saved_code_index(bool is_latin1) {
7457 return kIrregexpLatin1CodeSavedIndex;
7459 return kIrregexpUC16CodeSavedIndex;
7463 DECLARE_CAST(JSRegExp)
7465 // Dispatched behavior.
7466 DECLARE_VERIFIER(JSRegExp)
7468 static const int kDataOffset = JSObject::kHeaderSize;
7469 static const int kSize = kDataOffset + kPointerSize;
7471 // Indices in the data array.
7472 static const int kTagIndex = 0;
7473 static const int kSourceIndex = kTagIndex + 1;
7474 static const int kFlagsIndex = kSourceIndex + 1;
7475 static const int kDataIndex = kFlagsIndex + 1;
7476 // The data fields are used in different ways depending on the
7477 // value of the tag.
7478 // Atom regexps (literal strings).
7479 static const int kAtomPatternIndex = kDataIndex;
7481 static const int kAtomDataSize = kAtomPatternIndex + 1;
7483 // Irregexp compiled code or bytecode for Latin1. If compilation
7484 // fails, this fields hold an exception object that should be
7485 // thrown if the regexp is used again.
7486 static const int kIrregexpLatin1CodeIndex = kDataIndex;
7487 // Irregexp compiled code or bytecode for UC16. If compilation
7488 // fails, this fields hold an exception object that should be
7489 // thrown if the regexp is used again.
7490 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
7492 // Saved instance of Irregexp compiled code or bytecode for Latin1 that
7493 // is a potential candidate for flushing.
7494 static const int kIrregexpLatin1CodeSavedIndex = kDataIndex + 2;
7495 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
7496 // a potential candidate for flushing.
7497 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
7499 // Maximal number of registers used by either Latin1 or UC16.
7500 // Only used to check that there is enough stack space
7501 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
7502 // Number of captures in the compiled regexp.
7503 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
7505 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
7507 // Offsets directly into the data fixed array.
7508 static const int kDataTagOffset =
7509 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
7510 static const int kDataOneByteCodeOffset =
7511 FixedArray::kHeaderSize + kIrregexpLatin1CodeIndex * kPointerSize;
7512 static const int kDataUC16CodeOffset =
7513 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
7514 static const int kIrregexpCaptureCountOffset =
7515 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
7517 // In-object fields.
7518 static const int kSourceFieldIndex = 0;
7519 static const int kGlobalFieldIndex = 1;
7520 static const int kIgnoreCaseFieldIndex = 2;
7521 static const int kMultilineFieldIndex = 3;
7522 static const int kLastIndexFieldIndex = 4;
7523 static const int kInObjectFieldCount = 5;
7525 // The uninitialized value for a regexp code object.
7526 static const int kUninitializedValue = -1;
7528 // The compilation error value for the regexp code object. The real error
7529 // object is in the saved code field.
7530 static const int kCompilationErrorValue = -2;
7532 // When we store the sweep generation at which we moved the code from the
7533 // code index to the saved code index we mask it of to be in the [0:255]
7535 static const int kCodeAgeMask = 0xff;
7539 class CompilationCacheShape : public BaseShape<HashTableKey*> {
7541 static inline bool IsMatch(HashTableKey* key, Object* value) {
7542 return key->IsMatch(value);
7545 static inline uint32_t Hash(HashTableKey* key) {
7549 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7550 return key->HashForObject(object);
7553 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7555 static const int kPrefixSize = 0;
7556 static const int kEntrySize = 2;
7560 // This cache is used in two different variants. For regexp caching, it simply
7561 // maps identifying info of the regexp to the cached regexp object. Scripts and
7562 // eval code only gets cached after a second probe for the code object. To do
7563 // so, on first "put" only a hash identifying the source is entered into the
7564 // cache, mapping it to a lifetime count of the hash. On each call to Age all
7565 // such lifetimes get reduced, and removed once they reach zero. If a second put
7566 // is called while such a hash is live in the cache, the hash gets replaced by
7567 // an actual cache entry. Age also removes stale live entries from the cache.
7568 // Such entries are identified by SharedFunctionInfos pointing to either the
7569 // recompilation stub, or to "old" code. This avoids memory leaks due to
7570 // premature caching of scripts and eval strings that are never needed later.
7571 class CompilationCacheTable: public HashTable<CompilationCacheTable,
7572 CompilationCacheShape,
7575 // Find cached value for a string key, otherwise return null.
7576 Handle<Object> Lookup(
7577 Handle<String> src, Handle<Context> context, LanguageMode language_mode);
7578 Handle<Object> LookupEval(
7579 Handle<String> src, Handle<SharedFunctionInfo> shared,
7580 LanguageMode language_mode, int scope_position);
7581 Handle<Object> LookupRegExp(Handle<String> source, JSRegExp::Flags flags);
7582 static Handle<CompilationCacheTable> Put(
7583 Handle<CompilationCacheTable> cache, Handle<String> src,
7584 Handle<Context> context, LanguageMode language_mode,
7585 Handle<Object> value);
7586 static Handle<CompilationCacheTable> PutEval(
7587 Handle<CompilationCacheTable> cache, Handle<String> src,
7588 Handle<SharedFunctionInfo> context, Handle<SharedFunctionInfo> value,
7589 int scope_position);
7590 static Handle<CompilationCacheTable> PutRegExp(
7591 Handle<CompilationCacheTable> cache, Handle<String> src,
7592 JSRegExp::Flags flags, Handle<FixedArray> value);
7593 void Remove(Object* value);
7595 static const int kHashGenerations = 10;
7597 DECLARE_CAST(CompilationCacheTable)
7600 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
7604 class CodeCache: public Struct {
7606 DECL_ACCESSORS(default_cache, FixedArray)
7607 DECL_ACCESSORS(normal_type_cache, Object)
7609 // Add the code object to the cache.
7611 Handle<CodeCache> cache, Handle<Name> name, Handle<Code> code);
7613 // Lookup code object in the cache. Returns code object if found and undefined
7615 Object* Lookup(Name* name, Code::Flags flags);
7617 // Get the internal index of a code object in the cache. Returns -1 if the
7618 // code object is not in that cache. This index can be used to later call
7619 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
7621 int GetIndex(Object* name, Code* code);
7623 // Remove an object from the cache with the provided internal index.
7624 void RemoveByIndex(Object* name, Code* code, int index);
7626 DECLARE_CAST(CodeCache)
7628 // Dispatched behavior.
7629 DECLARE_PRINTER(CodeCache)
7630 DECLARE_VERIFIER(CodeCache)
7632 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
7633 static const int kNormalTypeCacheOffset =
7634 kDefaultCacheOffset + kPointerSize;
7635 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
7638 static void UpdateDefaultCache(
7639 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7640 static void UpdateNormalTypeCache(
7641 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7642 Object* LookupDefaultCache(Name* name, Code::Flags flags);
7643 Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
7645 // Code cache layout of the default cache. Elements are alternating name and
7646 // code objects for non normal load/store/call IC's.
7647 static const int kCodeCacheEntrySize = 2;
7648 static const int kCodeCacheEntryNameOffset = 0;
7649 static const int kCodeCacheEntryCodeOffset = 1;
7651 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
7655 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
7657 static inline bool IsMatch(HashTableKey* key, Object* value) {
7658 return key->IsMatch(value);
7661 static inline uint32_t Hash(HashTableKey* key) {
7665 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7666 return key->HashForObject(object);
7669 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7671 static const int kPrefixSize = 0;
7672 static const int kEntrySize = 2;
7676 class CodeCacheHashTable: public HashTable<CodeCacheHashTable,
7677 CodeCacheHashTableShape,
7680 Object* Lookup(Name* name, Code::Flags flags);
7681 static Handle<CodeCacheHashTable> Put(
7682 Handle<CodeCacheHashTable> table,
7686 int GetIndex(Name* name, Code::Flags flags);
7687 void RemoveByIndex(int index);
7689 DECLARE_CAST(CodeCacheHashTable)
7691 // Initial size of the fixed array backing the hash table.
7692 static const int kInitialSize = 64;
7695 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
7699 class PolymorphicCodeCache: public Struct {
7701 DECL_ACCESSORS(cache, Object)
7703 static void Update(Handle<PolymorphicCodeCache> cache,
7704 MapHandleList* maps,
7709 // Returns an undefined value if the entry is not found.
7710 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
7712 DECLARE_CAST(PolymorphicCodeCache)
7714 // Dispatched behavior.
7715 DECLARE_PRINTER(PolymorphicCodeCache)
7716 DECLARE_VERIFIER(PolymorphicCodeCache)
7718 static const int kCacheOffset = HeapObject::kHeaderSize;
7719 static const int kSize = kCacheOffset + kPointerSize;
7722 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
7726 class PolymorphicCodeCacheHashTable
7727 : public HashTable<PolymorphicCodeCacheHashTable,
7728 CodeCacheHashTableShape,
7731 Object* Lookup(MapHandleList* maps, int code_kind);
7733 static Handle<PolymorphicCodeCacheHashTable> Put(
7734 Handle<PolymorphicCodeCacheHashTable> hash_table,
7735 MapHandleList* maps,
7739 DECLARE_CAST(PolymorphicCodeCacheHashTable)
7741 static const int kInitialSize = 64;
7743 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
7747 class TypeFeedbackInfo: public Struct {
7749 inline int ic_total_count();
7750 inline void set_ic_total_count(int count);
7752 inline int ic_with_type_info_count();
7753 inline void change_ic_with_type_info_count(int delta);
7755 inline int ic_generic_count();
7756 inline void change_ic_generic_count(int delta);
7758 inline void initialize_storage();
7760 inline void change_own_type_change_checksum();
7761 inline int own_type_change_checksum();
7763 inline void set_inlined_type_change_checksum(int checksum);
7764 inline bool matches_inlined_type_change_checksum(int checksum);
7766 DECLARE_CAST(TypeFeedbackInfo)
7768 // Dispatched behavior.
7769 DECLARE_PRINTER(TypeFeedbackInfo)
7770 DECLARE_VERIFIER(TypeFeedbackInfo)
7772 static const int kStorage1Offset = HeapObject::kHeaderSize;
7773 static const int kStorage2Offset = kStorage1Offset + kPointerSize;
7774 static const int kStorage3Offset = kStorage2Offset + kPointerSize;
7775 static const int kSize = kStorage3Offset + kPointerSize;
7778 static const int kTypeChangeChecksumBits = 7;
7780 class ICTotalCountField: public BitField<int, 0,
7781 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7782 class OwnTypeChangeChecksum: public BitField<int,
7783 kSmiValueSize - kTypeChangeChecksumBits,
7784 kTypeChangeChecksumBits> {}; // NOLINT
7785 class ICsWithTypeInfoCountField: public BitField<int, 0,
7786 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7787 class InlinedTypeChangeChecksum: public BitField<int,
7788 kSmiValueSize - kTypeChangeChecksumBits,
7789 kTypeChangeChecksumBits> {}; // NOLINT
7791 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
7795 enum AllocationSiteMode {
7796 DONT_TRACK_ALLOCATION_SITE,
7797 TRACK_ALLOCATION_SITE,
7798 LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
7802 class AllocationSite: public Struct {
7804 static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
7805 static const double kPretenureRatio;
7806 static const int kPretenureMinimumCreated = 100;
7808 // Values for pretenure decision field.
7809 enum PretenureDecision {
7815 kLastPretenureDecisionValue = kZombie
7818 const char* PretenureDecisionName(PretenureDecision decision);
7820 DECL_ACCESSORS(transition_info, Object)
7821 // nested_site threads a list of sites that represent nested literals
7822 // walked in a particular order. So [[1, 2], 1, 2] will have one
7823 // nested_site, but [[1, 2], 3, [4]] will have a list of two.
7824 DECL_ACCESSORS(nested_site, Object)
7825 DECL_ACCESSORS(pretenure_data, Smi)
7826 DECL_ACCESSORS(pretenure_create_count, Smi)
7827 DECL_ACCESSORS(dependent_code, DependentCode)
7828 DECL_ACCESSORS(weak_next, Object)
7830 inline void Initialize();
7832 // This method is expensive, it should only be called for reporting.
7833 bool IsNestedSite();
7835 // transition_info bitfields, for constructed array transition info.
7836 class ElementsKindBits: public BitField<ElementsKind, 0, 15> {};
7837 class UnusedBits: public BitField<int, 15, 14> {};
7838 class DoNotInlineBit: public BitField<bool, 29, 1> {};
7840 // Bitfields for pretenure_data
7841 class MementoFoundCountBits: public BitField<int, 0, 26> {};
7842 class PretenureDecisionBits: public BitField<PretenureDecision, 26, 3> {};
7843 class DeoptDependentCodeBit: public BitField<bool, 29, 1> {};
7844 STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
7846 // Increments the mementos found counter and returns true when the first
7847 // memento was found for a given allocation site.
7848 inline bool IncrementMementoFoundCount();
7850 inline void IncrementMementoCreateCount();
7852 PretenureFlag GetPretenureMode();
7854 void ResetPretenureDecision();
7856 inline PretenureDecision pretenure_decision();
7857 inline void set_pretenure_decision(PretenureDecision decision);
7859 inline bool deopt_dependent_code();
7860 inline void set_deopt_dependent_code(bool deopt);
7862 inline int memento_found_count();
7863 inline void set_memento_found_count(int count);
7865 inline int memento_create_count();
7866 inline void set_memento_create_count(int count);
7868 // The pretenuring decision is made during gc, and the zombie state allows
7869 // us to recognize when an allocation site is just being kept alive because
7870 // a later traversal of new space may discover AllocationMementos that point
7871 // to this AllocationSite.
7872 inline bool IsZombie();
7874 inline bool IsMaybeTenure();
7876 inline void MarkZombie();
7878 inline bool MakePretenureDecision(PretenureDecision current_decision,
7880 bool maximum_size_scavenge);
7882 inline bool DigestPretenuringFeedback(bool maximum_size_scavenge);
7884 inline ElementsKind GetElementsKind();
7885 inline void SetElementsKind(ElementsKind kind);
7887 inline bool CanInlineCall();
7888 inline void SetDoNotInlineCall();
7890 inline bool SitePointsToLiteral();
7892 static void DigestTransitionFeedback(Handle<AllocationSite> site,
7893 ElementsKind to_kind);
7895 DECLARE_PRINTER(AllocationSite)
7896 DECLARE_VERIFIER(AllocationSite)
7898 DECLARE_CAST(AllocationSite)
7899 static inline AllocationSiteMode GetMode(
7900 ElementsKind boilerplate_elements_kind);
7901 static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
7902 static inline bool CanTrack(InstanceType type);
7904 static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
7905 static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
7906 static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
7907 static const int kPretenureCreateCountOffset =
7908 kPretenureDataOffset + kPointerSize;
7909 static const int kDependentCodeOffset =
7910 kPretenureCreateCountOffset + kPointerSize;
7911 static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
7912 static const int kSize = kWeakNextOffset + kPointerSize;
7914 // During mark compact we need to take special care for the dependent code
7916 static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
7917 static const int kPointerFieldsEndOffset = kWeakNextOffset;
7919 // For other visitors, use the fixed body descriptor below.
7920 typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
7921 kDependentCodeOffset + kPointerSize,
7922 kSize> BodyDescriptor;
7925 inline bool PretenuringDecisionMade();
7927 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
7931 class AllocationMemento: public Struct {
7933 static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
7934 static const int kSize = kAllocationSiteOffset + kPointerSize;
7936 DECL_ACCESSORS(allocation_site, Object)
7938 inline bool IsValid();
7939 inline AllocationSite* GetAllocationSite();
7941 DECLARE_PRINTER(AllocationMemento)
7942 DECLARE_VERIFIER(AllocationMemento)
7944 DECLARE_CAST(AllocationMemento)
7947 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
7951 // Representation of a slow alias as part of a sloppy arguments objects.
7952 // For fast aliases (if HasSloppyArgumentsElements()):
7953 // - the parameter map contains an index into the context
7954 // - all attributes of the element have default values
7955 // For slow aliases (if HasDictionaryArgumentsElements()):
7956 // - the parameter map contains no fast alias mapping (i.e. the hole)
7957 // - this struct (in the slow backing store) contains an index into the context
7958 // - all attributes are available as part if the property details
7959 class AliasedArgumentsEntry: public Struct {
7961 inline int aliased_context_slot() const;
7962 inline void set_aliased_context_slot(int count);
7964 DECLARE_CAST(AliasedArgumentsEntry)
7966 // Dispatched behavior.
7967 DECLARE_PRINTER(AliasedArgumentsEntry)
7968 DECLARE_VERIFIER(AliasedArgumentsEntry)
7970 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
7971 static const int kSize = kAliasedContextSlot + kPointerSize;
7974 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
7978 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
7979 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
7982 class StringHasher {
7984 explicit inline StringHasher(int length, uint32_t seed);
7986 template <typename schar>
7987 static inline uint32_t HashSequentialString(const schar* chars,
7991 // Reads all the data, even for long strings and computes the utf16 length.
7992 static uint32_t ComputeUtf8Hash(Vector<const char> chars,
7994 int* utf16_length_out);
7996 // Calculated hash value for a string consisting of 1 to
7997 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
7998 // value is represented decimal value.
7999 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
8001 // No string is allowed to have a hash of zero. That value is reserved
8002 // for internal properties. If the hash calculation yields zero then we
8004 static const int kZeroHash = 27;
8006 // Reusable parts of the hashing algorithm.
8007 INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
8008 INLINE(static uint32_t GetHashCore(uint32_t running_hash));
8009 INLINE(static uint32_t ComputeRunningHash(uint32_t running_hash,
8010 const uc16* chars, int length));
8011 INLINE(static uint32_t ComputeRunningHashOneByte(uint32_t running_hash,
8016 // Returns the value to store in the hash field of a string with
8017 // the given length and contents.
8018 uint32_t GetHashField();
8019 // Returns true if the hash of this string can be computed without
8020 // looking at the contents.
8021 inline bool has_trivial_hash();
8022 // Adds a block of characters to the hash.
8023 template<typename Char>
8024 inline void AddCharacters(const Char* chars, int len);
8027 // Add a character to the hash.
8028 inline void AddCharacter(uint16_t c);
8029 // Update index. Returns true if string is still an index.
8030 inline bool UpdateIndex(uint16_t c);
8033 uint32_t raw_running_hash_;
8034 uint32_t array_index_;
8035 bool is_array_index_;
8036 bool is_first_char_;
8037 DISALLOW_COPY_AND_ASSIGN(StringHasher);
8041 class IteratingStringHasher : public StringHasher {
8043 static inline uint32_t Hash(String* string, uint32_t seed);
8044 inline void VisitOneByteString(const uint8_t* chars, int length);
8045 inline void VisitTwoByteString(const uint16_t* chars, int length);
8048 inline IteratingStringHasher(int len, uint32_t seed);
8049 void VisitConsString(ConsString* cons_string);
8050 DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher);
8054 // The characteristics of a string are stored in its map. Retrieving these
8055 // few bits of information is moderately expensive, involving two memory
8056 // loads where the second is dependent on the first. To improve efficiency
8057 // the shape of the string is given its own class so that it can be retrieved
8058 // once and used for several string operations. A StringShape is small enough
8059 // to be passed by value and is immutable, but be aware that flattening a
8060 // string can potentially alter its shape. Also be aware that a GC caused by
8061 // something else can alter the shape of a string due to ConsString
8062 // shortcutting. Keeping these restrictions in mind has proven to be error-
8063 // prone and so we no longer put StringShapes in variables unless there is a
8064 // concrete performance benefit at that particular point in the code.
8065 class StringShape BASE_EMBEDDED {
8067 inline explicit StringShape(const String* s);
8068 inline explicit StringShape(Map* s);
8069 inline explicit StringShape(InstanceType t);
8070 inline bool IsSequential();
8071 inline bool IsExternal();
8072 inline bool IsCons();
8073 inline bool IsSliced();
8074 inline bool IsIndirect();
8075 inline bool IsExternalOneByte();
8076 inline bool IsExternalTwoByte();
8077 inline bool IsSequentialOneByte();
8078 inline bool IsSequentialTwoByte();
8079 inline bool IsInternalized();
8080 inline StringRepresentationTag representation_tag();
8081 inline uint32_t encoding_tag();
8082 inline uint32_t full_representation_tag();
8083 inline uint32_t size_tag();
8085 inline uint32_t type() { return type_; }
8086 inline void invalidate() { valid_ = false; }
8087 inline bool valid() { return valid_; }
8089 inline void invalidate() { }
8095 inline void set_valid() { valid_ = true; }
8098 inline void set_valid() { }
8103 // The Name abstract class captures anything that can be used as a property
8104 // name, i.e., strings and symbols. All names store a hash value.
8105 class Name: public HeapObject {
8107 // Get and set the hash field of the name.
8108 inline uint32_t hash_field();
8109 inline void set_hash_field(uint32_t value);
8111 // Tells whether the hash code has been computed.
8112 inline bool HasHashCode();
8114 // Returns a hash value used for the property table
8115 inline uint32_t Hash();
8117 // Equality operations.
8118 inline bool Equals(Name* other);
8119 inline static bool Equals(Handle<Name> one, Handle<Name> two);
8122 inline bool AsArrayIndex(uint32_t* index);
8124 // If the name is private, it can only name own properties.
8125 inline bool IsPrivate();
8127 // If the name is a non-flat string, this method returns a flat version of the
8128 // string. Otherwise it'll just return the input.
8129 static inline Handle<Name> Flatten(Handle<Name> name,
8130 PretenureFlag pretenure = NOT_TENURED);
8132 // Return a string version of this name that is converted according to the
8133 // rules described in ES6 section 9.2.11.
8134 MUST_USE_RESULT static MaybeHandle<String> ToFunctionName(Handle<Name> name);
8138 DECLARE_PRINTER(Name)
8140 void NameShortPrint();
8141 int NameShortPrint(Vector<char> str);
8144 // Layout description.
8145 static const int kHashFieldSlot = HeapObject::kHeaderSize;
8146 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
8147 static const int kHashFieldOffset = kHashFieldSlot;
8149 static const int kHashFieldOffset = kHashFieldSlot + kIntSize;
8151 static const int kSize = kHashFieldSlot + kPointerSize;
8153 // Mask constant for checking if a name has a computed hash code
8154 // and if it is a string that is an array index. The least significant bit
8155 // indicates whether a hash code has been computed. If the hash code has
8156 // been computed the 2nd bit tells whether the string can be used as an
8158 static const int kHashNotComputedMask = 1;
8159 static const int kIsNotArrayIndexMask = 1 << 1;
8160 static const int kNofHashBitFields = 2;
8162 // Shift constant retrieving hash code from hash field.
8163 static const int kHashShift = kNofHashBitFields;
8165 // Only these bits are relevant in the hash, since the top two are shifted
8167 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8169 // Array index strings this short can keep their index in the hash field.
8170 static const int kMaxCachedArrayIndexLength = 7;
8172 // For strings which are array indexes the hash value has the string length
8173 // mixed into the hash, mainly to avoid a hash value of zero which would be
8174 // the case for the string '0'. 24 bits are used for the array index value.
8175 static const int kArrayIndexValueBits = 24;
8176 static const int kArrayIndexLengthBits =
8177 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8179 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8181 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8182 kArrayIndexValueBits> {}; // NOLINT
8183 class ArrayIndexLengthBits : public BitField<unsigned int,
8184 kNofHashBitFields + kArrayIndexValueBits,
8185 kArrayIndexLengthBits> {}; // NOLINT
8187 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8188 // could use a mask to test if the length of string is less than or equal to
8189 // kMaxCachedArrayIndexLength.
8190 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8192 static const unsigned int kContainsCachedArrayIndexMask =
8193 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8194 << ArrayIndexLengthBits::kShift) |
8195 kIsNotArrayIndexMask;
8197 // Value of empty hash field indicating that the hash is not computed.
8198 static const int kEmptyHashField =
8199 kIsNotArrayIndexMask | kHashNotComputedMask;
8202 static inline bool IsHashFieldComputed(uint32_t field);
8205 DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8210 class Symbol: public Name {
8212 // [name]: The print name of a symbol, or undefined if none.
8213 DECL_ACCESSORS(name, Object)
8215 DECL_ACCESSORS(flags, Smi)
8217 // [is_private]: Whether this is a private symbol. Private symbols can only
8218 // be used to designate own properties of objects.
8219 DECL_BOOLEAN_ACCESSORS(is_private)
8221 DECLARE_CAST(Symbol)
8223 // Dispatched behavior.
8224 DECLARE_PRINTER(Symbol)
8225 DECLARE_VERIFIER(Symbol)
8227 // Layout description.
8228 static const int kNameOffset = Name::kSize;
8229 static const int kFlagsOffset = kNameOffset + kPointerSize;
8230 static const int kSize = kFlagsOffset + kPointerSize;
8232 typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
8234 void SymbolShortPrint(std::ostream& os);
8237 static const int kPrivateBit = 0;
8239 const char* PrivateSymbolToName() const;
8242 friend class Name; // For PrivateSymbolToName.
8245 DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
8251 // The String abstract class captures JavaScript string values:
8254 // 4.3.16 String Value
8255 // A string value is a member of the type String and is a finite
8256 // ordered sequence of zero or more 16-bit unsigned integer values.
8258 // All string values have a length field.
8259 class String: public Name {
8261 enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
8263 // Array index strings this short can keep their index in the hash field.
8264 static const int kMaxCachedArrayIndexLength = 7;
8266 // For strings which are array indexes the hash value has the string length
8267 // mixed into the hash, mainly to avoid a hash value of zero which would be
8268 // the case for the string '0'. 24 bits are used for the array index value.
8269 static const int kArrayIndexValueBits = 24;
8270 static const int kArrayIndexLengthBits =
8271 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8273 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8275 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8276 kArrayIndexValueBits> {}; // NOLINT
8277 class ArrayIndexLengthBits : public BitField<unsigned int,
8278 kNofHashBitFields + kArrayIndexValueBits,
8279 kArrayIndexLengthBits> {}; // NOLINT
8281 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8282 // could use a mask to test if the length of string is less than or equal to
8283 // kMaxCachedArrayIndexLength.
8284 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8286 static const unsigned int kContainsCachedArrayIndexMask =
8287 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8288 << ArrayIndexLengthBits::kShift) |
8289 kIsNotArrayIndexMask;
8291 class SubStringRange {
8293 explicit inline SubStringRange(String* string, int first = 0,
8296 inline iterator begin();
8297 inline iterator end();
8305 // Representation of the flat content of a String.
8306 // A non-flat string doesn't have flat content.
8307 // A flat string has content that's encoded as a sequence of either
8308 // one-byte chars or two-byte UC16.
8309 // Returned by String::GetFlatContent().
8312 // Returns true if the string is flat and this structure contains content.
8313 bool IsFlat() { return state_ != NON_FLAT; }
8314 // Returns true if the structure contains one-byte content.
8315 bool IsOneByte() { return state_ == ONE_BYTE; }
8316 // Returns true if the structure contains two-byte content.
8317 bool IsTwoByte() { return state_ == TWO_BYTE; }
8319 // Return the one byte content of the string. Only use if IsOneByte()
8321 Vector<const uint8_t> ToOneByteVector() {
8322 DCHECK_EQ(ONE_BYTE, state_);
8323 return Vector<const uint8_t>(onebyte_start, length_);
8325 // Return the two-byte content of the string. Only use if IsTwoByte()
8327 Vector<const uc16> ToUC16Vector() {
8328 DCHECK_EQ(TWO_BYTE, state_);
8329 return Vector<const uc16>(twobyte_start, length_);
8333 DCHECK(i < length_);
8334 DCHECK(state_ != NON_FLAT);
8335 if (state_ == ONE_BYTE) return onebyte_start[i];
8336 return twobyte_start[i];
8339 bool UsesSameString(const FlatContent& other) const {
8340 return onebyte_start == other.onebyte_start;
8344 enum State { NON_FLAT, ONE_BYTE, TWO_BYTE };
8346 // Constructors only used by String::GetFlatContent().
8347 explicit FlatContent(const uint8_t* start, int length)
8348 : onebyte_start(start), length_(length), state_(ONE_BYTE) {}
8349 explicit FlatContent(const uc16* start, int length)
8350 : twobyte_start(start), length_(length), state_(TWO_BYTE) { }
8351 FlatContent() : onebyte_start(NULL), length_(0), state_(NON_FLAT) { }
8354 const uint8_t* onebyte_start;
8355 const uc16* twobyte_start;
8360 friend class String;
8361 friend class IterableSubString;
8364 template <typename Char>
8365 INLINE(Vector<const Char> GetCharVector());
8367 // Get and set the length of the string.
8368 inline int length() const;
8369 inline void set_length(int value);
8371 // Get and set the length of the string using acquire loads and release
8373 inline int synchronized_length() const;
8374 inline void synchronized_set_length(int value);
8376 // Returns whether this string has only one-byte chars, i.e. all of them can
8377 // be one-byte encoded. This might be the case even if the string is
8378 // two-byte. Such strings may appear when the embedder prefers
8379 // two-byte external representations even for one-byte data.
8380 inline bool IsOneByteRepresentation() const;
8381 inline bool IsTwoByteRepresentation() const;
8383 // Cons and slices have an encoding flag that may not represent the actual
8384 // encoding of the underlying string. This is taken into account here.
8385 // Requires: this->IsFlat()
8386 inline bool IsOneByteRepresentationUnderneath();
8387 inline bool IsTwoByteRepresentationUnderneath();
8389 // NOTE: this should be considered only a hint. False negatives are
8391 inline bool HasOnlyOneByteChars();
8393 // Get and set individual two byte chars in the string.
8394 inline void Set(int index, uint16_t value);
8395 // Get individual two byte char in the string. Repeated calls
8396 // to this method are not efficient unless the string is flat.
8397 INLINE(uint16_t Get(int index));
8399 // ES6 section 7.1.3.1 ToNumber Applied to the String Type
8400 static Handle<Object> ToNumber(Handle<String> subject);
8402 // Flattens the string. Checks first inline to see if it is
8403 // necessary. Does nothing if the string is not a cons string.
8404 // Flattening allocates a sequential string with the same data as
8405 // the given string and mutates the cons string to a degenerate
8406 // form, where the first component is the new sequential string and
8407 // the second component is the empty string. If allocation fails,
8408 // this function returns a failure. If flattening succeeds, this
8409 // function returns the sequential string that is now the first
8410 // component of the cons string.
8412 // Degenerate cons strings are handled specially by the garbage
8413 // collector (see IsShortcutCandidate).
8415 static inline Handle<String> Flatten(Handle<String> string,
8416 PretenureFlag pretenure = NOT_TENURED);
8418 // Tries to return the content of a flat string as a structure holding either
8419 // a flat vector of char or of uc16.
8420 // If the string isn't flat, and therefore doesn't have flat content, the
8421 // returned structure will report so, and can't provide a vector of either
8423 FlatContent GetFlatContent();
8425 // Returns the parent of a sliced string or first part of a flat cons string.
8426 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
8427 inline String* GetUnderlying();
8429 // String equality operations.
8430 inline bool Equals(String* other);
8431 inline static bool Equals(Handle<String> one, Handle<String> two);
8432 bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
8433 bool IsOneByteEqualTo(Vector<const uint8_t> str);
8434 bool IsTwoByteEqualTo(Vector<const uc16> str);
8436 // Return a UTF8 representation of the string. The string is null
8437 // terminated but may optionally contain nulls. Length is returned
8438 // in length_output if length_output is not a null pointer The string
8439 // should be nearly flat, otherwise the performance of this method may
8440 // be very slow (quadratic in the length). Setting robustness_flag to
8441 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8442 // handles unexpected data without causing assert failures and it does not
8443 // do any heap allocations. This is useful when printing stack traces.
8444 base::SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
8445 RobustnessFlag robustness_flag,
8446 int offset, int length,
8447 int* length_output = 0);
8448 base::SmartArrayPointer<char> ToCString(
8449 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
8450 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
8451 int* length_output = 0);
8453 // Return a 16 bit Unicode representation of the string.
8454 // The string should be nearly flat, otherwise the performance of
8455 // of this method may be very bad. Setting robustness_flag to
8456 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8457 // handles unexpected data without causing assert failures and it does not
8458 // do any heap allocations. This is useful when printing stack traces.
8459 base::SmartArrayPointer<uc16> ToWideCString(
8460 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
8462 bool ComputeArrayIndex(uint32_t* index);
8465 bool MakeExternal(v8::String::ExternalStringResource* resource);
8466 bool MakeExternal(v8::String::ExternalOneByteStringResource* resource);
8469 inline bool AsArrayIndex(uint32_t* index);
8471 DECLARE_CAST(String)
8473 void PrintOn(FILE* out);
8475 // For use during stack traces. Performs rudimentary sanity check.
8478 // Dispatched behavior.
8479 void StringShortPrint(StringStream* accumulator);
8480 void PrintUC16(std::ostream& os, int start = 0, int end = -1); // NOLINT
8481 #if defined(DEBUG) || defined(OBJECT_PRINT)
8482 char* ToAsciiArray();
8484 DECLARE_PRINTER(String)
8485 DECLARE_VERIFIER(String)
8487 inline bool IsFlat();
8489 // Layout description.
8490 static const int kLengthOffset = Name::kSize;
8491 static const int kSize = kLengthOffset + kPointerSize;
8493 // Maximum number of characters to consider when trying to convert a string
8494 // value into an array index.
8495 static const int kMaxArrayIndexSize = 10;
8496 STATIC_ASSERT(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
8499 static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
8500 static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
8501 static const int kMaxUtf16CodeUnit = 0xffff;
8502 static const uint32_t kMaxUtf16CodeUnitU = kMaxUtf16CodeUnit;
8504 // Value of hash field containing computed hash equal to zero.
8505 static const int kEmptyStringHash = kIsNotArrayIndexMask;
8507 // Maximal string length.
8508 static const int kMaxLength = (1 << 28) - 16;
8510 // Max length for computing hash. For strings longer than this limit the
8511 // string length is used as the hash value.
8512 static const int kMaxHashCalcLength = 16383;
8514 // Limit for truncation in short printing.
8515 static const int kMaxShortPrintLength = 1024;
8517 // Support for regular expressions.
8518 const uc16* GetTwoByteData(unsigned start);
8520 // Helper function for flattening strings.
8521 template <typename sinkchar>
8522 static void WriteToFlat(String* source,
8527 // The return value may point to the first aligned word containing the first
8528 // non-one-byte character, rather than directly to the non-one-byte character.
8529 // If the return value is >= the passed length, the entire string was
8531 static inline int NonAsciiStart(const char* chars, int length) {
8532 const char* start = chars;
8533 const char* limit = chars + length;
8535 if (length >= kIntptrSize) {
8536 // Check unaligned bytes.
8537 while (!IsAligned(reinterpret_cast<intptr_t>(chars), sizeof(uintptr_t))) {
8538 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8539 return static_cast<int>(chars - start);
8543 // Check aligned words.
8544 DCHECK(unibrow::Utf8::kMaxOneByteChar == 0x7F);
8545 const uintptr_t non_one_byte_mask = kUintptrAllBitsSet / 0xFF * 0x80;
8546 while (chars + sizeof(uintptr_t) <= limit) {
8547 if (*reinterpret_cast<const uintptr_t*>(chars) & non_one_byte_mask) {
8548 return static_cast<int>(chars - start);
8550 chars += sizeof(uintptr_t);
8553 // Check remaining unaligned bytes.
8554 while (chars < limit) {
8555 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8556 return static_cast<int>(chars - start);
8561 return static_cast<int>(chars - start);
8564 static inline bool IsAscii(const char* chars, int length) {
8565 return NonAsciiStart(chars, length) >= length;
8568 static inline bool IsAscii(const uint8_t* chars, int length) {
8570 NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
8573 static inline int NonOneByteStart(const uc16* chars, int length) {
8574 const uc16* limit = chars + length;
8575 const uc16* start = chars;
8576 while (chars < limit) {
8577 if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
8580 return static_cast<int>(chars - start);
8583 static inline bool IsOneByte(const uc16* chars, int length) {
8584 return NonOneByteStart(chars, length) >= length;
8587 template<class Visitor>
8588 static inline ConsString* VisitFlat(Visitor* visitor,
8592 static Handle<FixedArray> CalculateLineEnds(Handle<String> string,
8593 bool include_ending_line);
8595 // Use the hash field to forward to the canonical internalized string
8596 // when deserializing an internalized string.
8597 inline void SetForwardedInternalizedString(String* string);
8598 inline String* GetForwardedInternalizedString();
8602 friend class StringTableInsertionKey;
8604 static Handle<String> SlowFlatten(Handle<ConsString> cons,
8605 PretenureFlag tenure);
8607 // Slow case of String::Equals. This implementation works on any strings
8608 // but it is most efficient on strings that are almost flat.
8609 bool SlowEquals(String* other);
8611 static bool SlowEquals(Handle<String> one, Handle<String> two);
8613 // Slow case of AsArrayIndex.
8614 bool SlowAsArrayIndex(uint32_t* index);
8616 // Compute and set the hash code.
8617 uint32_t ComputeAndSetHash();
8619 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
8623 // The SeqString abstract class captures sequential string values.
8624 class SeqString: public String {
8626 DECLARE_CAST(SeqString)
8628 // Layout description.
8629 static const int kHeaderSize = String::kSize;
8631 // Truncate the string in-place if possible and return the result.
8632 // In case of new_length == 0, the empty string is returned without
8633 // truncating the original string.
8634 MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
8637 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
8641 // The OneByteString class captures sequential one-byte string objects.
8642 // Each character in the OneByteString is an one-byte character.
8643 class SeqOneByteString: public SeqString {
8645 static const bool kHasOneByteEncoding = true;
8647 // Dispatched behavior.
8648 inline uint16_t SeqOneByteStringGet(int index);
8649 inline void SeqOneByteStringSet(int index, uint16_t value);
8651 // Get the address of the characters in this string.
8652 inline Address GetCharsAddress();
8654 inline uint8_t* GetChars();
8656 DECLARE_CAST(SeqOneByteString)
8658 // Garbage collection support. This method is called by the
8659 // garbage collector to compute the actual size of an OneByteString
8661 inline int SeqOneByteStringSize(InstanceType instance_type);
8663 // Computes the size for an OneByteString instance of a given length.
8664 static int SizeFor(int length) {
8665 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
8668 // Maximal memory usage for a single sequential one-byte string.
8669 static const int kMaxSize = 512 * MB - 1;
8670 STATIC_ASSERT((kMaxSize - kHeaderSize) >= String::kMaxLength);
8673 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
8677 // The TwoByteString class captures sequential unicode string objects.
8678 // Each character in the TwoByteString is a two-byte uint16_t.
8679 class SeqTwoByteString: public SeqString {
8681 static const bool kHasOneByteEncoding = false;
8683 // Dispatched behavior.
8684 inline uint16_t SeqTwoByteStringGet(int index);
8685 inline void SeqTwoByteStringSet(int index, uint16_t value);
8687 // Get the address of the characters in this string.
8688 inline Address GetCharsAddress();
8690 inline uc16* GetChars();
8693 const uint16_t* SeqTwoByteStringGetData(unsigned start);
8695 DECLARE_CAST(SeqTwoByteString)
8697 // Garbage collection support. This method is called by the
8698 // garbage collector to compute the actual size of a TwoByteString
8700 inline int SeqTwoByteStringSize(InstanceType instance_type);
8702 // Computes the size for a TwoByteString instance of a given length.
8703 static int SizeFor(int length) {
8704 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
8707 // Maximal memory usage for a single sequential two-byte string.
8708 static const int kMaxSize = 512 * MB - 1;
8709 STATIC_ASSERT(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
8710 String::kMaxLength);
8713 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
8717 // The ConsString class describes string values built by using the
8718 // addition operator on strings. A ConsString is a pair where the
8719 // first and second components are pointers to other string values.
8720 // One or both components of a ConsString can be pointers to other
8721 // ConsStrings, creating a binary tree of ConsStrings where the leaves
8722 // are non-ConsString string values. The string value represented by
8723 // a ConsString can be obtained by concatenating the leaf string
8724 // values in a left-to-right depth-first traversal of the tree.
8725 class ConsString: public String {
8727 // First string of the cons cell.
8728 inline String* first();
8729 // Doesn't check that the result is a string, even in debug mode. This is
8730 // useful during GC where the mark bits confuse the checks.
8731 inline Object* unchecked_first();
8732 inline void set_first(String* first,
8733 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8735 // Second string of the cons cell.
8736 inline String* second();
8737 // Doesn't check that the result is a string, even in debug mode. This is
8738 // useful during GC where the mark bits confuse the checks.
8739 inline Object* unchecked_second();
8740 inline void set_second(String* second,
8741 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8743 // Dispatched behavior.
8744 uint16_t ConsStringGet(int index);
8746 DECLARE_CAST(ConsString)
8748 // Layout description.
8749 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
8750 static const int kSecondOffset = kFirstOffset + kPointerSize;
8751 static const int kSize = kSecondOffset + kPointerSize;
8753 // Minimum length for a cons string.
8754 static const int kMinLength = 13;
8756 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
8759 DECLARE_VERIFIER(ConsString)
8762 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
8766 // The Sliced String class describes strings that are substrings of another
8767 // sequential string. The motivation is to save time and memory when creating
8768 // a substring. A Sliced String is described as a pointer to the parent,
8769 // the offset from the start of the parent string and the length. Using
8770 // a Sliced String therefore requires unpacking of the parent string and
8771 // adding the offset to the start address. A substring of a Sliced String
8772 // are not nested since the double indirection is simplified when creating
8773 // such a substring.
8774 // Currently missing features are:
8775 // - handling externalized parent strings
8776 // - external strings as parent
8777 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
8778 class SlicedString: public String {
8780 inline String* parent();
8781 inline void set_parent(String* parent,
8782 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8783 inline int offset() const;
8784 inline void set_offset(int offset);
8786 // Dispatched behavior.
8787 uint16_t SlicedStringGet(int index);
8789 DECLARE_CAST(SlicedString)
8791 // Layout description.
8792 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
8793 static const int kOffsetOffset = kParentOffset + kPointerSize;
8794 static const int kSize = kOffsetOffset + kPointerSize;
8796 // Minimum length for a sliced string.
8797 static const int kMinLength = 13;
8799 typedef FixedBodyDescriptor<kParentOffset,
8800 kOffsetOffset + kPointerSize, kSize>
8803 DECLARE_VERIFIER(SlicedString)
8806 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
8810 // The ExternalString class describes string values that are backed by
8811 // a string resource that lies outside the V8 heap. ExternalStrings
8812 // consist of the length field common to all strings, a pointer to the
8813 // external resource. It is important to ensure (externally) that the
8814 // resource is not deallocated while the ExternalString is live in the
8817 // The API expects that all ExternalStrings are created through the
8818 // API. Therefore, ExternalStrings should not be used internally.
8819 class ExternalString: public String {
8821 DECLARE_CAST(ExternalString)
8823 // Layout description.
8824 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
8825 static const int kShortSize = kResourceOffset + kPointerSize;
8826 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
8827 static const int kSize = kResourceDataOffset + kPointerSize;
8829 static const int kMaxShortLength =
8830 (kShortSize - SeqString::kHeaderSize) / kCharSize;
8832 // Return whether external string is short (data pointer is not cached).
8833 inline bool is_short();
8835 STATIC_ASSERT(kResourceOffset == Internals::kStringResourceOffset);
8838 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
8842 // The ExternalOneByteString class is an external string backed by an
8844 class ExternalOneByteString : public ExternalString {
8846 static const bool kHasOneByteEncoding = true;
8848 typedef v8::String::ExternalOneByteStringResource Resource;
8850 // The underlying resource.
8851 inline const Resource* resource();
8852 inline void set_resource(const Resource* buffer);
8854 // Update the pointer cache to the external character array.
8855 // The cached pointer is always valid, as the external character array does =
8856 // not move during lifetime. Deserialization is the only exception, after
8857 // which the pointer cache has to be refreshed.
8858 inline void update_data_cache();
8860 inline const uint8_t* GetChars();
8862 // Dispatched behavior.
8863 inline uint16_t ExternalOneByteStringGet(int index);
8865 DECLARE_CAST(ExternalOneByteString)
8867 // Garbage collection support.
8868 inline void ExternalOneByteStringIterateBody(ObjectVisitor* v);
8870 template <typename StaticVisitor>
8871 inline void ExternalOneByteStringIterateBody();
8874 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalOneByteString);
8878 // The ExternalTwoByteString class is an external string backed by a UTF-16
8880 class ExternalTwoByteString: public ExternalString {
8882 static const bool kHasOneByteEncoding = false;
8884 typedef v8::String::ExternalStringResource Resource;
8886 // The underlying string resource.
8887 inline const Resource* resource();
8888 inline void set_resource(const Resource* buffer);
8890 // Update the pointer cache to the external character array.
8891 // The cached pointer is always valid, as the external character array does =
8892 // not move during lifetime. Deserialization is the only exception, after
8893 // which the pointer cache has to be refreshed.
8894 inline void update_data_cache();
8896 inline const uint16_t* GetChars();
8898 // Dispatched behavior.
8899 inline uint16_t ExternalTwoByteStringGet(int index);
8902 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
8904 DECLARE_CAST(ExternalTwoByteString)
8906 // Garbage collection support.
8907 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
8909 template<typename StaticVisitor>
8910 inline void ExternalTwoByteStringIterateBody();
8913 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
8917 // Utility superclass for stack-allocated objects that must be updated
8918 // on gc. It provides two ways for the gc to update instances, either
8919 // iterating or updating after gc.
8920 class Relocatable BASE_EMBEDDED {
8922 explicit inline Relocatable(Isolate* isolate);
8923 inline virtual ~Relocatable();
8924 virtual void IterateInstance(ObjectVisitor* v) { }
8925 virtual void PostGarbageCollection() { }
8927 static void PostGarbageCollectionProcessing(Isolate* isolate);
8928 static int ArchiveSpacePerThread();
8929 static char* ArchiveState(Isolate* isolate, char* to);
8930 static char* RestoreState(Isolate* isolate, char* from);
8931 static void Iterate(Isolate* isolate, ObjectVisitor* v);
8932 static void Iterate(ObjectVisitor* v, Relocatable* top);
8933 static char* Iterate(ObjectVisitor* v, char* t);
8941 // A flat string reader provides random access to the contents of a
8942 // string independent of the character width of the string. The handle
8943 // must be valid as long as the reader is being used.
8944 class FlatStringReader : public Relocatable {
8946 FlatStringReader(Isolate* isolate, Handle<String> str);
8947 FlatStringReader(Isolate* isolate, Vector<const char> input);
8948 void PostGarbageCollection();
8949 inline uc32 Get(int index);
8950 template <typename Char>
8951 inline Char Get(int index);
8952 int length() { return length_; }
8961 // This maintains an off-stack representation of the stack frames required
8962 // to traverse a ConsString, allowing an entirely iterative and restartable
8963 // traversal of the entire string
8964 class ConsStringIterator {
8966 inline ConsStringIterator() {}
8967 inline explicit ConsStringIterator(ConsString* cons_string, int offset = 0) {
8968 Reset(cons_string, offset);
8970 inline void Reset(ConsString* cons_string, int offset = 0) {
8972 // Next will always return NULL.
8973 if (cons_string == NULL) return;
8974 Initialize(cons_string, offset);
8976 // Returns NULL when complete.
8977 inline String* Next(int* offset_out) {
8979 if (depth_ == 0) return NULL;
8980 return Continue(offset_out);
8984 static const int kStackSize = 32;
8985 // Use a mask instead of doing modulo operations for stack wrapping.
8986 static const int kDepthMask = kStackSize-1;
8987 STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
8988 static inline int OffsetForDepth(int depth);
8990 inline void PushLeft(ConsString* string);
8991 inline void PushRight(ConsString* string);
8992 inline void AdjustMaximumDepth();
8994 inline bool StackBlown() { return maximum_depth_ - depth_ == kStackSize; }
8995 void Initialize(ConsString* cons_string, int offset);
8996 String* Continue(int* offset_out);
8997 String* NextLeaf(bool* blew_stack);
8998 String* Search(int* offset_out);
9000 // Stack must always contain only frames for which right traversal
9001 // has not yet been performed.
9002 ConsString* frames_[kStackSize];
9007 DISALLOW_COPY_AND_ASSIGN(ConsStringIterator);
9011 class StringCharacterStream {
9013 inline StringCharacterStream(String* string,
9015 inline uint16_t GetNext();
9016 inline bool HasMore();
9017 inline void Reset(String* string, int offset = 0);
9018 inline void VisitOneByteString(const uint8_t* chars, int length);
9019 inline void VisitTwoByteString(const uint16_t* chars, int length);
9022 ConsStringIterator iter_;
9025 const uint8_t* buffer8_;
9026 const uint16_t* buffer16_;
9028 const uint8_t* end_;
9029 DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
9033 template <typename T>
9034 class VectorIterator {
9036 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
9037 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
9038 T GetNext() { return data_[index_++]; }
9039 bool has_more() { return index_ < data_.length(); }
9041 Vector<const T> data_;
9046 // The Oddball describes objects null, undefined, true, and false.
9047 class Oddball: public HeapObject {
9049 // [to_string]: Cached to_string computed at startup.
9050 DECL_ACCESSORS(to_string, String)
9052 // [to_number]: Cached to_number computed at startup.
9053 DECL_ACCESSORS(to_number, Object)
9055 // [typeof]: Cached type_of computed at startup.
9056 DECL_ACCESSORS(type_of, String)
9058 inline byte kind() const;
9059 inline void set_kind(byte kind);
9061 DECLARE_CAST(Oddball)
9063 // Dispatched behavior.
9064 DECLARE_VERIFIER(Oddball)
9066 // Initialize the fields.
9067 static void Initialize(Isolate* isolate, Handle<Oddball> oddball,
9068 const char* to_string, Handle<Object> to_number,
9069 const char* type_of, byte kind);
9071 // Layout description.
9072 static const int kToStringOffset = HeapObject::kHeaderSize;
9073 static const int kToNumberOffset = kToStringOffset + kPointerSize;
9074 static const int kTypeOfOffset = kToNumberOffset + kPointerSize;
9075 static const int kKindOffset = kTypeOfOffset + kPointerSize;
9076 static const int kSize = kKindOffset + kPointerSize;
9078 static const byte kFalse = 0;
9079 static const byte kTrue = 1;
9080 static const byte kNotBooleanMask = ~1;
9081 static const byte kTheHole = 2;
9082 static const byte kNull = 3;
9083 static const byte kArgumentMarker = 4;
9084 static const byte kUndefined = 5;
9085 static const byte kUninitialized = 6;
9086 static const byte kOther = 7;
9087 static const byte kException = 8;
9089 typedef FixedBodyDescriptor<kToStringOffset, kTypeOfOffset + kPointerSize,
9090 kSize> BodyDescriptor;
9092 STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset);
9093 STATIC_ASSERT(kNull == Internals::kNullOddballKind);
9094 STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind);
9097 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
9101 class Cell: public HeapObject {
9103 // [value]: value of the cell.
9104 DECL_ACCESSORS(value, Object)
9108 static inline Cell* FromValueAddress(Address value) {
9109 Object* result = FromAddress(value - kValueOffset);
9110 return static_cast<Cell*>(result);
9113 inline Address ValueAddress() {
9114 return address() + kValueOffset;
9117 // Dispatched behavior.
9118 DECLARE_PRINTER(Cell)
9119 DECLARE_VERIFIER(Cell)
9121 // Layout description.
9122 static const int kValueOffset = HeapObject::kHeaderSize;
9123 static const int kSize = kValueOffset + kPointerSize;
9125 typedef FixedBodyDescriptor<kValueOffset,
9126 kValueOffset + kPointerSize,
9127 kSize> BodyDescriptor;
9130 DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9134 class PropertyCell : public HeapObject {
9136 // [property_details]: details of the global property.
9137 DECL_ACCESSORS(property_details_raw, Object)
9138 // [value]: value of the global property.
9139 DECL_ACCESSORS(value, Object)
9140 // [dependent_code]: dependent code that depends on the type of the global
9142 DECL_ACCESSORS(dependent_code, DependentCode)
9144 inline PropertyDetails property_details();
9145 inline void set_property_details(PropertyDetails details);
9147 PropertyCellConstantType GetConstantType();
9149 // Computes the new type of the cell's contents for the given value, but
9150 // without actually modifying the details.
9151 static PropertyCellType UpdatedType(Handle<PropertyCell> cell,
9152 Handle<Object> value,
9153 PropertyDetails details);
9154 static void UpdateCell(Handle<GlobalDictionary> dictionary, int entry,
9155 Handle<Object> value, PropertyDetails details);
9157 static Handle<PropertyCell> InvalidateEntry(
9158 Handle<GlobalDictionary> dictionary, int entry);
9160 static void SetValueWithInvalidation(Handle<PropertyCell> cell,
9161 Handle<Object> new_value);
9163 DECLARE_CAST(PropertyCell)
9165 // Dispatched behavior.
9166 DECLARE_PRINTER(PropertyCell)
9167 DECLARE_VERIFIER(PropertyCell)
9169 // Layout description.
9170 static const int kDetailsOffset = HeapObject::kHeaderSize;
9171 static const int kValueOffset = kDetailsOffset + kPointerSize;
9172 static const int kDependentCodeOffset = kValueOffset + kPointerSize;
9173 static const int kSize = kDependentCodeOffset + kPointerSize;
9175 static const int kPointerFieldsBeginOffset = kValueOffset;
9176 static const int kPointerFieldsEndOffset = kSize;
9178 typedef FixedBodyDescriptor<kValueOffset,
9180 kSize> BodyDescriptor;
9183 DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9187 class WeakCell : public HeapObject {
9189 inline Object* value() const;
9191 // This should not be called by anyone except GC.
9192 inline void clear();
9194 // This should not be called by anyone except allocator.
9195 inline void initialize(HeapObject* value);
9197 inline bool cleared() const;
9199 DECL_ACCESSORS(next, Object)
9201 inline void clear_next(Heap* heap);
9203 inline bool next_cleared();
9205 DECLARE_CAST(WeakCell)
9207 DECLARE_PRINTER(WeakCell)
9208 DECLARE_VERIFIER(WeakCell)
9210 // Layout description.
9211 static const int kValueOffset = HeapObject::kHeaderSize;
9212 static const int kNextOffset = kValueOffset + kPointerSize;
9213 static const int kSize = kNextOffset + kPointerSize;
9215 typedef FixedBodyDescriptor<kValueOffset, kSize, kSize> BodyDescriptor;
9218 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakCell);
9222 // The JSProxy describes EcmaScript Harmony proxies
9223 class JSProxy: public JSReceiver {
9225 // [handler]: The handler property.
9226 DECL_ACCESSORS(handler, Object)
9228 // [hash]: The hash code property (undefined if not initialized yet).
9229 DECL_ACCESSORS(hash, Object)
9231 DECLARE_CAST(JSProxy)
9233 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithHandler(
9234 Handle<JSProxy> proxy,
9235 Handle<Object> receiver,
9238 // If the handler defines an accessor property with a setter, invoke it.
9239 // If it defines an accessor property without a setter, or a data property
9240 // that is read-only, throw. In all these cases set '*done' to true,
9241 // otherwise set it to false.
9243 static MaybeHandle<Object> SetPropertyViaPrototypesWithHandler(
9244 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9245 Handle<Object> value, LanguageMode language_mode, bool* done);
9247 MUST_USE_RESULT static Maybe<PropertyAttributes>
9248 GetPropertyAttributesWithHandler(Handle<JSProxy> proxy,
9249 Handle<Object> receiver,
9251 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithHandler(
9252 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9253 Handle<Object> value, LanguageMode language_mode);
9255 // Turn the proxy into an (empty) JSObject.
9256 static void Fix(Handle<JSProxy> proxy);
9258 // Initializes the body after the handler slot.
9259 inline void InitializeBody(int object_size, Object* value);
9261 // Invoke a trap by name. If the trap does not exist on this's handler,
9262 // but derived_trap is non-NULL, invoke that instead. May cause GC.
9263 MUST_USE_RESULT static MaybeHandle<Object> CallTrap(
9264 Handle<JSProxy> proxy,
9266 Handle<Object> derived_trap,
9268 Handle<Object> args[]);
9270 // Dispatched behavior.
9271 DECLARE_PRINTER(JSProxy)
9272 DECLARE_VERIFIER(JSProxy)
9274 // Layout description. We add padding so that a proxy has the same
9275 // size as a virgin JSObject. This is essential for becoming a JSObject
9277 static const int kHandlerOffset = HeapObject::kHeaderSize;
9278 static const int kHashOffset = kHandlerOffset + kPointerSize;
9279 static const int kPaddingOffset = kHashOffset + kPointerSize;
9280 static const int kSize = JSObject::kHeaderSize;
9281 static const int kHeaderSize = kPaddingOffset;
9282 static const int kPaddingSize = kSize - kPaddingOffset;
9284 STATIC_ASSERT(kPaddingSize >= 0);
9286 typedef FixedBodyDescriptor<kHandlerOffset,
9288 kSize> BodyDescriptor;
9291 friend class JSReceiver;
9293 MUST_USE_RESULT static Maybe<bool> HasPropertyWithHandler(
9294 Handle<JSProxy> proxy, Handle<Name> name);
9296 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithHandler(
9297 Handle<JSProxy> proxy, Handle<Name> name, LanguageMode language_mode);
9299 MUST_USE_RESULT Object* GetIdentityHash();
9301 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
9303 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
9307 class JSFunctionProxy: public JSProxy {
9309 // [call_trap]: The call trap.
9310 DECL_ACCESSORS(call_trap, JSReceiver)
9312 // [construct_trap]: The construct trap.
9313 DECL_ACCESSORS(construct_trap, Object)
9315 DECLARE_CAST(JSFunctionProxy)
9317 // Dispatched behavior.
9318 DECLARE_PRINTER(JSFunctionProxy)
9319 DECLARE_VERIFIER(JSFunctionProxy)
9321 // Layout description.
9322 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
9323 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
9324 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
9325 static const int kSize = JSFunction::kSize;
9326 static const int kPaddingSize = kSize - kPaddingOffset;
9328 STATIC_ASSERT(kPaddingSize >= 0);
9330 typedef FixedBodyDescriptor<kHandlerOffset,
9331 kConstructTrapOffset + kPointerSize,
9332 kSize> BodyDescriptor;
9335 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
9339 class JSCollection : public JSObject {
9341 // [table]: the backing hash table
9342 DECL_ACCESSORS(table, Object)
9344 static const int kTableOffset = JSObject::kHeaderSize;
9345 static const int kSize = kTableOffset + kPointerSize;
9348 DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollection);
9352 // The JSSet describes EcmaScript Harmony sets
9353 class JSSet : public JSCollection {
9357 static void Initialize(Handle<JSSet> set, Isolate* isolate);
9358 static void Clear(Handle<JSSet> set);
9360 // Dispatched behavior.
9361 DECLARE_PRINTER(JSSet)
9362 DECLARE_VERIFIER(JSSet)
9365 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
9369 // The JSMap describes EcmaScript Harmony maps
9370 class JSMap : public JSCollection {
9374 static void Initialize(Handle<JSMap> map, Isolate* isolate);
9375 static void Clear(Handle<JSMap> map);
9377 // Dispatched behavior.
9378 DECLARE_PRINTER(JSMap)
9379 DECLARE_VERIFIER(JSMap)
9382 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
9386 // OrderedHashTableIterator is an iterator that iterates over the keys and
9387 // values of an OrderedHashTable.
9389 // The iterator has a reference to the underlying OrderedHashTable data,
9390 // [table], as well as the current [index] the iterator is at.
9392 // When the OrderedHashTable is rehashed it adds a reference from the old table
9393 // to the new table as well as storing enough data about the changes so that the
9394 // iterator [index] can be adjusted accordingly.
9396 // When the [Next] result from the iterator is requested, the iterator checks if
9397 // there is a newer table that it needs to transition to.
9398 template<class Derived, class TableType>
9399 class OrderedHashTableIterator: public JSObject {
9401 // [table]: the backing hash table mapping keys to values.
9402 DECL_ACCESSORS(table, Object)
9404 // [index]: The index into the data table.
9405 DECL_ACCESSORS(index, Object)
9407 // [kind]: The kind of iteration this is. One of the [Kind] enum values.
9408 DECL_ACCESSORS(kind, Object)
9411 void OrderedHashTableIteratorPrint(std::ostream& os); // NOLINT
9414 static const int kTableOffset = JSObject::kHeaderSize;
9415 static const int kIndexOffset = kTableOffset + kPointerSize;
9416 static const int kKindOffset = kIndexOffset + kPointerSize;
9417 static const int kSize = kKindOffset + kPointerSize;
9425 // Whether the iterator has more elements. This needs to be called before
9426 // calling |CurrentKey| and/or |CurrentValue|.
9429 // Move the index forward one.
9431 set_index(Smi::FromInt(Smi::cast(index())->value() + 1));
9434 // Populates the array with the next key and value and then moves the iterator
9436 // This returns the |kind| or 0 if the iterator is already at the end.
9437 Smi* Next(JSArray* value_array);
9439 // Returns the current key of the iterator. This should only be called when
9440 // |HasMore| returns true.
9441 inline Object* CurrentKey();
9444 // Transitions the iterator to the non obsolete backing store. This is a NOP
9445 // if the [table] is not obsolete.
9448 DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
9452 class JSSetIterator: public OrderedHashTableIterator<JSSetIterator,
9455 // Dispatched behavior.
9456 DECLARE_PRINTER(JSSetIterator)
9457 DECLARE_VERIFIER(JSSetIterator)
9459 DECLARE_CAST(JSSetIterator)
9461 // Called by |Next| to populate the array. This allows the subclasses to
9462 // populate the array differently.
9463 inline void PopulateValueArray(FixedArray* array);
9466 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSetIterator);
9470 class JSMapIterator: public OrderedHashTableIterator<JSMapIterator,
9473 // Dispatched behavior.
9474 DECLARE_PRINTER(JSMapIterator)
9475 DECLARE_VERIFIER(JSMapIterator)
9477 DECLARE_CAST(JSMapIterator)
9479 // Called by |Next| to populate the array. This allows the subclasses to
9480 // populate the array differently.
9481 inline void PopulateValueArray(FixedArray* array);
9484 // Returns the current value of the iterator. This should only be called when
9485 // |HasMore| returns true.
9486 inline Object* CurrentValue();
9488 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMapIterator);
9492 // Base class for both JSWeakMap and JSWeakSet
9493 class JSWeakCollection: public JSObject {
9495 // [table]: the backing hash table mapping keys to values.
9496 DECL_ACCESSORS(table, Object)
9498 // [next]: linked list of encountered weak maps during GC.
9499 DECL_ACCESSORS(next, Object)
9501 static void Initialize(Handle<JSWeakCollection> collection, Isolate* isolate);
9502 static void Set(Handle<JSWeakCollection> collection, Handle<Object> key,
9503 Handle<Object> value, int32_t hash);
9504 static bool Delete(Handle<JSWeakCollection> collection, Handle<Object> key,
9507 static const int kTableOffset = JSObject::kHeaderSize;
9508 static const int kNextOffset = kTableOffset + kPointerSize;
9509 static const int kSize = kNextOffset + kPointerSize;
9512 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
9516 // The JSWeakMap describes EcmaScript Harmony weak maps
9517 class JSWeakMap: public JSWeakCollection {
9519 DECLARE_CAST(JSWeakMap)
9521 // Dispatched behavior.
9522 DECLARE_PRINTER(JSWeakMap)
9523 DECLARE_VERIFIER(JSWeakMap)
9526 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
9530 // The JSWeakSet describes EcmaScript Harmony weak sets
9531 class JSWeakSet: public JSWeakCollection {
9533 DECLARE_CAST(JSWeakSet)
9535 // Dispatched behavior.
9536 DECLARE_PRINTER(JSWeakSet)
9537 DECLARE_VERIFIER(JSWeakSet)
9540 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
9544 // Whether a JSArrayBuffer is a SharedArrayBuffer or not.
9545 enum class SharedFlag { kNotShared, kShared };
9548 class JSArrayBuffer: public JSObject {
9550 // [backing_store]: backing memory for this array
9551 DECL_ACCESSORS(backing_store, void)
9553 // [byte_length]: length in bytes
9554 DECL_ACCESSORS(byte_length, Object)
9556 inline uint32_t bit_field() const;
9557 inline void set_bit_field(uint32_t bits);
9559 inline bool is_external();
9560 inline void set_is_external(bool value);
9562 inline bool is_neuterable();
9563 inline void set_is_neuterable(bool value);
9565 inline bool was_neutered();
9566 inline void set_was_neutered(bool value);
9568 inline bool is_shared();
9569 inline void set_is_shared(bool value);
9571 DECLARE_CAST(JSArrayBuffer)
9575 static void Setup(Handle<JSArrayBuffer> array_buffer, Isolate* isolate,
9576 bool is_external, void* data, size_t allocated_length,
9577 SharedFlag shared = SharedFlag::kNotShared);
9579 static bool SetupAllocatingData(Handle<JSArrayBuffer> array_buffer,
9580 Isolate* isolate, size_t allocated_length,
9581 bool initialize = true,
9582 SharedFlag shared = SharedFlag::kNotShared);
9584 // Dispatched behavior.
9585 DECLARE_PRINTER(JSArrayBuffer)
9586 DECLARE_VERIFIER(JSArrayBuffer)
9588 static const int kBackingStoreOffset = JSObject::kHeaderSize;
9589 static const int kByteLengthOffset = kBackingStoreOffset + kPointerSize;
9590 static const int kBitFieldSlot = kByteLengthOffset + kPointerSize;
9591 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
9592 static const int kBitFieldOffset = kBitFieldSlot;
9594 static const int kBitFieldOffset = kBitFieldSlot + kIntSize;
9596 static const int kSize = kBitFieldSlot + kPointerSize;
9598 static const int kSizeWithInternalFields =
9599 kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
9601 class IsExternal : public BitField<bool, 1, 1> {};
9602 class IsNeuterable : public BitField<bool, 2, 1> {};
9603 class WasNeutered : public BitField<bool, 3, 1> {};
9604 class IsShared : public BitField<bool, 4, 1> {};
9607 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
9611 class JSArrayBufferView: public JSObject {
9613 // [buffer]: ArrayBuffer that this typed array views.
9614 DECL_ACCESSORS(buffer, Object)
9616 // [byte_offset]: offset of typed array in bytes.
9617 DECL_ACCESSORS(byte_offset, Object)
9619 // [byte_length]: length of typed array in bytes.
9620 DECL_ACCESSORS(byte_length, Object)
9622 DECLARE_CAST(JSArrayBufferView)
9624 DECLARE_VERIFIER(JSArrayBufferView)
9626 inline bool WasNeutered() const;
9628 static const int kBufferOffset = JSObject::kHeaderSize;
9629 static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
9630 static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
9631 static const int kViewSize = kByteLengthOffset + kPointerSize;
9635 DECL_ACCESSORS(raw_byte_offset, Object)
9636 DECL_ACCESSORS(raw_byte_length, Object)
9639 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
9643 class JSTypedArray: public JSArrayBufferView {
9645 // [length]: length of typed array in elements.
9646 DECL_ACCESSORS(length, Object)
9647 inline uint32_t length_value() const;
9649 DECLARE_CAST(JSTypedArray)
9651 ExternalArrayType type();
9652 size_t element_size();
9654 Handle<JSArrayBuffer> GetBuffer();
9656 // Dispatched behavior.
9657 DECLARE_PRINTER(JSTypedArray)
9658 DECLARE_VERIFIER(JSTypedArray)
9660 static const int kLengthOffset = kViewSize + kPointerSize;
9661 static const int kSize = kLengthOffset + kPointerSize;
9663 static const int kSizeWithInternalFields =
9664 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9667 static Handle<JSArrayBuffer> MaterializeArrayBuffer(
9668 Handle<JSTypedArray> typed_array);
9670 DECL_ACCESSORS(raw_length, Object)
9673 DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
9677 class JSDataView: public JSArrayBufferView {
9679 DECLARE_CAST(JSDataView)
9681 // Dispatched behavior.
9682 DECLARE_PRINTER(JSDataView)
9683 DECLARE_VERIFIER(JSDataView)
9685 static const int kSize = kViewSize;
9687 static const int kSizeWithInternalFields =
9688 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9691 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
9695 // Foreign describes objects pointing from JavaScript to C structures.
9696 class Foreign: public HeapObject {
9698 // [address]: field containing the address.
9699 inline Address foreign_address();
9700 inline void set_foreign_address(Address value);
9702 DECLARE_CAST(Foreign)
9704 // Dispatched behavior.
9705 inline void ForeignIterateBody(ObjectVisitor* v);
9707 template<typename StaticVisitor>
9708 inline void ForeignIterateBody();
9710 // Dispatched behavior.
9711 DECLARE_PRINTER(Foreign)
9712 DECLARE_VERIFIER(Foreign)
9714 // Layout description.
9716 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
9717 static const int kSize = kForeignAddressOffset + kPointerSize;
9719 STATIC_ASSERT(kForeignAddressOffset == Internals::kForeignAddressOffset);
9722 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
9726 // The JSArray describes JavaScript Arrays
9727 // Such an array can be in one of two modes:
9728 // - fast, backing storage is a FixedArray and length <= elements.length();
9729 // Please note: push and pop can be used to grow and shrink the array.
9730 // - slow, backing storage is a HashTable with numbers as keys.
9731 class JSArray: public JSObject {
9733 // [length]: The length property.
9734 DECL_ACCESSORS(length, Object)
9736 // Overload the length setter to skip write barrier when the length
9737 // is set to a smi. This matches the set function on FixedArray.
9738 inline void set_length(Smi* length);
9740 static bool HasReadOnlyLength(Handle<JSArray> array);
9741 static bool WouldChangeReadOnlyLength(Handle<JSArray> array, uint32_t index);
9742 static MaybeHandle<Object> ReadOnlyLengthError(Handle<JSArray> array);
9744 // Initialize the array with the given capacity. The function may
9745 // fail due to out-of-memory situations, but only if the requested
9746 // capacity is non-zero.
9747 static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
9749 // If the JSArray has fast elements, and new_length would result in
9750 // normalization, returns true.
9751 bool SetLengthWouldNormalize(uint32_t new_length);
9752 static inline bool SetLengthWouldNormalize(Heap* heap, uint32_t new_length);
9754 // Initializes the array to a certain length.
9755 inline bool AllowsSetLength();
9757 static void SetLength(Handle<JSArray> array, uint32_t length);
9758 // Same as above but will also queue splice records if |array| is observed.
9759 static MaybeHandle<Object> ObservableSetLength(Handle<JSArray> array,
9762 // Set the content of the array to the content of storage.
9763 static inline void SetContent(Handle<JSArray> array,
9764 Handle<FixedArrayBase> storage);
9766 DECLARE_CAST(JSArray)
9768 // Dispatched behavior.
9769 DECLARE_PRINTER(JSArray)
9770 DECLARE_VERIFIER(JSArray)
9772 // Number of element slots to pre-allocate for an empty array.
9773 static const int kPreallocatedArrayElements = 4;
9775 // Layout description.
9776 static const int kLengthOffset = JSObject::kHeaderSize;
9777 static const int kSize = kLengthOffset + kPointerSize;
9780 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
9784 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
9785 Handle<Map> initial_map);
9788 // JSRegExpResult is just a JSArray with a specific initial map.
9789 // This initial map adds in-object properties for "index" and "input"
9790 // properties, as assigned by RegExp.prototype.exec, which allows
9791 // faster creation of RegExp exec results.
9792 // This class just holds constants used when creating the result.
9793 // After creation the result must be treated as a JSArray in all regards.
9794 class JSRegExpResult: public JSArray {
9796 // Offsets of object fields.
9797 static const int kIndexOffset = JSArray::kSize;
9798 static const int kInputOffset = kIndexOffset + kPointerSize;
9799 static const int kSize = kInputOffset + kPointerSize;
9800 // Indices of in-object properties.
9801 static const int kIndexIndex = 0;
9802 static const int kInputIndex = 1;
9804 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
9808 class AccessorInfo: public Struct {
9810 DECL_ACCESSORS(name, Object)
9811 DECL_ACCESSORS(flag, Smi)
9812 DECL_ACCESSORS(expected_receiver_type, Object)
9814 inline bool all_can_read();
9815 inline void set_all_can_read(bool value);
9817 inline bool all_can_write();
9818 inline void set_all_can_write(bool value);
9820 inline bool is_special_data_property();
9821 inline void set_is_special_data_property(bool value);
9823 inline PropertyAttributes property_attributes();
9824 inline void set_property_attributes(PropertyAttributes attributes);
9826 // Checks whether the given receiver is compatible with this accessor.
9827 static bool IsCompatibleReceiverMap(Isolate* isolate,
9828 Handle<AccessorInfo> info,
9830 inline bool IsCompatibleReceiver(Object* receiver);
9832 DECLARE_CAST(AccessorInfo)
9834 // Dispatched behavior.
9835 DECLARE_VERIFIER(AccessorInfo)
9837 // Append all descriptors to the array that are not already there.
9838 // Return number added.
9839 static int AppendUnique(Handle<Object> descriptors,
9840 Handle<FixedArray> array,
9841 int valid_descriptors);
9843 static const int kNameOffset = HeapObject::kHeaderSize;
9844 static const int kFlagOffset = kNameOffset + kPointerSize;
9845 static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
9846 static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
9849 inline bool HasExpectedReceiverType();
9851 // Bit positions in flag.
9852 static const int kAllCanReadBit = 0;
9853 static const int kAllCanWriteBit = 1;
9854 static const int kSpecialDataProperty = 2;
9855 class AttributesField : public BitField<PropertyAttributes, 3, 3> {};
9857 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
9861 // An accessor must have a getter, but can have no setter.
9863 // When setting a property, V8 searches accessors in prototypes.
9864 // If an accessor was found and it does not have a setter,
9865 // the request is ignored.
9867 // If the accessor in the prototype has the READ_ONLY property attribute, then
9868 // a new value is added to the derived object when the property is set.
9869 // This shadows the accessor in the prototype.
9870 class ExecutableAccessorInfo: public AccessorInfo {
9872 DECL_ACCESSORS(getter, Object)
9873 DECL_ACCESSORS(setter, Object)
9874 DECL_ACCESSORS(data, Object)
9876 DECLARE_CAST(ExecutableAccessorInfo)
9878 // Dispatched behavior.
9879 DECLARE_PRINTER(ExecutableAccessorInfo)
9880 DECLARE_VERIFIER(ExecutableAccessorInfo)
9882 static const int kGetterOffset = AccessorInfo::kSize;
9883 static const int kSetterOffset = kGetterOffset + kPointerSize;
9884 static const int kDataOffset = kSetterOffset + kPointerSize;
9885 static const int kSize = kDataOffset + kPointerSize;
9887 static void ClearSetter(Handle<ExecutableAccessorInfo> info);
9890 DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
9894 // Support for JavaScript accessors: A pair of a getter and a setter. Each
9895 // accessor can either be
9896 // * a pointer to a JavaScript function or proxy: a real accessor
9897 // * undefined: considered an accessor by the spec, too, strangely enough
9898 // * the hole: an accessor which has not been set
9899 // * a pointer to a map: a transition used to ensure map sharing
9900 class AccessorPair: public Struct {
9902 DECL_ACCESSORS(getter, Object)
9903 DECL_ACCESSORS(setter, Object)
9905 DECLARE_CAST(AccessorPair)
9907 static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
9909 inline Object* get(AccessorComponent component);
9910 inline void set(AccessorComponent component, Object* value);
9912 // Note: Returns undefined instead in case of a hole.
9913 Object* GetComponent(AccessorComponent component);
9915 // Set both components, skipping arguments which are a JavaScript null.
9916 inline void SetComponents(Object* getter, Object* setter);
9918 inline bool Equals(AccessorPair* pair);
9919 inline bool Equals(Object* getter_value, Object* setter_value);
9921 inline bool ContainsAccessor();
9923 // Dispatched behavior.
9924 DECLARE_PRINTER(AccessorPair)
9925 DECLARE_VERIFIER(AccessorPair)
9927 static const int kGetterOffset = HeapObject::kHeaderSize;
9928 static const int kSetterOffset = kGetterOffset + kPointerSize;
9929 static const int kSize = kSetterOffset + kPointerSize;
9932 // Strangely enough, in addition to functions and harmony proxies, the spec
9933 // requires us to consider undefined as a kind of accessor, too:
9935 // Object.defineProperty(obj, "foo", {get: undefined});
9936 // assertTrue("foo" in obj);
9937 inline bool IsJSAccessor(Object* obj);
9939 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
9943 class AccessCheckInfo: public Struct {
9945 DECL_ACCESSORS(named_callback, Object)
9946 DECL_ACCESSORS(indexed_callback, Object)
9947 DECL_ACCESSORS(data, Object)
9949 DECLARE_CAST(AccessCheckInfo)
9951 // Dispatched behavior.
9952 DECLARE_PRINTER(AccessCheckInfo)
9953 DECLARE_VERIFIER(AccessCheckInfo)
9955 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
9956 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
9957 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
9958 static const int kSize = kDataOffset + kPointerSize;
9961 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
9965 class InterceptorInfo: public Struct {
9967 DECL_ACCESSORS(getter, Object)
9968 DECL_ACCESSORS(setter, Object)
9969 DECL_ACCESSORS(query, Object)
9970 DECL_ACCESSORS(deleter, Object)
9971 DECL_ACCESSORS(enumerator, Object)
9972 DECL_ACCESSORS(data, Object)
9973 DECL_BOOLEAN_ACCESSORS(can_intercept_symbols)
9974 DECL_BOOLEAN_ACCESSORS(all_can_read)
9975 DECL_BOOLEAN_ACCESSORS(non_masking)
9977 inline int flags() const;
9978 inline void set_flags(int flags);
9980 DECLARE_CAST(InterceptorInfo)
9982 // Dispatched behavior.
9983 DECLARE_PRINTER(InterceptorInfo)
9984 DECLARE_VERIFIER(InterceptorInfo)
9986 static const int kGetterOffset = HeapObject::kHeaderSize;
9987 static const int kSetterOffset = kGetterOffset + kPointerSize;
9988 static const int kQueryOffset = kSetterOffset + kPointerSize;
9989 static const int kDeleterOffset = kQueryOffset + kPointerSize;
9990 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
9991 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
9992 static const int kFlagsOffset = kDataOffset + kPointerSize;
9993 static const int kSize = kFlagsOffset + kPointerSize;
9995 static const int kCanInterceptSymbolsBit = 0;
9996 static const int kAllCanReadBit = 1;
9997 static const int kNonMasking = 2;
10000 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
10004 class CallHandlerInfo: public Struct {
10006 DECL_ACCESSORS(callback, Object)
10007 DECL_ACCESSORS(data, Object)
10009 DECLARE_CAST(CallHandlerInfo)
10011 // Dispatched behavior.
10012 DECLARE_PRINTER(CallHandlerInfo)
10013 DECLARE_VERIFIER(CallHandlerInfo)
10015 static const int kCallbackOffset = HeapObject::kHeaderSize;
10016 static const int kDataOffset = kCallbackOffset + kPointerSize;
10017 static const int kSize = kDataOffset + kPointerSize;
10020 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
10024 class TemplateInfo: public Struct {
10026 DECL_ACCESSORS(tag, Object)
10027 inline int number_of_properties() const;
10028 inline void set_number_of_properties(int value);
10029 DECL_ACCESSORS(property_list, Object)
10030 DECL_ACCESSORS(property_accessors, Object)
10032 DECLARE_VERIFIER(TemplateInfo)
10034 static const int kTagOffset = HeapObject::kHeaderSize;
10035 static const int kNumberOfProperties = kTagOffset + kPointerSize;
10036 static const int kPropertyListOffset = kNumberOfProperties + kPointerSize;
10037 static const int kPropertyAccessorsOffset =
10038 kPropertyListOffset + kPointerSize;
10039 static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
10042 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
10046 class FunctionTemplateInfo: public TemplateInfo {
10048 DECL_ACCESSORS(serial_number, Object)
10049 DECL_ACCESSORS(call_code, Object)
10050 DECL_ACCESSORS(prototype_template, Object)
10051 DECL_ACCESSORS(parent_template, Object)
10052 DECL_ACCESSORS(named_property_handler, Object)
10053 DECL_ACCESSORS(indexed_property_handler, Object)
10054 DECL_ACCESSORS(instance_template, Object)
10055 DECL_ACCESSORS(class_name, Object)
10056 DECL_ACCESSORS(signature, Object)
10057 DECL_ACCESSORS(instance_call_handler, Object)
10058 DECL_ACCESSORS(access_check_info, Object)
10059 DECL_ACCESSORS(flag, Smi)
10061 inline int length() const;
10062 inline void set_length(int value);
10064 // Following properties use flag bits.
10065 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
10066 DECL_BOOLEAN_ACCESSORS(undetectable)
10067 // If the bit is set, object instances created by this function
10068 // requires access check.
10069 DECL_BOOLEAN_ACCESSORS(needs_access_check)
10070 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
10071 DECL_BOOLEAN_ACCESSORS(remove_prototype)
10072 DECL_BOOLEAN_ACCESSORS(do_not_cache)
10073 DECL_BOOLEAN_ACCESSORS(instantiated)
10074 DECL_BOOLEAN_ACCESSORS(accept_any_receiver)
10076 DECLARE_CAST(FunctionTemplateInfo)
10078 // Dispatched behavior.
10079 DECLARE_PRINTER(FunctionTemplateInfo)
10080 DECLARE_VERIFIER(FunctionTemplateInfo)
10082 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
10083 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
10084 static const int kPrototypeTemplateOffset =
10085 kCallCodeOffset + kPointerSize;
10086 static const int kParentTemplateOffset =
10087 kPrototypeTemplateOffset + kPointerSize;
10088 static const int kNamedPropertyHandlerOffset =
10089 kParentTemplateOffset + kPointerSize;
10090 static const int kIndexedPropertyHandlerOffset =
10091 kNamedPropertyHandlerOffset + kPointerSize;
10092 static const int kInstanceTemplateOffset =
10093 kIndexedPropertyHandlerOffset + kPointerSize;
10094 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
10095 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
10096 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
10097 static const int kAccessCheckInfoOffset =
10098 kInstanceCallHandlerOffset + kPointerSize;
10099 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
10100 static const int kLengthOffset = kFlagOffset + kPointerSize;
10101 static const int kSize = kLengthOffset + kPointerSize;
10103 // Returns true if |object| is an instance of this function template.
10104 bool IsTemplateFor(Object* object);
10105 bool IsTemplateFor(Map* map);
10107 // Returns the holder JSObject if the function can legally be called with this
10108 // receiver. Returns Heap::null_value() if the call is illegal.
10109 Object* GetCompatibleReceiver(Isolate* isolate, Object* receiver);
10112 // Bit position in the flag, from least significant bit position.
10113 static const int kHiddenPrototypeBit = 0;
10114 static const int kUndetectableBit = 1;
10115 static const int kNeedsAccessCheckBit = 2;
10116 static const int kReadOnlyPrototypeBit = 3;
10117 static const int kRemovePrototypeBit = 4;
10118 static const int kDoNotCacheBit = 5;
10119 static const int kInstantiatedBit = 6;
10120 static const int kAcceptAnyReceiver = 7;
10122 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
10126 class ObjectTemplateInfo: public TemplateInfo {
10128 DECL_ACCESSORS(constructor, Object)
10129 DECL_ACCESSORS(internal_field_count, Object)
10131 DECLARE_CAST(ObjectTemplateInfo)
10133 // Dispatched behavior.
10134 DECLARE_PRINTER(ObjectTemplateInfo)
10135 DECLARE_VERIFIER(ObjectTemplateInfo)
10137 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10138 static const int kInternalFieldCountOffset =
10139 kConstructorOffset + kPointerSize;
10140 static const int kSize = kInternalFieldCountOffset + kPointerSize;
10144 class TypeSwitchInfo: public Struct {
10146 DECL_ACCESSORS(types, Object)
10148 DECLARE_CAST(TypeSwitchInfo)
10150 // Dispatched behavior.
10151 DECLARE_PRINTER(TypeSwitchInfo)
10152 DECLARE_VERIFIER(TypeSwitchInfo)
10154 static const int kTypesOffset = Struct::kHeaderSize;
10155 static const int kSize = kTypesOffset + kPointerSize;
10159 // The DebugInfo class holds additional information for a function being
10161 class DebugInfo: public Struct {
10163 // The shared function info for the source being debugged.
10164 DECL_ACCESSORS(shared, SharedFunctionInfo)
10165 // Code object for the patched code. This code object is the code object
10166 // currently active for the function.
10167 DECL_ACCESSORS(code, Code)
10168 // Fixed array holding status information for each active break point.
10169 DECL_ACCESSORS(break_points, FixedArray)
10171 // Check if there is a break point at a code position.
10172 bool HasBreakPoint(int code_position);
10173 // Get the break point info object for a code position.
10174 Object* GetBreakPointInfo(int code_position);
10175 // Clear a break point.
10176 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
10178 Handle<Object> break_point_object);
10179 // Set a break point.
10180 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
10181 int source_position, int statement_position,
10182 Handle<Object> break_point_object);
10183 // Get the break point objects for a code position.
10184 Handle<Object> GetBreakPointObjects(int code_position);
10185 // Find the break point info holding this break point object.
10186 static Handle<Object> FindBreakPointInfo(Handle<DebugInfo> debug_info,
10187 Handle<Object> break_point_object);
10188 // Get the number of break points for this function.
10189 int GetBreakPointCount();
10191 DECLARE_CAST(DebugInfo)
10193 // Dispatched behavior.
10194 DECLARE_PRINTER(DebugInfo)
10195 DECLARE_VERIFIER(DebugInfo)
10197 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
10198 static const int kCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
10199 static const int kBreakPointsStateIndex = kCodeIndex + kPointerSize;
10200 static const int kSize = kBreakPointsStateIndex + kPointerSize;
10202 static const int kEstimatedNofBreakPointsInFunction = 16;
10205 static const int kNoBreakPointInfo = -1;
10207 // Lookup the index in the break_points array for a code position.
10208 int GetBreakPointInfoIndex(int code_position);
10210 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
10214 // The BreakPointInfo class holds information for break points set in a
10215 // function. The DebugInfo object holds a BreakPointInfo object for each code
10216 // position with one or more break points.
10217 class BreakPointInfo: public Struct {
10219 // The position in the code for the break point.
10220 DECL_ACCESSORS(code_position, Smi)
10221 // The position in the source for the break position.
10222 DECL_ACCESSORS(source_position, Smi)
10223 // The position in the source for the last statement before this break
10225 DECL_ACCESSORS(statement_position, Smi)
10226 // List of related JavaScript break points.
10227 DECL_ACCESSORS(break_point_objects, Object)
10229 // Removes a break point.
10230 static void ClearBreakPoint(Handle<BreakPointInfo> info,
10231 Handle<Object> break_point_object);
10232 // Set a break point.
10233 static void SetBreakPoint(Handle<BreakPointInfo> info,
10234 Handle<Object> break_point_object);
10235 // Check if break point info has this break point object.
10236 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
10237 Handle<Object> break_point_object);
10238 // Get the number of break points for this code position.
10239 int GetBreakPointCount();
10241 DECLARE_CAST(BreakPointInfo)
10243 // Dispatched behavior.
10244 DECLARE_PRINTER(BreakPointInfo)
10245 DECLARE_VERIFIER(BreakPointInfo)
10247 static const int kCodePositionIndex = Struct::kHeaderSize;
10248 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
10249 static const int kStatementPositionIndex =
10250 kSourcePositionIndex + kPointerSize;
10251 static const int kBreakPointObjectsIndex =
10252 kStatementPositionIndex + kPointerSize;
10253 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
10256 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
10260 #undef DECL_BOOLEAN_ACCESSORS
10261 #undef DECL_ACCESSORS
10262 #undef DECLARE_CAST
10263 #undef DECLARE_VERIFIER
10265 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
10266 V(kStringTable, "string_table", "(Internalized strings)") \
10267 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
10268 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
10269 V(kSmiRootList, "smi_root_list", "(Smi roots)") \
10270 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
10271 V(kTop, "top", "(Isolate)") \
10272 V(kRelocatable, "relocatable", "(Relocatable)") \
10273 V(kDebug, "debug", "(Debugger)") \
10274 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
10275 V(kHandleScope, "handlescope", "(Handle scope)") \
10276 V(kBuiltins, "builtins", "(Builtins)") \
10277 V(kGlobalHandles, "globalhandles", "(Global handles)") \
10278 V(kEternalHandles, "eternalhandles", "(Eternal handles)") \
10279 V(kThreadManager, "threadmanager", "(Thread manager)") \
10280 V(kStrongRoots, "strong roots", "(Strong roots)") \
10281 V(kExtensions, "Extensions", "(Extensions)")
10283 class VisitorSynchronization : public AllStatic {
10285 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
10287 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
10290 #undef DECLARE_ENUM
10292 static const char* const kTags[kNumberOfSyncTags];
10293 static const char* const kTagNames[kNumberOfSyncTags];
10296 // Abstract base class for visiting, and optionally modifying, the
10297 // pointers contained in Objects. Used in GC and serialization/deserialization.
10298 class ObjectVisitor BASE_EMBEDDED {
10300 virtual ~ObjectVisitor() {}
10302 // Visits a contiguous arrays of pointers in the half-open range
10303 // [start, end). Any or all of the values may be modified on return.
10304 virtual void VisitPointers(Object** start, Object** end) = 0;
10306 // Handy shorthand for visiting a single pointer.
10307 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
10309 // Visit weak next_code_link in Code object.
10310 virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
10312 // To allow lazy clearing of inline caches the visitor has
10313 // a rich interface for iterating over Code objects..
10315 // Visits a code target in the instruction stream.
10316 virtual void VisitCodeTarget(RelocInfo* rinfo);
10318 // Visits a code entry in a JS function.
10319 virtual void VisitCodeEntry(Address entry_address);
10321 // Visits a global property cell reference in the instruction stream.
10322 virtual void VisitCell(RelocInfo* rinfo);
10324 // Visits a runtime entry in the instruction stream.
10325 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
10327 // Visits the resource of an one-byte or two-byte string.
10328 virtual void VisitExternalOneByteString(
10329 v8::String::ExternalOneByteStringResource** resource) {}
10330 virtual void VisitExternalTwoByteString(
10331 v8::String::ExternalStringResource** resource) {}
10333 // Visits a debug call target in the instruction stream.
10334 virtual void VisitDebugTarget(RelocInfo* rinfo);
10336 // Visits the byte sequence in a function's prologue that contains information
10337 // about the code's age.
10338 virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
10340 // Visit pointer embedded into a code object.
10341 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
10343 // Visits an external reference embedded into a code object.
10344 virtual void VisitExternalReference(RelocInfo* rinfo);
10346 // Visits an external reference.
10347 virtual void VisitExternalReference(Address* p) {}
10349 // Visits an (encoded) internal reference.
10350 virtual void VisitInternalReference(RelocInfo* rinfo) {}
10352 // Visits a handle that has an embedder-assigned class ID.
10353 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
10355 // Intended for serialization/deserialization checking: insert, or
10356 // check for the presence of, a tag at this position in the stream.
10357 // Also used for marking up GC roots in heap snapshots.
10358 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
10362 class StructBodyDescriptor : public
10363 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
10365 static inline int SizeOf(Map* map, HeapObject* object);
10369 // BooleanBit is a helper class for setting and getting a bit in an
10371 class BooleanBit : public AllStatic {
10373 static inline bool get(Smi* smi, int bit_position) {
10374 return get(smi->value(), bit_position);
10377 static inline bool get(int value, int bit_position) {
10378 return (value & (1 << bit_position)) != 0;
10381 static inline Smi* set(Smi* smi, int bit_position, bool v) {
10382 return Smi::FromInt(set(smi->value(), bit_position, v));
10385 static inline int set(int value, int bit_position, bool v) {
10387 value |= (1 << bit_position);
10389 value &= ~(1 << bit_position);
10395 } } // namespace v8::internal
10397 #endif // V8_OBJECTS_H_