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.
8 #include "src/allocation.h"
9 #include "src/assert-scope.h"
10 #include "src/builtins.h"
11 #include "src/checks.h"
12 #include "src/elements-kind.h"
13 #include "src/field-index.h"
14 #include "src/flags.h"
16 #include "src/property-details.h"
17 #include "src/smart-pointers.h"
18 #include "src/unicode-inl.h"
21 #if V8_TARGET_ARCH_ARM
22 #include "src/arm/constants-arm.h" // NOLINT
23 #elif V8_TARGET_ARCH_ARM64
24 #include "src/arm64/constants-arm64.h" // NOLINT
25 #elif V8_TARGET_ARCH_MIPS
26 #include "src/mips/constants-mips.h" // NOLINT
27 #elif V8_TARGET_ARCH_MIPS64
28 #include "src/mips64/constants-mips64.h" // NOLINT
33 // Most object types in the V8 JavaScript are described in this file.
35 // Inheritance hierarchy:
37 // - Smi (immediate small integer)
38 // - HeapObject (superclass for everything allocated in the heap)
39 // - JSReceiver (suitable for property access)
43 // - JSArrayBufferView
56 // - JSGeneratorObject
74 // - CompilationCacheTable
75 // - CodeCacheHashTable
81 // - JSFunctionResultCache
86 // - ExternalUint8ClampedArray
87 // - ExternalInt8Array
88 // - ExternalUint8Array
89 // - ExternalInt16Array
90 // - ExternalUint16Array
91 // - ExternalInt32Array
92 // - ExternalUint32Array
93 // - ExternalFloat32Array
102 // - ExternalAsciiString
103 // - ExternalTwoByteString
104 // - InternalizedString
105 // - SeqInternalizedString
106 // - SeqOneByteInternalizedString
107 // - SeqTwoByteInternalizedString
108 // - ConsInternalizedString
109 // - ExternalInternalizedString
110 // - ExternalAsciiInternalizedString
111 // - ExternalTwoByteInternalizedString
120 // - SharedFunctionInfo
123 // - DeclaredAccessorDescriptor
125 // - DeclaredAccessorInfo
126 // - ExecutableAccessorInfo
132 // - FunctionTemplateInfo
133 // - ObjectTemplateInfo
141 // Formats of Object*:
142 // Smi: [31 bit signed int] 0
143 // HeapObject: [32 bit direct pointer] (4 byte aligned) | 01
150 enum KeyedAccessStoreMode {
152 STORE_TRANSITION_SMI_TO_OBJECT,
153 STORE_TRANSITION_SMI_TO_DOUBLE,
154 STORE_TRANSITION_DOUBLE_TO_OBJECT,
155 STORE_TRANSITION_HOLEY_SMI_TO_OBJECT,
156 STORE_TRANSITION_HOLEY_SMI_TO_DOUBLE,
157 STORE_TRANSITION_HOLEY_DOUBLE_TO_OBJECT,
158 STORE_AND_GROW_NO_TRANSITION,
159 STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT,
160 STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE,
161 STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT,
162 STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_OBJECT,
163 STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_DOUBLE,
164 STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT,
165 STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS,
166 STORE_NO_TRANSITION_HANDLE_COW
170 enum ContextualMode {
182 static const int kGrowICDelta = STORE_AND_GROW_NO_TRANSITION -
184 STATIC_ASSERT(STANDARD_STORE == 0);
185 STATIC_ASSERT(kGrowICDelta ==
186 STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT -
187 STORE_TRANSITION_SMI_TO_OBJECT);
188 STATIC_ASSERT(kGrowICDelta ==
189 STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE -
190 STORE_TRANSITION_SMI_TO_DOUBLE);
191 STATIC_ASSERT(kGrowICDelta ==
192 STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT -
193 STORE_TRANSITION_DOUBLE_TO_OBJECT);
196 static inline KeyedAccessStoreMode GetGrowStoreMode(
197 KeyedAccessStoreMode store_mode) {
198 if (store_mode < STORE_AND_GROW_NO_TRANSITION) {
199 store_mode = static_cast<KeyedAccessStoreMode>(
200 static_cast<int>(store_mode) + kGrowICDelta);
206 static inline bool IsTransitionStoreMode(KeyedAccessStoreMode store_mode) {
207 return store_mode > STANDARD_STORE &&
208 store_mode <= STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT &&
209 store_mode != STORE_AND_GROW_NO_TRANSITION;
213 static inline KeyedAccessStoreMode GetNonTransitioningStoreMode(
214 KeyedAccessStoreMode store_mode) {
215 if (store_mode >= STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS) {
218 if (store_mode >= STORE_AND_GROW_NO_TRANSITION) {
219 return STORE_AND_GROW_NO_TRANSITION;
221 return STANDARD_STORE;
225 static inline bool IsGrowStoreMode(KeyedAccessStoreMode store_mode) {
226 return store_mode >= STORE_AND_GROW_NO_TRANSITION &&
227 store_mode <= STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT;
231 // Setter that skips the write barrier if mode is SKIP_WRITE_BARRIER.
232 enum WriteBarrierMode { SKIP_WRITE_BARRIER, UPDATE_WRITE_BARRIER };
235 // Indicates whether a value can be loaded as a constant.
242 // PropertyNormalizationMode is used to specify whether to keep
243 // inobject properties when normalizing properties of a JSObject.
244 enum PropertyNormalizationMode {
245 CLEAR_INOBJECT_PROPERTIES,
246 KEEP_INOBJECT_PROPERTIES
250 // Indicates how aggressively the prototype should be optimized. FAST_PROTOTYPE
251 // will give the fastest result by tailoring the map to the prototype, but that
252 // will cause polymorphism with other objects. REGULAR_PROTOTYPE is to be used
253 // (at least for now) when dynamically modifying the prototype chain of an
254 // object using __proto__ or Object.setPrototypeOf.
255 enum PrototypeOptimizationMode { REGULAR_PROTOTYPE, FAST_PROTOTYPE };
258 // Indicates whether transitions can be added to a source map or not.
259 enum TransitionFlag {
265 enum DebugExtraICState {
267 DEBUG_PREPARE_STEP_IN
271 // Indicates whether the transition is simple: the target map of the transition
272 // either extends the current map with a new property, or it modifies the
273 // property that was added last to the current map.
274 enum SimpleTransitionFlag {
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. ASCII
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(ASCII_STRING_TYPE) \
339 V(CONS_STRING_TYPE) \
340 V(CONS_ASCII_STRING_TYPE) \
341 V(SLICED_STRING_TYPE) \
342 V(SLICED_ASCII_STRING_TYPE) \
343 V(EXTERNAL_STRING_TYPE) \
344 V(EXTERNAL_ASCII_STRING_TYPE) \
345 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
346 V(SHORT_EXTERNAL_STRING_TYPE) \
347 V(SHORT_EXTERNAL_ASCII_STRING_TYPE) \
348 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
350 V(INTERNALIZED_STRING_TYPE) \
351 V(ASCII_INTERNALIZED_STRING_TYPE) \
352 V(EXTERNAL_INTERNALIZED_STRING_TYPE) \
353 V(EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE) \
354 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
355 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE) \
356 V(SHORT_EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE) \
357 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
365 V(PROPERTY_CELL_TYPE) \
367 V(HEAP_NUMBER_TYPE) \
368 V(MUTABLE_HEAP_NUMBER_TYPE) \
372 /* Note: the order of these external array */ \
373 /* types is relied upon in */ \
374 /* Object::IsExternalArray(). */ \
375 V(EXTERNAL_INT8_ARRAY_TYPE) \
376 V(EXTERNAL_UINT8_ARRAY_TYPE) \
377 V(EXTERNAL_INT16_ARRAY_TYPE) \
378 V(EXTERNAL_UINT16_ARRAY_TYPE) \
379 V(EXTERNAL_INT32_ARRAY_TYPE) \
380 V(EXTERNAL_UINT32_ARRAY_TYPE) \
381 V(EXTERNAL_FLOAT32_ARRAY_TYPE) \
382 V(EXTERNAL_FLOAT64_ARRAY_TYPE) \
383 V(EXTERNAL_UINT8_CLAMPED_ARRAY_TYPE) \
385 V(FIXED_INT8_ARRAY_TYPE) \
386 V(FIXED_UINT8_ARRAY_TYPE) \
387 V(FIXED_INT16_ARRAY_TYPE) \
388 V(FIXED_UINT16_ARRAY_TYPE) \
389 V(FIXED_INT32_ARRAY_TYPE) \
390 V(FIXED_UINT32_ARRAY_TYPE) \
391 V(FIXED_FLOAT32_ARRAY_TYPE) \
392 V(FIXED_FLOAT64_ARRAY_TYPE) \
393 V(FIXED_UINT8_CLAMPED_ARRAY_TYPE) \
397 V(DECLARED_ACCESSOR_DESCRIPTOR_TYPE) \
398 V(DECLARED_ACCESSOR_INFO_TYPE) \
399 V(EXECUTABLE_ACCESSOR_INFO_TYPE) \
400 V(ACCESSOR_PAIR_TYPE) \
401 V(ACCESS_CHECK_INFO_TYPE) \
402 V(INTERCEPTOR_INFO_TYPE) \
403 V(CALL_HANDLER_INFO_TYPE) \
404 V(FUNCTION_TEMPLATE_INFO_TYPE) \
405 V(OBJECT_TEMPLATE_INFO_TYPE) \
406 V(SIGNATURE_INFO_TYPE) \
407 V(TYPE_SWITCH_INFO_TYPE) \
408 V(ALLOCATION_MEMENTO_TYPE) \
409 V(ALLOCATION_SITE_TYPE) \
412 V(POLYMORPHIC_CODE_CACHE_TYPE) \
413 V(TYPE_FEEDBACK_INFO_TYPE) \
414 V(ALIASED_ARGUMENTS_ENTRY_TYPE) \
417 V(FIXED_ARRAY_TYPE) \
418 V(FIXED_DOUBLE_ARRAY_TYPE) \
419 V(CONSTANT_POOL_ARRAY_TYPE) \
420 V(SHARED_FUNCTION_INFO_TYPE) \
422 V(JS_MESSAGE_OBJECT_TYPE) \
427 V(JS_CONTEXT_EXTENSION_OBJECT_TYPE) \
428 V(JS_GENERATOR_OBJECT_TYPE) \
430 V(JS_GLOBAL_OBJECT_TYPE) \
431 V(JS_BUILTINS_OBJECT_TYPE) \
432 V(JS_GLOBAL_PROXY_TYPE) \
434 V(JS_ARRAY_BUFFER_TYPE) \
435 V(JS_TYPED_ARRAY_TYPE) \
436 V(JS_DATA_VIEW_TYPE) \
440 V(JS_SET_ITERATOR_TYPE) \
441 V(JS_MAP_ITERATOR_TYPE) \
442 V(JS_WEAK_MAP_TYPE) \
443 V(JS_WEAK_SET_TYPE) \
446 V(JS_FUNCTION_TYPE) \
447 V(JS_FUNCTION_PROXY_TYPE) \
449 V(BREAK_POINT_INFO_TYPE)
452 // Since string types are not consecutive, this macro is used to
453 // iterate over them.
454 #define STRING_TYPE_LIST(V) \
456 kVariableSizeSentinel, \
459 V(ASCII_STRING_TYPE, \
460 kVariableSizeSentinel, \
463 V(CONS_STRING_TYPE, \
467 V(CONS_ASCII_STRING_TYPE, \
471 V(SLICED_STRING_TYPE, \
472 SlicedString::kSize, \
475 V(SLICED_ASCII_STRING_TYPE, \
476 SlicedString::kSize, \
477 sliced_ascii_string, \
479 V(EXTERNAL_STRING_TYPE, \
480 ExternalTwoByteString::kSize, \
483 V(EXTERNAL_ASCII_STRING_TYPE, \
484 ExternalAsciiString::kSize, \
485 external_ascii_string, \
486 ExternalAsciiString) \
487 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, \
488 ExternalTwoByteString::kSize, \
489 external_string_with_one_byte_data, \
490 ExternalStringWithOneByteData) \
491 V(SHORT_EXTERNAL_STRING_TYPE, \
492 ExternalTwoByteString::kShortSize, \
493 short_external_string, \
494 ShortExternalString) \
495 V(SHORT_EXTERNAL_ASCII_STRING_TYPE, \
496 ExternalAsciiString::kShortSize, \
497 short_external_ascii_string, \
498 ShortExternalAsciiString) \
499 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, \
500 ExternalTwoByteString::kShortSize, \
501 short_external_string_with_one_byte_data, \
502 ShortExternalStringWithOneByteData) \
504 V(INTERNALIZED_STRING_TYPE, \
505 kVariableSizeSentinel, \
506 internalized_string, \
507 InternalizedString) \
508 V(ASCII_INTERNALIZED_STRING_TYPE, \
509 kVariableSizeSentinel, \
510 ascii_internalized_string, \
511 AsciiInternalizedString) \
512 V(EXTERNAL_INTERNALIZED_STRING_TYPE, \
513 ExternalTwoByteString::kSize, \
514 external_internalized_string, \
515 ExternalInternalizedString) \
516 V(EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE, \
517 ExternalAsciiString::kSize, \
518 external_ascii_internalized_string, \
519 ExternalAsciiInternalizedString) \
520 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
521 ExternalTwoByteString::kSize, \
522 external_internalized_string_with_one_byte_data, \
523 ExternalInternalizedStringWithOneByteData) \
524 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE, \
525 ExternalTwoByteString::kShortSize, \
526 short_external_internalized_string, \
527 ShortExternalInternalizedString) \
528 V(SHORT_EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE, \
529 ExternalAsciiString::kShortSize, \
530 short_external_ascii_internalized_string, \
531 ShortExternalAsciiInternalizedString) \
532 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
533 ExternalTwoByteString::kShortSize, \
534 short_external_internalized_string_with_one_byte_data, \
535 ShortExternalInternalizedStringWithOneByteData) \
537 // A struct is a simple object a set of object-valued fields. Including an
538 // object type in this causes the compiler to generate most of the boilerplate
539 // code for the class including allocation and garbage collection routines,
540 // casts and predicates. All you need to define is the class, methods and
541 // object verification routines. Easy, no?
543 // Note that for subtle reasons related to the ordering or numerical values of
544 // type tags, elements in this list have to be added to the INSTANCE_TYPE_LIST
546 #define STRUCT_LIST(V) \
548 V(DECLARED_ACCESSOR_DESCRIPTOR, \
549 DeclaredAccessorDescriptor, \
550 declared_accessor_descriptor) \
551 V(DECLARED_ACCESSOR_INFO, DeclaredAccessorInfo, declared_accessor_info) \
552 V(EXECUTABLE_ACCESSOR_INFO, ExecutableAccessorInfo, executable_accessor_info)\
553 V(ACCESSOR_PAIR, AccessorPair, accessor_pair) \
554 V(ACCESS_CHECK_INFO, AccessCheckInfo, access_check_info) \
555 V(INTERCEPTOR_INFO, InterceptorInfo, interceptor_info) \
556 V(CALL_HANDLER_INFO, CallHandlerInfo, call_handler_info) \
557 V(FUNCTION_TEMPLATE_INFO, FunctionTemplateInfo, function_template_info) \
558 V(OBJECT_TEMPLATE_INFO, ObjectTemplateInfo, object_template_info) \
559 V(SIGNATURE_INFO, SignatureInfo, signature_info) \
560 V(TYPE_SWITCH_INFO, TypeSwitchInfo, type_switch_info) \
561 V(SCRIPT, Script, script) \
562 V(ALLOCATION_SITE, AllocationSite, allocation_site) \
563 V(ALLOCATION_MEMENTO, AllocationMemento, allocation_memento) \
564 V(CODE_CACHE, CodeCache, code_cache) \
565 V(POLYMORPHIC_CODE_CACHE, PolymorphicCodeCache, polymorphic_code_cache) \
566 V(TYPE_FEEDBACK_INFO, TypeFeedbackInfo, type_feedback_info) \
567 V(ALIASED_ARGUMENTS_ENTRY, AliasedArgumentsEntry, aliased_arguments_entry) \
568 V(DEBUG_INFO, DebugInfo, debug_info) \
569 V(BREAK_POINT_INFO, BreakPointInfo, break_point_info)
571 // We use the full 8 bits of the instance_type field to encode heap object
572 // instance types. The high-order bit (bit 7) is set if the object is not a
573 // string, and cleared if it is a string.
574 const uint32_t kIsNotStringMask = 0x80;
575 const uint32_t kStringTag = 0x0;
576 const uint32_t kNotStringTag = 0x80;
578 // Bit 6 indicates that the object is an internalized string (if set) or not.
579 // Bit 7 has to be clear as well.
580 const uint32_t kIsNotInternalizedMask = 0x40;
581 const uint32_t kNotInternalizedTag = 0x40;
582 const uint32_t kInternalizedTag = 0x0;
584 // If bit 7 is clear then bit 2 indicates whether the string consists of
585 // two-byte characters or one-byte characters.
586 const uint32_t kStringEncodingMask = 0x4;
587 const uint32_t kTwoByteStringTag = 0x0;
588 const uint32_t kOneByteStringTag = 0x4;
590 // If bit 7 is clear, the low-order 2 bits indicate the representation
592 const uint32_t kStringRepresentationMask = 0x03;
593 enum StringRepresentationTag {
595 kConsStringTag = 0x1,
596 kExternalStringTag = 0x2,
597 kSlicedStringTag = 0x3
599 const uint32_t kIsIndirectStringMask = 0x1;
600 const uint32_t kIsIndirectStringTag = 0x1;
601 STATIC_ASSERT((kSeqStringTag & kIsIndirectStringMask) == 0); // NOLINT
602 STATIC_ASSERT((kExternalStringTag & kIsIndirectStringMask) == 0); // NOLINT
603 STATIC_ASSERT((kConsStringTag &
604 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
605 STATIC_ASSERT((kSlicedStringTag &
606 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
608 // Use this mask to distinguish between cons and slice only after making
609 // sure that the string is one of the two (an indirect string).
610 const uint32_t kSlicedNotConsMask = kSlicedStringTag & ~kConsStringTag;
611 STATIC_ASSERT(IS_POWER_OF_TWO(kSlicedNotConsMask));
613 // If bit 7 is clear, then bit 3 indicates whether this two-byte
614 // string actually contains one byte data.
615 const uint32_t kOneByteDataHintMask = 0x08;
616 const uint32_t kOneByteDataHintTag = 0x08;
618 // If bit 7 is clear and string representation indicates an external string,
619 // then bit 4 indicates whether the data pointer is cached.
620 const uint32_t kShortExternalStringMask = 0x10;
621 const uint32_t kShortExternalStringTag = 0x10;
624 // A ConsString with an empty string as the right side is a candidate
625 // for being shortcut by the garbage collector. We don't allocate any
626 // non-flat internalized strings, so we do not shortcut them thereby
627 // avoiding turning internalized strings into strings. The bit-masks
628 // below contain the internalized bit as additional safety.
629 // See heap.cc, mark-compact.cc and objects-visiting.cc.
630 const uint32_t kShortcutTypeMask =
632 kIsNotInternalizedMask |
633 kStringRepresentationMask;
634 const uint32_t kShortcutTypeTag = kConsStringTag | kNotInternalizedTag;
636 static inline bool IsShortcutCandidate(int type) {
637 return ((type & kShortcutTypeMask) == kShortcutTypeTag);
643 INTERNALIZED_STRING_TYPE = kTwoByteStringTag | kSeqStringTag
645 ASCII_INTERNALIZED_STRING_TYPE = kOneByteStringTag | kSeqStringTag
647 EXTERNAL_INTERNALIZED_STRING_TYPE = kTwoByteStringTag | kExternalStringTag
649 EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE = kOneByteStringTag
650 | kExternalStringTag | kInternalizedTag,
651 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
652 EXTERNAL_INTERNALIZED_STRING_TYPE | kOneByteDataHintTag
654 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE =
655 EXTERNAL_INTERNALIZED_STRING_TYPE | kShortExternalStringTag
657 SHORT_EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE =
658 EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE | kShortExternalStringTag
660 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
661 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE
662 | kShortExternalStringTag | kInternalizedTag,
664 STRING_TYPE = INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
665 ASCII_STRING_TYPE = ASCII_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
666 CONS_STRING_TYPE = kTwoByteStringTag | kConsStringTag | kNotInternalizedTag,
667 CONS_ASCII_STRING_TYPE =
668 kOneByteStringTag | kConsStringTag | kNotInternalizedTag,
671 kTwoByteStringTag | kSlicedStringTag | kNotInternalizedTag,
672 SLICED_ASCII_STRING_TYPE =
673 kOneByteStringTag | kSlicedStringTag | kNotInternalizedTag,
674 EXTERNAL_STRING_TYPE =
675 EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
676 EXTERNAL_ASCII_STRING_TYPE =
677 EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
678 EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
679 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE
680 | kNotInternalizedTag,
681 SHORT_EXTERNAL_STRING_TYPE =
682 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
683 SHORT_EXTERNAL_ASCII_STRING_TYPE =
684 SHORT_EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
685 SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
686 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE
687 | kNotInternalizedTag,
690 SYMBOL_TYPE = kNotStringTag, // FIRST_NONSTRING_TYPE, LAST_NAME_TYPE
692 // Objects allocated in their own spaces (never in new space).
699 // "Data", objects that cannot contain non-map-word pointers to heap
702 MUTABLE_HEAP_NUMBER_TYPE,
707 EXTERNAL_INT8_ARRAY_TYPE, // FIRST_EXTERNAL_ARRAY_TYPE
708 EXTERNAL_UINT8_ARRAY_TYPE,
709 EXTERNAL_INT16_ARRAY_TYPE,
710 EXTERNAL_UINT16_ARRAY_TYPE,
711 EXTERNAL_INT32_ARRAY_TYPE,
712 EXTERNAL_UINT32_ARRAY_TYPE,
713 EXTERNAL_FLOAT32_ARRAY_TYPE,
714 EXTERNAL_FLOAT64_ARRAY_TYPE,
715 EXTERNAL_UINT8_CLAMPED_ARRAY_TYPE, // LAST_EXTERNAL_ARRAY_TYPE
717 FIXED_INT8_ARRAY_TYPE, // FIRST_FIXED_TYPED_ARRAY_TYPE
718 FIXED_UINT8_ARRAY_TYPE,
719 FIXED_INT16_ARRAY_TYPE,
720 FIXED_UINT16_ARRAY_TYPE,
721 FIXED_INT32_ARRAY_TYPE,
722 FIXED_UINT32_ARRAY_TYPE,
723 FIXED_FLOAT32_ARRAY_TYPE,
724 FIXED_FLOAT64_ARRAY_TYPE,
725 FIXED_UINT8_CLAMPED_ARRAY_TYPE, // LAST_FIXED_TYPED_ARRAY_TYPE
727 FIXED_DOUBLE_ARRAY_TYPE,
728 FILLER_TYPE, // LAST_DATA_TYPE
731 DECLARED_ACCESSOR_DESCRIPTOR_TYPE,
732 DECLARED_ACCESSOR_INFO_TYPE,
733 EXECUTABLE_ACCESSOR_INFO_TYPE,
735 ACCESS_CHECK_INFO_TYPE,
736 INTERCEPTOR_INFO_TYPE,
737 CALL_HANDLER_INFO_TYPE,
738 FUNCTION_TEMPLATE_INFO_TYPE,
739 OBJECT_TEMPLATE_INFO_TYPE,
741 TYPE_SWITCH_INFO_TYPE,
742 ALLOCATION_SITE_TYPE,
743 ALLOCATION_MEMENTO_TYPE,
746 POLYMORPHIC_CODE_CACHE_TYPE,
747 TYPE_FEEDBACK_INFO_TYPE,
748 ALIASED_ARGUMENTS_ENTRY_TYPE,
751 BREAK_POINT_INFO_TYPE,
754 CONSTANT_POOL_ARRAY_TYPE,
755 SHARED_FUNCTION_INFO_TYPE,
757 // All the following types are subtypes of JSReceiver, which corresponds to
758 // objects in the JS sense. The first and the last type in this range are
759 // the two forms of function. This organization enables using the same
760 // compares for checking the JS_RECEIVER/SPEC_OBJECT range and the
761 // NONCALLABLE_JS_OBJECT range.
762 JS_FUNCTION_PROXY_TYPE, // FIRST_JS_RECEIVER_TYPE, FIRST_JS_PROXY_TYPE
763 JS_PROXY_TYPE, // LAST_JS_PROXY_TYPE
765 JS_VALUE_TYPE, // FIRST_JS_OBJECT_TYPE
766 JS_MESSAGE_OBJECT_TYPE,
769 JS_CONTEXT_EXTENSION_OBJECT_TYPE,
770 JS_GENERATOR_OBJECT_TYPE,
772 JS_GLOBAL_OBJECT_TYPE,
773 JS_BUILTINS_OBJECT_TYPE,
774 JS_GLOBAL_PROXY_TYPE,
776 JS_ARRAY_BUFFER_TYPE,
781 JS_SET_ITERATOR_TYPE,
782 JS_MAP_ITERATOR_TYPE,
788 JS_FUNCTION_TYPE, // LAST_JS_OBJECT_TYPE, LAST_JS_RECEIVER_TYPE
792 LAST_TYPE = JS_FUNCTION_TYPE,
793 FIRST_NAME_TYPE = FIRST_TYPE,
794 LAST_NAME_TYPE = SYMBOL_TYPE,
795 FIRST_UNIQUE_NAME_TYPE = INTERNALIZED_STRING_TYPE,
796 LAST_UNIQUE_NAME_TYPE = SYMBOL_TYPE,
797 FIRST_NONSTRING_TYPE = SYMBOL_TYPE,
798 // Boundaries for testing for an external array.
799 FIRST_EXTERNAL_ARRAY_TYPE = EXTERNAL_INT8_ARRAY_TYPE,
800 LAST_EXTERNAL_ARRAY_TYPE = EXTERNAL_UINT8_CLAMPED_ARRAY_TYPE,
801 // Boundaries for testing for a fixed typed array.
802 FIRST_FIXED_TYPED_ARRAY_TYPE = FIXED_INT8_ARRAY_TYPE,
803 LAST_FIXED_TYPED_ARRAY_TYPE = FIXED_UINT8_CLAMPED_ARRAY_TYPE,
804 // Boundary for promotion to old data space/old pointer space.
805 LAST_DATA_TYPE = FILLER_TYPE,
806 // Boundary for objects represented as JSReceiver (i.e. JSObject or JSProxy).
807 // Note that there is no range for JSObject or JSProxy, since their subtypes
808 // are not continuous in this enum! The enum ranges instead reflect the
809 // external class names, where proxies are treated as either ordinary objects,
811 FIRST_JS_RECEIVER_TYPE = JS_FUNCTION_PROXY_TYPE,
812 LAST_JS_RECEIVER_TYPE = LAST_TYPE,
813 // Boundaries for testing the types represented as JSObject
814 FIRST_JS_OBJECT_TYPE = JS_VALUE_TYPE,
815 LAST_JS_OBJECT_TYPE = LAST_TYPE,
816 // Boundaries for testing the types represented as JSProxy
817 FIRST_JS_PROXY_TYPE = JS_FUNCTION_PROXY_TYPE,
818 LAST_JS_PROXY_TYPE = JS_PROXY_TYPE,
819 // Boundaries for testing whether the type is a JavaScript object.
820 FIRST_SPEC_OBJECT_TYPE = FIRST_JS_RECEIVER_TYPE,
821 LAST_SPEC_OBJECT_TYPE = LAST_JS_RECEIVER_TYPE,
822 // Boundaries for testing the types for which typeof is "object".
823 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_PROXY_TYPE,
824 LAST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_REGEXP_TYPE,
825 // Note that the types for which typeof is "function" are not continuous.
826 // Define this so that we can put assertions on discrete checks.
827 NUM_OF_CALLABLE_SPEC_OBJECT_TYPES = 2
830 const int kExternalArrayTypeCount =
831 LAST_EXTERNAL_ARRAY_TYPE - FIRST_EXTERNAL_ARRAY_TYPE + 1;
833 STATIC_ASSERT(JS_OBJECT_TYPE == Internals::kJSObjectType);
834 STATIC_ASSERT(FIRST_NONSTRING_TYPE == Internals::kFirstNonstringType);
835 STATIC_ASSERT(ODDBALL_TYPE == Internals::kOddballType);
836 STATIC_ASSERT(FOREIGN_TYPE == Internals::kForeignType);
839 #define FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(V) \
840 V(FAST_ELEMENTS_SUB_TYPE) \
841 V(DICTIONARY_ELEMENTS_SUB_TYPE) \
842 V(FAST_PROPERTIES_SUB_TYPE) \
843 V(DICTIONARY_PROPERTIES_SUB_TYPE) \
844 V(MAP_CODE_CACHE_SUB_TYPE) \
845 V(SCOPE_INFO_SUB_TYPE) \
846 V(STRING_TABLE_SUB_TYPE) \
847 V(DESCRIPTOR_ARRAY_SUB_TYPE) \
848 V(TRANSITION_ARRAY_SUB_TYPE)
850 enum FixedArraySubInstanceType {
851 #define DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE(name) name,
852 FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE)
853 #undef DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE
854 LAST_FIXED_ARRAY_SUB_TYPE = TRANSITION_ARRAY_SUB_TYPE
867 #define DECL_BOOLEAN_ACCESSORS(name) \
868 inline bool name() const; \
869 inline void set_##name(bool value); \
872 #define DECL_ACCESSORS(name, type) \
873 inline type* name() const; \
874 inline void set_##name(type* value, \
875 WriteBarrierMode mode = UPDATE_WRITE_BARRIER); \
878 #define DECLARE_CAST(type) \
879 INLINE(static type* cast(Object* object)); \
880 INLINE(static const type* cast(const Object* object));
884 class AllocationSite;
885 class AllocationSiteCreationContext;
886 class AllocationSiteUsageContext;
887 class DictionaryElementsAccessor;
888 class ElementsAccessor;
889 class FixedArrayBase;
892 class LookupIterator;
894 // We cannot just say "class HeapType;" if it is created from a template... =8-?
895 template<class> class TypeImpl;
896 struct HeapTypeConfig;
897 typedef TypeImpl<HeapTypeConfig> HeapType;
900 // A template-ized version of the IsXXX functions.
901 template <class C> inline bool Is(Object* obj);
904 #define DECLARE_VERIFIER(Name) void Name##Verify();
906 #define DECLARE_VERIFIER(Name)
910 #define DECLARE_PRINTER(Name) void Name##Print(OStream& os); // NOLINT
912 #define DECLARE_PRINTER(Name)
916 #define OBJECT_TYPE_LIST(V) \
921 #define HEAP_OBJECT_TYPE_LIST(V) \
923 V(MutableHeapNumber) \
931 V(ExternalTwoByteString) \
932 V(ExternalAsciiString) \
933 V(SeqTwoByteString) \
934 V(SeqOneByteString) \
935 V(InternalizedString) \
939 V(ExternalInt8Array) \
940 V(ExternalUint8Array) \
941 V(ExternalInt16Array) \
942 V(ExternalUint16Array) \
943 V(ExternalInt32Array) \
944 V(ExternalUint32Array) \
945 V(ExternalFloat32Array) \
946 V(ExternalFloat64Array) \
947 V(ExternalUint8ClampedArray) \
948 V(FixedTypedArrayBase) \
951 V(FixedUint16Array) \
953 V(FixedUint32Array) \
955 V(FixedFloat32Array) \
956 V(FixedFloat64Array) \
957 V(FixedUint8ClampedArray) \
962 V(JSContextExtensionObject) \
963 V(JSGeneratorObject) \
968 V(DeoptimizationInputData) \
969 V(DeoptimizationOutputData) \
972 V(FixedDoubleArray) \
973 V(ConstantPoolArray) \
980 V(SharedFunctionInfo) \
989 V(JSArrayBufferView) \
998 V(JSWeakCollection) \
1005 V(JSFunctionResultCache) \
1006 V(NormalizedMapCache) \
1007 V(CompilationCacheTable) \
1008 V(CodeCacheHashTable) \
1009 V(PolymorphicCodeCacheHashTable) \
1014 V(JSBuiltinsObject) \
1016 V(UndetectableObject) \
1017 V(AccessCheckNeeded) \
1020 V(ObjectHashTable) \
1025 #define ERROR_MESSAGES_LIST(V) \
1026 V(kNoReason, "no reason") \
1028 V(k32BitValueInRegisterIsNotZeroExtended, \
1029 "32 bit value in register is not zero-extended") \
1030 V(kAlignmentMarkerExpected, "Alignment marker expected") \
1031 V(kAllocationIsNotDoubleAligned, "Allocation is not double aligned") \
1032 V(kAPICallReturnedInvalidObject, "API call returned invalid object") \
1033 V(kArgumentsObjectValueInATestContext, \
1034 "Arguments object value in a test context") \
1035 V(kArrayBoilerplateCreationFailed, "Array boilerplate creation failed") \
1036 V(kArrayIndexConstantValueTooBig, "Array index constant value too big") \
1037 V(kAssignmentToArguments, "Assignment to arguments") \
1038 V(kAssignmentToLetVariableBeforeInitialization, \
1039 "Assignment to let variable before initialization") \
1040 V(kAssignmentToLOOKUPVariable, "Assignment to LOOKUP variable") \
1041 V(kAssignmentToParameterFunctionUsesArgumentsObject, \
1042 "Assignment to parameter, function uses arguments object") \
1043 V(kAssignmentToParameterInArgumentsObject, \
1044 "Assignment to parameter in arguments object") \
1045 V(kAttemptToUseUndefinedCache, "Attempt to use undefined cache") \
1046 V(kBadValueContextForArgumentsObjectValue, \
1047 "Bad value context for arguments object value") \
1048 V(kBadValueContextForArgumentsValue, \
1049 "Bad value context for arguments value") \
1050 V(kBailedOutDueToDependencyChange, "Bailed out due to dependency change") \
1051 V(kBailoutWasNotPrepared, "Bailout was not prepared") \
1052 V(kBinaryStubGenerateFloatingPointCode, \
1053 "BinaryStub_GenerateFloatingPointCode") \
1054 V(kBothRegistersWereSmisInSelectNonSmi, \
1055 "Both registers were smis in SelectNonSmi") \
1056 V(kCallToAJavaScriptRuntimeFunction, \
1057 "Call to a JavaScript runtime function") \
1058 V(kCannotTranslatePositionInChangedArea, \
1059 "Cannot translate position in changed area") \
1060 V(kCodeGenerationFailed, "Code generation failed") \
1061 V(kCodeObjectNotProperlyPatched, "Code object not properly patched") \
1062 V(kCompoundAssignmentToLookupSlot, "Compound assignment to lookup slot") \
1063 V(kContextAllocatedArguments, "Context-allocated arguments") \
1064 V(kCopyBuffersOverlap, "Copy buffers overlap") \
1065 V(kCouldNotGenerateZero, "Could not generate +0.0") \
1066 V(kCouldNotGenerateNegativeZero, "Could not generate -0.0") \
1067 V(kDebuggerHasBreakPoints, "Debugger has break points") \
1068 V(kDebuggerStatement, "DebuggerStatement") \
1069 V(kDeclarationInCatchContext, "Declaration in catch context") \
1070 V(kDeclarationInWithContext, "Declaration in with context") \
1071 V(kDefaultNaNModeNotSet, "Default NaN mode not set") \
1072 V(kDeleteWithGlobalVariable, "Delete with global variable") \
1073 V(kDeleteWithNonGlobalVariable, "Delete with non-global variable") \
1074 V(kDestinationOfCopyNotAligned, "Destination of copy not aligned") \
1075 V(kDontDeleteCellsCannotContainTheHole, \
1076 "DontDelete cells can't contain the hole") \
1077 V(kDoPushArgumentNotImplementedForDoubleType, \
1078 "DoPushArgument not implemented for double type") \
1079 V(kEliminatedBoundsCheckFailed, "Eliminated bounds check failed") \
1080 V(kEmitLoadRegisterUnsupportedDoubleImmediate, \
1081 "EmitLoadRegister: Unsupported double immediate") \
1083 V(kExpected0AsASmiSentinel, "Expected 0 as a Smi sentinel") \
1084 V(kExpectedAlignmentMarker, "Expected alignment marker") \
1085 V(kExpectedAllocationSite, "Expected allocation site") \
1086 V(kExpectedFunctionObject, "Expected function object in register") \
1087 V(kExpectedHeapNumber, "Expected HeapNumber") \
1088 V(kExpectedNativeContext, "Expected native context") \
1089 V(kExpectedNonIdenticalObjects, "Expected non-identical objects") \
1090 V(kExpectedNonNullContext, "Expected non-null context") \
1091 V(kExpectedPositiveZero, "Expected +0.0") \
1092 V(kExpectedAllocationSiteInCell, \
1093 "Expected AllocationSite in property cell") \
1094 V(kExpectedFixedArrayInFeedbackVector, \
1095 "Expected fixed array in feedback vector") \
1096 V(kExpectedFixedArrayInRegisterA2, \
1097 "Expected fixed array in register a2") \
1098 V(kExpectedFixedArrayInRegisterEbx, \
1099 "Expected fixed array in register ebx") \
1100 V(kExpectedFixedArrayInRegisterR2, \
1101 "Expected fixed array in register r2") \
1102 V(kExpectedFixedArrayInRegisterRbx, \
1103 "Expected fixed array in register rbx") \
1104 V(kExpectedNewSpaceObject, "Expected new space object") \
1105 V(kExpectedSmiOrHeapNumber, "Expected smi or HeapNumber") \
1106 V(kExpectedUndefinedOrCell, \
1107 "Expected undefined or cell in register") \
1108 V(kExpectingAlignmentForCopyBytes, \
1109 "Expecting alignment for CopyBytes") \
1110 V(kExportDeclaration, "Export declaration") \
1111 V(kExternalStringExpectedButNotFound, \
1112 "External string expected, but not found") \
1113 V(kFailedBailedOutLastTime, "Failed/bailed out last time") \
1114 V(kForInStatementIsNotFastCase, "ForInStatement is not fast case") \
1115 V(kForInStatementOptimizationIsDisabled, \
1116 "ForInStatement optimization is disabled") \
1117 V(kForInStatementWithNonLocalEachVariable, \
1118 "ForInStatement with non-local each variable") \
1119 V(kForOfStatement, "ForOfStatement") \
1120 V(kFrameIsExpectedToBeAligned, "Frame is expected to be aligned") \
1121 V(kFunctionCallsEval, "Function calls eval") \
1122 V(kFunctionIsAGenerator, "Function is a generator") \
1123 V(kFunctionWithIllegalRedeclaration, "Function with illegal redeclaration") \
1124 V(kGeneratedCodeIsTooLarge, "Generated code is too large") \
1125 V(kGeneratorFailedToResume, "Generator failed to resume") \
1126 V(kGenerator, "Generator") \
1127 V(kGlobalFunctionsMustHaveInitialMap, \
1128 "Global functions must have initial map") \
1129 V(kHeapNumberMapRegisterClobbered, "HeapNumberMap register clobbered") \
1130 V(kHydrogenFilter, "Optimization disabled by filter") \
1131 V(kImportDeclaration, "Import declaration") \
1132 V(kImproperObjectOnPrototypeChainForStore, \
1133 "Improper object on prototype chain for store") \
1134 V(kIndexIsNegative, "Index is negative") \
1135 V(kIndexIsTooLarge, "Index is too large") \
1136 V(kInlinedRuntimeFunctionClassOf, "Inlined runtime function: ClassOf") \
1137 V(kInlinedRuntimeFunctionFastAsciiArrayJoin, \
1138 "Inlined runtime function: FastAsciiArrayJoin") \
1139 V(kInlinedRuntimeFunctionGeneratorNext, \
1140 "Inlined runtime function: GeneratorNext") \
1141 V(kInlinedRuntimeFunctionGeneratorThrow, \
1142 "Inlined runtime function: GeneratorThrow") \
1143 V(kInlinedRuntimeFunctionGetFromCache, \
1144 "Inlined runtime function: GetFromCache") \
1145 V(kInlinedRuntimeFunctionIsNonNegativeSmi, \
1146 "Inlined runtime function: IsNonNegativeSmi") \
1147 V(kInlinedRuntimeFunctionIsStringWrapperSafeForDefaultValueOf, \
1148 "Inlined runtime function: IsStringWrapperSafeForDefaultValueOf") \
1149 V(kInliningBailedOut, "Inlining bailed out") \
1150 V(kInputGPRIsExpectedToHaveUpper32Cleared, \
1151 "Input GPR is expected to have upper32 cleared") \
1152 V(kInputStringTooLong, "Input string too long") \
1153 V(kInstanceofStubUnexpectedCallSiteCacheCheck, \
1154 "InstanceofStub unexpected call site cache (check)") \
1155 V(kInstanceofStubUnexpectedCallSiteCacheCmp1, \
1156 "InstanceofStub unexpected call site cache (cmp 1)") \
1157 V(kInstanceofStubUnexpectedCallSiteCacheCmp2, \
1158 "InstanceofStub unexpected call site cache (cmp 2)") \
1159 V(kInstanceofStubUnexpectedCallSiteCacheMov, \
1160 "InstanceofStub unexpected call site cache (mov)") \
1161 V(kInteger32ToSmiFieldWritingToNonSmiLocation, \
1162 "Integer32ToSmiField writing to non-smi location") \
1163 V(kInvalidCaptureReferenced, "Invalid capture referenced") \
1164 V(kInvalidElementsKindForInternalArrayOrInternalPackedArray, \
1165 "Invalid ElementsKind for InternalArray or InternalPackedArray") \
1166 V(kInvalidFullCodegenState, "invalid full-codegen state") \
1167 V(kInvalidHandleScopeLevel, "Invalid HandleScope level") \
1168 V(kInvalidLeftHandSideInAssignment, "Invalid left-hand side in assignment") \
1169 V(kInvalidLhsInCompoundAssignment, "Invalid lhs in compound assignment") \
1170 V(kInvalidLhsInCountOperation, "Invalid lhs in count operation") \
1171 V(kInvalidMinLength, "Invalid min_length") \
1172 V(kJSGlobalObjectNativeContextShouldBeANativeContext, \
1173 "JSGlobalObject::native_context should be a native context") \
1174 V(kJSGlobalProxyContextShouldNotBeNull, \
1175 "JSGlobalProxy::context() should not be null") \
1176 V(kJSObjectWithFastElementsMapHasSlowElements, \
1177 "JSObject with fast elements map has slow elements") \
1178 V(kLetBindingReInitialization, "Let binding re-initialization") \
1179 V(kLhsHasBeenClobbered, "lhs has been clobbered") \
1180 V(kLiveBytesCountOverflowChunkSize, "Live Bytes Count overflow chunk size") \
1181 V(kLiveEdit, "LiveEdit") \
1182 V(kLookupVariableInCountOperation, \
1183 "Lookup variable in count operation") \
1184 V(kMapBecameDeprecated, "Map became deprecated") \
1185 V(kMapBecameUnstable, "Map became unstable") \
1186 V(kMapIsNoLongerInEax, "Map is no longer in eax") \
1187 V(kModuleDeclaration, "Module declaration") \
1188 V(kModuleLiteral, "Module literal") \
1189 V(kModulePath, "Module path") \
1190 V(kModuleStatement, "Module statement") \
1191 V(kModuleVariable, "Module variable") \
1192 V(kModuleUrl, "Module url") \
1193 V(kNativeFunctionLiteral, "Native function literal") \
1194 V(kNeedSmiLiteral, "Need a Smi literal here") \
1195 V(kNoCasesLeft, "No cases left") \
1196 V(kNoEmptyArraysHereInEmitFastAsciiArrayJoin, \
1197 "No empty arrays here in EmitFastAsciiArrayJoin") \
1198 V(kNonInitializerAssignmentToConst, \
1199 "Non-initializer assignment to const") \
1200 V(kNonSmiIndex, "Non-smi index") \
1201 V(kNonSmiKeyInArrayLiteral, "Non-smi key in array literal") \
1202 V(kNonSmiValue, "Non-smi value") \
1203 V(kNonObject, "Non-object value") \
1204 V(kNotEnoughVirtualRegistersForValues, \
1205 "Not enough virtual registers for values") \
1206 V(kNotEnoughSpillSlotsForOsr, \
1207 "Not enough spill slots for OSR") \
1208 V(kNotEnoughVirtualRegistersRegalloc, \
1209 "Not enough virtual registers (regalloc)") \
1210 V(kObjectFoundInSmiOnlyArray, "Object found in smi-only array") \
1211 V(kObjectLiteralWithComplexProperty, \
1212 "Object literal with complex property") \
1213 V(kOddballInStringTableIsNotUndefinedOrTheHole, \
1214 "Oddball in string table is not undefined or the hole") \
1215 V(kOffsetOutOfRange, "Offset out of range") \
1216 V(kOperandIsASmiAndNotAName, "Operand is a smi and not a name") \
1217 V(kOperandIsASmiAndNotAString, "Operand is a smi and not a string") \
1218 V(kOperandIsASmi, "Operand is a smi") \
1219 V(kOperandIsNotAName, "Operand is not a name") \
1220 V(kOperandIsNotANumber, "Operand is not a number") \
1221 V(kOperandIsNotASmi, "Operand is not a smi") \
1222 V(kOperandIsNotAString, "Operand is not a string") \
1223 V(kOperandIsNotSmi, "Operand is not smi") \
1224 V(kOperandNotANumber, "Operand not a number") \
1225 V(kObjectTagged, "The object is tagged") \
1226 V(kObjectNotTagged, "The object is not tagged") \
1227 V(kOptimizationDisabled, "Optimization is disabled") \
1228 V(kOptimizedTooManyTimes, "Optimized too many times") \
1229 V(kOutOfVirtualRegistersWhileTryingToAllocateTempRegister, \
1230 "Out of virtual registers while trying to allocate temp register") \
1231 V(kParseScopeError, "Parse/scope error") \
1232 V(kPossibleDirectCallToEval, "Possible direct call to eval") \
1233 V(kPreconditionsWereNotMet, "Preconditions were not met") \
1234 V(kPropertyAllocationCountFailed, "Property allocation count failed") \
1235 V(kReceivedInvalidReturnAddress, "Received invalid return address") \
1236 V(kReferenceToAVariableWhichRequiresDynamicLookup, \
1237 "Reference to a variable which requires dynamic lookup") \
1238 V(kReferenceToGlobalLexicalVariable, \
1239 "Reference to global lexical variable") \
1240 V(kReferenceToUninitializedVariable, "Reference to uninitialized variable") \
1241 V(kRegisterDidNotMatchExpectedRoot, "Register did not match expected root") \
1242 V(kRegisterWasClobbered, "Register was clobbered") \
1243 V(kRememberedSetPointerInNewSpace, "Remembered set pointer is in new space") \
1244 V(kReturnAddressNotFoundInFrame, "Return address not found in frame") \
1245 V(kRhsHasBeenClobbered, "Rhs has been clobbered") \
1246 V(kScopedBlock, "ScopedBlock") \
1247 V(kSmiAdditionOverflow, "Smi addition overflow") \
1248 V(kSmiSubtractionOverflow, "Smi subtraction overflow") \
1249 V(kStackAccessBelowStackPointer, "Stack access below stack pointer") \
1250 V(kStackFrameTypesMustMatch, "Stack frame types must match") \
1251 V(kSwitchStatementMixedOrNonLiteralSwitchLabels, \
1252 "SwitchStatement: mixed or non-literal switch labels") \
1253 V(kSwitchStatementTooManyClauses, "SwitchStatement: too many clauses") \
1254 V(kTheCurrentStackPointerIsBelowCsp, \
1255 "The current stack pointer is below csp") \
1256 V(kTheInstructionShouldBeALui, "The instruction should be a lui") \
1257 V(kTheInstructionShouldBeAnOri, "The instruction should be an ori") \
1258 V(kTheInstructionToPatchShouldBeALoadFromConstantPool, \
1259 "The instruction to patch should be a load from the constant pool") \
1260 V(kTheInstructionToPatchShouldBeAnLdrLiteral, \
1261 "The instruction to patch should be a ldr literal") \
1262 V(kTheInstructionToPatchShouldBeALui, \
1263 "The instruction to patch should be a lui") \
1264 V(kTheInstructionToPatchShouldBeAnOri, \
1265 "The instruction to patch should be an ori") \
1266 V(kTheSourceAndDestinationAreTheSame, \
1267 "The source and destination are the same") \
1268 V(kTheStackPointerIsNotAligned, "The stack pointer is not aligned.") \
1269 V(kTheStackWasCorruptedByMacroAssemblerCall, \
1270 "The stack was corrupted by MacroAssembler::Call()") \
1271 V(kTooManyParametersLocals, "Too many parameters/locals") \
1272 V(kTooManyParameters, "Too many parameters") \
1273 V(kTooManySpillSlotsNeededForOSR, "Too many spill slots needed for OSR") \
1274 V(kToOperand32UnsupportedImmediate, "ToOperand32 unsupported immediate.") \
1275 V(kToOperandIsDoubleRegisterUnimplemented, \
1276 "ToOperand IsDoubleRegister unimplemented") \
1277 V(kToOperandUnsupportedDoubleImmediate, \
1278 "ToOperand Unsupported double immediate") \
1279 V(kTryCatchStatement, "TryCatchStatement") \
1280 V(kTryFinallyStatement, "TryFinallyStatement") \
1281 V(kUnableToEncodeValueAsSmi, "Unable to encode value as smi") \
1282 V(kUnalignedAllocationInNewSpace, "Unaligned allocation in new space") \
1283 V(kUnalignedCellInWriteBarrier, "Unaligned cell in write barrier") \
1284 V(kUndefinedValueNotLoaded, "Undefined value not loaded") \
1285 V(kUndoAllocationOfNonAllocatedMemory, \
1286 "Undo allocation of non allocated memory") \
1287 V(kUnexpectedAllocationTop, "Unexpected allocation top") \
1288 V(kUnexpectedColorFound, "Unexpected color bit pattern found") \
1289 V(kUnexpectedElementsKindInArrayConstructor, \
1290 "Unexpected ElementsKind in array constructor") \
1291 V(kUnexpectedFallthroughFromCharCodeAtSlowCase, \
1292 "Unexpected fallthrough from CharCodeAt slow case") \
1293 V(kUnexpectedFallthroughFromCharFromCodeSlowCase, \
1294 "Unexpected fallthrough from CharFromCode slow case") \
1295 V(kUnexpectedFallThroughFromStringComparison, \
1296 "Unexpected fall-through from string comparison") \
1297 V(kUnexpectedFallThroughInBinaryStubGenerateFloatingPointCode, \
1298 "Unexpected fall-through in BinaryStub_GenerateFloatingPointCode") \
1299 V(kUnexpectedFallthroughToCharCodeAtSlowCase, \
1300 "Unexpected fallthrough to CharCodeAt slow case") \
1301 V(kUnexpectedFallthroughToCharFromCodeSlowCase, \
1302 "Unexpected fallthrough to CharFromCode slow case") \
1303 V(kUnexpectedFPUStackDepthAfterInstruction, \
1304 "Unexpected FPU stack depth after instruction") \
1305 V(kUnexpectedInitialMapForArrayFunction1, \
1306 "Unexpected initial map for Array function (1)") \
1307 V(kUnexpectedInitialMapForArrayFunction2, \
1308 "Unexpected initial map for Array function (2)") \
1309 V(kUnexpectedInitialMapForArrayFunction, \
1310 "Unexpected initial map for Array function") \
1311 V(kUnexpectedInitialMapForInternalArrayFunction, \
1312 "Unexpected initial map for InternalArray function") \
1313 V(kUnexpectedLevelAfterReturnFromApiCall, \
1314 "Unexpected level after return from api call") \
1315 V(kUnexpectedNegativeValue, "Unexpected negative value") \
1316 V(kUnexpectedNumberOfPreAllocatedPropertyFields, \
1317 "Unexpected number of pre-allocated property fields") \
1318 V(kUnexpectedFPCRMode, "Unexpected FPCR mode.") \
1319 V(kUnexpectedSmi, "Unexpected smi value") \
1320 V(kUnexpectedStringFunction, "Unexpected String function") \
1321 V(kUnexpectedStringType, "Unexpected string type") \
1322 V(kUnexpectedStringWrapperInstanceSize, \
1323 "Unexpected string wrapper instance size") \
1324 V(kUnexpectedTypeForRegExpDataFixedArrayExpected, \
1325 "Unexpected type for RegExp data, FixedArray expected") \
1326 V(kUnexpectedValue, "Unexpected value") \
1327 V(kUnexpectedUnusedPropertiesOfStringWrapper, \
1328 "Unexpected unused properties of string wrapper") \
1329 V(kUnimplemented, "unimplemented") \
1330 V(kUninitializedKSmiConstantRegister, "Uninitialized kSmiConstantRegister") \
1331 V(kUnknown, "Unknown") \
1332 V(kUnsupportedConstCompoundAssignment, \
1333 "Unsupported const compound assignment") \
1334 V(kUnsupportedCountOperationWithConst, \
1335 "Unsupported count operation with const") \
1336 V(kUnsupportedDoubleImmediate, "Unsupported double immediate") \
1337 V(kUnsupportedLetCompoundAssignment, "Unsupported let compound assignment") \
1338 V(kUnsupportedLookupSlotInDeclaration, \
1339 "Unsupported lookup slot in declaration") \
1340 V(kUnsupportedNonPrimitiveCompare, "Unsupported non-primitive compare") \
1341 V(kUnsupportedPhiUseOfArguments, "Unsupported phi use of arguments") \
1342 V(kUnsupportedPhiUseOfConstVariable, \
1343 "Unsupported phi use of const variable") \
1344 V(kUnsupportedTaggedImmediate, "Unsupported tagged immediate") \
1345 V(kVariableResolvedToWithContext, "Variable resolved to with context") \
1346 V(kWeShouldNotHaveAnEmptyLexicalContext, \
1347 "We should not have an empty lexical context") \
1348 V(kWithStatement, "WithStatement") \
1349 V(kWrongAddressOrValuePassedToRecordWrite, \
1350 "Wrong address or value passed to RecordWrite") \
1354 #define ERROR_MESSAGES_CONSTANTS(C, T) C,
1355 enum BailoutReason {
1356 ERROR_MESSAGES_LIST(ERROR_MESSAGES_CONSTANTS)
1359 #undef ERROR_MESSAGES_CONSTANTS
1362 const char* GetBailoutReason(BailoutReason reason);
1365 // Object is the abstract superclass for all classes in the
1366 // object hierarchy.
1367 // Object does not use any virtual functions to avoid the
1368 // allocation of the C++ vtable.
1369 // Since both Smi and HeapObject are subclasses of Object no
1370 // data members can be present in Object.
1374 bool IsObject() const { return true; }
1376 #define IS_TYPE_FUNCTION_DECL(type_) INLINE(bool Is##type_() const);
1377 OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1378 HEAP_OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1379 #undef IS_TYPE_FUNCTION_DECL
1381 // A non-keyed store is of the form a.x = foo or a["x"] = foo whereas
1382 // a keyed store is of the form a[expression] = foo.
1383 enum StoreFromKeyed {
1384 MAY_BE_STORE_FROM_KEYED,
1385 CERTAINLY_NOT_STORE_FROM_KEYED
1388 INLINE(bool IsFixedArrayBase() const);
1389 INLINE(bool IsExternal() const);
1390 INLINE(bool IsAccessorInfo() const);
1392 INLINE(bool IsStruct() const);
1393 #define DECLARE_STRUCT_PREDICATE(NAME, Name, name) \
1394 INLINE(bool Is##Name() const);
1395 STRUCT_LIST(DECLARE_STRUCT_PREDICATE)
1396 #undef DECLARE_STRUCT_PREDICATE
1398 INLINE(bool IsSpecObject()) const;
1399 INLINE(bool IsSpecFunction()) const;
1400 INLINE(bool IsTemplateInfo()) const;
1401 INLINE(bool IsNameDictionary() const);
1402 INLINE(bool IsSeededNumberDictionary() const);
1403 INLINE(bool IsUnseededNumberDictionary() const);
1404 INLINE(bool IsOrderedHashSet() const);
1405 INLINE(bool IsOrderedHashMap() const);
1406 bool IsCallable() const;
1409 INLINE(bool IsUndefined() const);
1410 INLINE(bool IsNull() const);
1411 INLINE(bool IsTheHole() const);
1412 INLINE(bool IsException() const);
1413 INLINE(bool IsUninitialized() const);
1414 INLINE(bool IsTrue() const);
1415 INLINE(bool IsFalse() const);
1416 INLINE(bool IsArgumentsMarker() const);
1418 // Filler objects (fillers and free space objects).
1419 INLINE(bool IsFiller() const);
1421 // Extract the number.
1422 inline double Number();
1423 INLINE(bool IsNaN() const);
1424 INLINE(bool IsMinusZero() const);
1425 bool ToInt32(int32_t* value);
1426 bool ToUint32(uint32_t* value);
1428 inline Representation OptimalRepresentation() {
1429 if (!FLAG_track_fields) return Representation::Tagged();
1431 return Representation::Smi();
1432 } else if (FLAG_track_double_fields && IsHeapNumber()) {
1433 return Representation::Double();
1434 } else if (FLAG_track_computed_fields && IsUninitialized()) {
1435 return Representation::None();
1436 } else if (FLAG_track_heap_object_fields) {
1437 DCHECK(IsHeapObject());
1438 return Representation::HeapObject();
1440 return Representation::Tagged();
1444 inline bool FitsRepresentation(Representation representation) {
1445 if (FLAG_track_fields && representation.IsNone()) {
1447 } else if (FLAG_track_fields && representation.IsSmi()) {
1449 } else if (FLAG_track_double_fields && representation.IsDouble()) {
1450 return IsMutableHeapNumber() || IsNumber();
1451 } else if (FLAG_track_heap_object_fields && representation.IsHeapObject()) {
1452 return IsHeapObject();
1457 Handle<HeapType> OptimalType(Isolate* isolate, Representation representation);
1459 inline static Handle<Object> NewStorageFor(Isolate* isolate,
1460 Handle<Object> object,
1461 Representation representation);
1463 inline static Handle<Object> WrapForRead(Isolate* isolate,
1464 Handle<Object> object,
1465 Representation representation);
1467 // Returns true if the object is of the correct type to be used as a
1468 // implementation of a JSObject's elements.
1469 inline bool HasValidElements();
1471 inline bool HasSpecificClassOf(String* name);
1473 bool BooleanValue(); // ECMA-262 9.2.
1475 // Convert to a JSObject if needed.
1476 // native_context is used when creating wrapper object.
1477 static inline MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1478 Handle<Object> object);
1479 static MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1480 Handle<Object> object,
1481 Handle<Context> context);
1483 // Converts this to a Smi if possible.
1484 static MUST_USE_RESULT inline MaybeHandle<Smi> ToSmi(Isolate* isolate,
1485 Handle<Object> object);
1487 void Lookup(Handle<Name> name, LookupResult* result);
1489 MUST_USE_RESULT static MaybeHandle<Object> GetProperty(LookupIterator* it);
1491 // Implementation of [[Put]], ECMA-262 5th edition, section 8.12.5.
1492 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1493 Handle<Object> object, Handle<Name> key, Handle<Object> value,
1494 StrictMode strict_mode,
1495 StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
1497 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1498 LookupIterator* it, Handle<Object> value, StrictMode strict_mode,
1499 StoreFromKeyed store_mode);
1500 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1501 LookupIterator* it, Handle<Object> value, StrictMode strict_mode);
1502 MUST_USE_RESULT static MaybeHandle<Object> SetDataProperty(
1503 LookupIterator* it, Handle<Object> value);
1504 MUST_USE_RESULT static MaybeHandle<Object> AddDataProperty(
1505 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1506 StrictMode strict_mode, StoreFromKeyed store_mode);
1507 MUST_USE_RESULT static inline MaybeHandle<Object> GetPropertyOrElement(
1508 Handle<Object> object,
1510 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1512 Handle<Object> object,
1514 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1515 Handle<Object> object,
1518 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithAccessor(
1519 Handle<Object> receiver,
1521 Handle<JSObject> holder,
1522 Handle<Object> structure);
1523 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithAccessor(
1524 Handle<Object> receiver, Handle<Name> name, Handle<Object> value,
1525 Handle<JSObject> holder, Handle<Object> structure,
1526 StrictMode strict_mode);
1528 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithDefinedGetter(
1529 Handle<Object> receiver,
1530 Handle<JSReceiver> getter);
1531 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithDefinedSetter(
1532 Handle<Object> receiver,
1533 Handle<JSReceiver> setter,
1534 Handle<Object> value);
1536 MUST_USE_RESULT static inline MaybeHandle<Object> GetElement(
1538 Handle<Object> object,
1541 MUST_USE_RESULT static MaybeHandle<Object> GetElementWithReceiver(
1543 Handle<Object> object,
1544 Handle<Object> receiver,
1547 // Returns the permanent hash code associated with this object. May return
1548 // undefined if not yet created.
1551 // Returns the permanent hash code associated with this object depending on
1552 // the actual object type. May create and store a hash code if needed and none
1554 static Handle<Smi> GetOrCreateHash(Isolate* isolate, Handle<Object> object);
1556 // Checks whether this object has the same value as the given one. This
1557 // function is implemented according to ES5, section 9.12 and can be used
1558 // to implement the Harmony "egal" function.
1559 bool SameValue(Object* other);
1561 // Checks whether this object has the same value as the given one.
1562 // +0 and -0 are treated equal. Everything else is the same as SameValue.
1563 // This function is implemented according to ES6, section 7.2.4 and is used
1564 // by ES6 Map and Set.
1565 bool SameValueZero(Object* other);
1567 // Tries to convert an object to an array index. Returns true and sets
1568 // the output parameter if it succeeds.
1569 inline bool ToArrayIndex(uint32_t* index);
1571 // Returns true if this is a JSValue containing a string and the index is
1572 // < the length of the string. Used to implement [] on strings.
1573 inline bool IsStringObjectWithCharacterAt(uint32_t index);
1575 DECLARE_VERIFIER(Object)
1577 // Verify a pointer is a valid object pointer.
1578 static void VerifyPointer(Object* p);
1581 inline void VerifyApiCallResultType();
1583 // Prints this object without details.
1584 void ShortPrint(FILE* out = stdout);
1586 // Prints this object without details to a message accumulator.
1587 void ShortPrint(StringStream* accumulator);
1589 DECLARE_CAST(Object)
1591 // Layout description.
1592 static const int kHeaderSize = 0; // Object does not take up any space.
1595 // For our gdb macros, we should perhaps change these in the future.
1598 // Prints this object with details.
1599 void Print(OStream& os); // NOLINT
1603 friend class LookupIterator;
1604 friend class PrototypeIterator;
1606 // Return the map of the root of object's prototype chain.
1607 Map* GetRootMap(Isolate* isolate);
1609 DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
1614 explicit Brief(const Object* const v) : value(v) {}
1615 const Object* value;
1619 OStream& operator<<(OStream& os, const Brief& v);
1622 // Smi represents integer Numbers that can be stored in 31 bits.
1623 // Smis are immediate which means they are NOT allocated in the heap.
1624 // The this pointer has the following format: [31 bit signed int] 0
1625 // For long smis it has the following format:
1626 // [32 bit signed int] [31 bits zero padding] 0
1627 // Smi stands for small integer.
1628 class Smi: public Object {
1630 // Returns the integer value.
1631 inline int value() const;
1633 // Convert a value to a Smi object.
1634 static inline Smi* FromInt(int value);
1636 static inline Smi* FromIntptr(intptr_t value);
1638 // Returns whether value can be represented in a Smi.
1639 static inline bool IsValid(intptr_t value);
1643 // Dispatched behavior.
1644 void SmiPrint(OStream& os) const; // NOLINT
1645 DECLARE_VERIFIER(Smi)
1647 static const int kMinValue =
1648 (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1649 static const int kMaxValue = -(kMinValue + 1);
1652 DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1656 // Heap objects typically have a map pointer in their first word. However,
1657 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1658 // encoded in the first word. The class MapWord is an abstraction of the
1659 // value in a heap object's first word.
1660 class MapWord BASE_EMBEDDED {
1662 // Normal state: the map word contains a map pointer.
1664 // Create a map word from a map pointer.
1665 static inline MapWord FromMap(const Map* map);
1667 // View this map word as a map pointer.
1668 inline Map* ToMap();
1671 // Scavenge collection: the map word of live objects in the from space
1672 // contains a forwarding address (a heap object pointer in the to space).
1674 // True if this map word is a forwarding address for a scavenge
1675 // collection. Only valid during a scavenge collection (specifically,
1676 // when all map words are heap object pointers, i.e. not during a full GC).
1677 inline bool IsForwardingAddress();
1679 // Create a map word from a forwarding address.
1680 static inline MapWord FromForwardingAddress(HeapObject* object);
1682 // View this map word as a forwarding address.
1683 inline HeapObject* ToForwardingAddress();
1685 static inline MapWord FromRawValue(uintptr_t value) {
1686 return MapWord(value);
1689 inline uintptr_t ToRawValue() {
1694 // HeapObject calls the private constructor and directly reads the value.
1695 friend class HeapObject;
1697 explicit MapWord(uintptr_t value) : value_(value) {}
1703 // HeapObject is the superclass for all classes describing heap allocated
1705 class HeapObject: public Object {
1707 // [map]: Contains a map which contains the object's reflective
1709 inline Map* map() const;
1710 inline void set_map(Map* value);
1711 // The no-write-barrier version. This is OK if the object is white and in
1712 // new space, or if the value is an immortal immutable object, like the maps
1713 // of primitive (non-JS) objects like strings, heap numbers etc.
1714 inline void set_map_no_write_barrier(Map* value);
1716 // Get the map using acquire load.
1717 inline Map* synchronized_map();
1718 inline MapWord synchronized_map_word() const;
1720 // Set the map using release store
1721 inline void synchronized_set_map(Map* value);
1722 inline void synchronized_set_map_no_write_barrier(Map* value);
1723 inline void synchronized_set_map_word(MapWord map_word);
1725 // During garbage collection, the map word of a heap object does not
1726 // necessarily contain a map pointer.
1727 inline MapWord map_word() const;
1728 inline void set_map_word(MapWord map_word);
1730 // The Heap the object was allocated in. Used also to access Isolate.
1731 inline Heap* GetHeap() const;
1733 // Convenience method to get current isolate.
1734 inline Isolate* GetIsolate() const;
1736 // Converts an address to a HeapObject pointer.
1737 static inline HeapObject* FromAddress(Address address);
1739 // Returns the address of this HeapObject.
1740 inline Address address();
1742 // Iterates over pointers contained in the object (including the Map)
1743 void Iterate(ObjectVisitor* v);
1745 // Iterates over all pointers contained in the object except the
1746 // first map pointer. The object type is given in the first
1747 // parameter. This function does not access the map pointer in the
1748 // object, and so is safe to call while the map pointer is modified.
1749 void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1751 // Returns the heap object's size in bytes
1754 // Returns true if this heap object may contain pointers to objects in new
1756 inline bool MayContainNewSpacePointers();
1758 // Given a heap object's map pointer, returns the heap size in bytes
1759 // Useful when the map pointer field is used for other purposes.
1761 inline int SizeFromMap(Map* map);
1763 // Returns the field at offset in obj, as a read/write Object* reference.
1764 // Does no checking, and is safe to use during GC, while maps are invalid.
1765 // Does not invoke write barrier, so should only be assigned to
1766 // during marking GC.
1767 static inline Object** RawField(HeapObject* obj, int offset);
1769 // Adds the |code| object related to |name| to the code cache of this map. If
1770 // this map is a dictionary map that is shared, the map copied and installed
1772 static void UpdateMapCodeCache(Handle<HeapObject> object,
1776 DECLARE_CAST(HeapObject)
1778 // Return the write barrier mode for this. Callers of this function
1779 // must be able to present a reference to an DisallowHeapAllocation
1780 // object as a sign that they are not going to use this function
1781 // from code that allocates and thus invalidates the returned write
1783 inline WriteBarrierMode GetWriteBarrierMode(
1784 const DisallowHeapAllocation& promise);
1786 // Dispatched behavior.
1787 void HeapObjectShortPrint(OStream& os); // NOLINT
1789 void PrintHeader(OStream& os, const char* id); // NOLINT
1791 DECLARE_PRINTER(HeapObject)
1792 DECLARE_VERIFIER(HeapObject)
1794 inline void VerifyObjectField(int offset);
1795 inline void VerifySmiField(int offset);
1797 // Verify a pointer is a valid HeapObject pointer that points to object
1798 // areas in the heap.
1799 static void VerifyHeapPointer(Object* p);
1802 // Layout description.
1803 // First field in a heap object is map.
1804 static const int kMapOffset = Object::kHeaderSize;
1805 static const int kHeaderSize = kMapOffset + kPointerSize;
1807 STATIC_ASSERT(kMapOffset == Internals::kHeapObjectMapOffset);
1810 // helpers for calling an ObjectVisitor to iterate over pointers in the
1811 // half-open range [start, end) specified as integer offsets
1812 inline void IteratePointers(ObjectVisitor* v, int start, int end);
1813 // as above, for the single element at "offset"
1814 inline void IteratePointer(ObjectVisitor* v, int offset);
1815 // as above, for the next code link of a code object.
1816 inline void IterateNextCodeLink(ObjectVisitor* v, int offset);
1819 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1823 // This class describes a body of an object of a fixed size
1824 // in which all pointer fields are located in the [start_offset, end_offset)
1826 template<int start_offset, int end_offset, int size>
1827 class FixedBodyDescriptor {
1829 static const int kStartOffset = start_offset;
1830 static const int kEndOffset = end_offset;
1831 static const int kSize = size;
1833 static inline void IterateBody(HeapObject* obj, ObjectVisitor* v);
1835 template<typename StaticVisitor>
1836 static inline void IterateBody(HeapObject* obj) {
1837 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1838 HeapObject::RawField(obj, end_offset));
1843 // This class describes a body of an object of a variable size
1844 // in which all pointer fields are located in the [start_offset, object_size)
1846 template<int start_offset>
1847 class FlexibleBodyDescriptor {
1849 static const int kStartOffset = start_offset;
1851 static inline void IterateBody(HeapObject* obj,
1855 template<typename StaticVisitor>
1856 static inline void IterateBody(HeapObject* obj, int object_size) {
1857 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1858 HeapObject::RawField(obj, object_size));
1863 // The HeapNumber class describes heap allocated numbers that cannot be
1864 // represented in a Smi (small integer)
1865 class HeapNumber: public HeapObject {
1867 // [value]: number value.
1868 inline double value() const;
1869 inline void set_value(double value);
1871 DECLARE_CAST(HeapNumber)
1873 // Dispatched behavior.
1874 bool HeapNumberBooleanValue();
1876 void HeapNumberPrint(OStream& os); // NOLINT
1877 DECLARE_VERIFIER(HeapNumber)
1879 inline int get_exponent();
1880 inline int get_sign();
1882 // Layout description.
1883 static const int kValueOffset = HeapObject::kHeaderSize;
1884 // IEEE doubles are two 32 bit words. The first is just mantissa, the second
1885 // is a mixture of sign, exponent and mantissa. The offsets of two 32 bit
1886 // words within double numbers are endian dependent and they are set
1888 #if defined(V8_TARGET_LITTLE_ENDIAN)
1889 static const int kMantissaOffset = kValueOffset;
1890 static const int kExponentOffset = kValueOffset + 4;
1891 #elif defined(V8_TARGET_BIG_ENDIAN)
1892 static const int kMantissaOffset = kValueOffset + 4;
1893 static const int kExponentOffset = kValueOffset;
1895 #error Unknown byte ordering
1898 static const int kSize = kValueOffset + kDoubleSize;
1899 static const uint32_t kSignMask = 0x80000000u;
1900 static const uint32_t kExponentMask = 0x7ff00000u;
1901 static const uint32_t kMantissaMask = 0xfffffu;
1902 static const int kMantissaBits = 52;
1903 static const int kExponentBits = 11;
1904 static const int kExponentBias = 1023;
1905 static const int kExponentShift = 20;
1906 static const int kInfinityOrNanExponent =
1907 (kExponentMask >> kExponentShift) - kExponentBias;
1908 static const int kMantissaBitsInTopWord = 20;
1909 static const int kNonMantissaBitsInTopWord = 12;
1912 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
1916 enum EnsureElementsMode {
1917 DONT_ALLOW_DOUBLE_ELEMENTS,
1918 ALLOW_COPIED_DOUBLE_ELEMENTS,
1919 ALLOW_CONVERTED_DOUBLE_ELEMENTS
1923 // Indicates whether a property should be set or (re)defined. Setting of a
1924 // property causes attributes to remain unchanged, writability to be checked
1925 // and callbacks to be called. Defining of a property causes attributes to
1926 // be updated and callbacks to be overridden.
1927 enum SetPropertyMode {
1933 // Indicator for one component of an AccessorPair.
1934 enum AccessorComponent {
1940 // JSReceiver includes types on which properties can be defined, i.e.,
1941 // JSObject and JSProxy.
1942 class JSReceiver: public HeapObject {
1950 // Internal properties (e.g. the hidden properties dictionary) might
1951 // be added even though the receiver is non-extensible.
1952 enum ExtensibilityCheck {
1953 PERFORM_EXTENSIBILITY_CHECK,
1954 OMIT_EXTENSIBILITY_CHECK
1957 DECLARE_CAST(JSReceiver)
1959 MUST_USE_RESULT static MaybeHandle<Object> SetElement(
1960 Handle<JSReceiver> object,
1962 Handle<Object> value,
1963 PropertyAttributes attributes,
1964 StrictMode strict_mode);
1966 // Implementation of [[HasProperty]], ECMA-262 5th edition, section 8.12.6.
1967 MUST_USE_RESULT static inline Maybe<bool> HasProperty(
1968 Handle<JSReceiver> object, Handle<Name> name);
1969 MUST_USE_RESULT static inline Maybe<bool> HasOwnProperty(Handle<JSReceiver>,
1971 MUST_USE_RESULT static inline Maybe<bool> HasElement(
1972 Handle<JSReceiver> object, uint32_t index);
1973 MUST_USE_RESULT static inline Maybe<bool> HasOwnElement(
1974 Handle<JSReceiver> object, uint32_t index);
1976 // Implementation of [[Delete]], ECMA-262 5th edition, section 8.12.7.
1977 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1978 Handle<JSReceiver> object,
1980 DeleteMode mode = NORMAL_DELETION);
1981 MUST_USE_RESULT static MaybeHandle<Object> DeleteElement(
1982 Handle<JSReceiver> object,
1984 DeleteMode mode = NORMAL_DELETION);
1986 // Tests for the fast common case for property enumeration.
1987 bool IsSimpleEnum();
1989 // Returns the class name ([[Class]] property in the specification).
1990 String* class_name();
1992 // Returns the constructor name (the name (possibly, inferred name) of the
1993 // function that was used to instantiate the object).
1994 String* constructor_name();
1996 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetPropertyAttributes(
1997 Handle<JSReceiver> object, Handle<Name> name);
1998 MUST_USE_RESULT static Maybe<PropertyAttributes> GetPropertyAttributes(
1999 LookupIterator* it);
2000 MUST_USE_RESULT static Maybe<PropertyAttributes> GetOwnPropertyAttributes(
2001 Handle<JSReceiver> object, Handle<Name> name);
2003 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetElementAttribute(
2004 Handle<JSReceiver> object, uint32_t index);
2005 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
2006 GetOwnElementAttribute(Handle<JSReceiver> object, uint32_t index);
2008 // Return the constructor function (may be Heap::null_value()).
2009 inline Object* GetConstructor();
2011 // Retrieves a permanent object identity hash code. The undefined value might
2012 // be returned in case no hash was created yet.
2013 inline Object* GetIdentityHash();
2015 // Retrieves a permanent object identity hash code. May create and store a
2016 // hash code if needed and none exists.
2017 inline static Handle<Smi> GetOrCreateIdentityHash(
2018 Handle<JSReceiver> object);
2020 // Lookup a property. If found, the result is valid and has
2021 // detailed information.
2022 void LookupOwn(Handle<Name> name, LookupResult* result,
2023 bool search_hidden_prototypes = false);
2024 void Lookup(Handle<Name> name, LookupResult* result);
2026 enum KeyCollectionType { OWN_ONLY, INCLUDE_PROTOS };
2028 // Computes the enumerable keys for a JSObject. Used for implementing
2029 // "for (n in object) { }".
2030 MUST_USE_RESULT static MaybeHandle<FixedArray> GetKeys(
2031 Handle<JSReceiver> object,
2032 KeyCollectionType type);
2035 DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
2038 // Forward declaration for JSObject::GetOrCreateHiddenPropertiesHashTable.
2039 class ObjectHashTable;
2041 // Forward declaration for JSObject::Copy.
2042 class AllocationSite;
2045 // The JSObject describes real heap allocated JavaScript objects with
2047 // Note that the map of JSObject changes during execution to enable inline
2049 class JSObject: public JSReceiver {
2051 // [properties]: Backing storage for properties.
2052 // properties is a FixedArray in the fast case and a Dictionary in the
2054 DECL_ACCESSORS(properties, FixedArray) // Get and set fast properties.
2055 inline void initialize_properties();
2056 inline bool HasFastProperties();
2057 inline NameDictionary* property_dictionary(); // Gets slow properties.
2059 // [elements]: The elements (properties with names that are integers).
2061 // Elements can be in two general modes: fast and slow. Each mode
2062 // corrensponds to a set of object representations of elements that
2063 // have something in common.
2065 // In the fast mode elements is a FixedArray and so each element can
2066 // be quickly accessed. This fact is used in the generated code. The
2067 // elements array can have one of three maps in this mode:
2068 // fixed_array_map, sloppy_arguments_elements_map or
2069 // fixed_cow_array_map (for copy-on-write arrays). In the latter case
2070 // the elements array may be shared by a few objects and so before
2071 // writing to any element the array must be copied. Use
2072 // EnsureWritableFastElements in this case.
2074 // In the slow mode the elements is either a NumberDictionary, an
2075 // ExternalArray, or a FixedArray parameter map for a (sloppy)
2076 // arguments object.
2077 DECL_ACCESSORS(elements, FixedArrayBase)
2078 inline void initialize_elements();
2079 static void ResetElements(Handle<JSObject> object);
2080 static inline void SetMapAndElements(Handle<JSObject> object,
2082 Handle<FixedArrayBase> elements);
2083 inline ElementsKind GetElementsKind();
2084 inline ElementsAccessor* GetElementsAccessor();
2085 // Returns true if an object has elements of FAST_SMI_ELEMENTS ElementsKind.
2086 inline bool HasFastSmiElements();
2087 // Returns true if an object has elements of FAST_ELEMENTS ElementsKind.
2088 inline bool HasFastObjectElements();
2089 // Returns true if an object has elements of FAST_ELEMENTS or
2090 // FAST_SMI_ONLY_ELEMENTS.
2091 inline bool HasFastSmiOrObjectElements();
2092 // Returns true if an object has any of the fast elements kinds.
2093 inline bool HasFastElements();
2094 // Returns true if an object has elements of FAST_DOUBLE_ELEMENTS
2096 inline bool HasFastDoubleElements();
2097 // Returns true if an object has elements of FAST_HOLEY_*_ELEMENTS
2099 inline bool HasFastHoleyElements();
2100 inline bool HasSloppyArgumentsElements();
2101 inline bool HasDictionaryElements();
2103 inline bool HasExternalUint8ClampedElements();
2104 inline bool HasExternalArrayElements();
2105 inline bool HasExternalInt8Elements();
2106 inline bool HasExternalUint8Elements();
2107 inline bool HasExternalInt16Elements();
2108 inline bool HasExternalUint16Elements();
2109 inline bool HasExternalInt32Elements();
2110 inline bool HasExternalUint32Elements();
2111 inline bool HasExternalFloat32Elements();
2112 inline bool HasExternalFloat64Elements();
2114 inline bool HasFixedTypedArrayElements();
2116 inline bool HasFixedUint8ClampedElements();
2117 inline bool HasFixedArrayElements();
2118 inline bool HasFixedInt8Elements();
2119 inline bool HasFixedUint8Elements();
2120 inline bool HasFixedInt16Elements();
2121 inline bool HasFixedUint16Elements();
2122 inline bool HasFixedInt32Elements();
2123 inline bool HasFixedUint32Elements();
2124 inline bool HasFixedFloat32Elements();
2125 inline bool HasFixedFloat64Elements();
2127 bool HasFastArgumentsElements();
2128 bool HasDictionaryArgumentsElements();
2129 inline SeededNumberDictionary* element_dictionary(); // Gets slow elements.
2131 // Requires: HasFastElements().
2132 static Handle<FixedArray> EnsureWritableFastElements(
2133 Handle<JSObject> object);
2135 // Collects elements starting at index 0.
2136 // Undefined values are placed after non-undefined values.
2137 // Returns the number of non-undefined values.
2138 static Handle<Object> PrepareElementsForSort(Handle<JSObject> object,
2140 // As PrepareElementsForSort, but only on objects where elements is
2141 // a dictionary, and it will stay a dictionary. Collates undefined and
2142 // unexisting elements below limit from position zero of the elements.
2143 static Handle<Object> PrepareSlowElementsForSort(Handle<JSObject> object,
2146 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithInterceptor(
2147 LookupIterator* it, Handle<Object> value);
2149 // SetLocalPropertyIgnoreAttributes converts callbacks to fields. We need to
2150 // grant an exemption to ExecutableAccessor callbacks in some cases.
2151 enum ExecutableAccessorInfoHandling {
2156 MUST_USE_RESULT static MaybeHandle<Object> SetOwnPropertyIgnoreAttributes(
2157 Handle<JSObject> object,
2159 Handle<Object> value,
2160 PropertyAttributes attributes,
2161 ExtensibilityCheck extensibility_check = PERFORM_EXTENSIBILITY_CHECK,
2162 StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED,
2163 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
2165 static void AddProperty(Handle<JSObject> object, Handle<Name> key,
2166 Handle<Object> value, PropertyAttributes attributes);
2168 // Extend the receiver with a single fast property appeared first in the
2169 // passed map. This also extends the property backing store if necessary.
2170 static void AllocateStorageForMap(Handle<JSObject> object, Handle<Map> map);
2172 // Migrates the given object to a map whose field representations are the
2173 // lowest upper bound of all known representations for that field.
2174 static void MigrateInstance(Handle<JSObject> instance);
2176 // Migrates the given object only if the target map is already available,
2177 // or returns false if such a map is not yet available.
2178 static bool TryMigrateInstance(Handle<JSObject> instance);
2180 // Retrieve a value in a normalized object given a lookup result.
2181 // Handles the special representation of JS global objects.
2182 Object* GetNormalizedProperty(const LookupResult* result);
2183 static Handle<Object> GetNormalizedProperty(Handle<JSObject> object,
2184 const LookupResult* result);
2186 // Sets the property value in a normalized object given a lookup result.
2187 // Handles the special representation of JS global objects.
2188 static void SetNormalizedProperty(Handle<JSObject> object,
2189 const LookupResult* result,
2190 Handle<Object> value);
2192 // Sets the property value in a normalized object given (key, value, details).
2193 // Handles the special representation of JS global objects.
2194 static void SetNormalizedProperty(Handle<JSObject> object,
2196 Handle<Object> value,
2197 PropertyDetails details);
2199 static void OptimizeAsPrototype(Handle<JSObject> object,
2200 PrototypeOptimizationMode mode);
2201 static void ReoptimizeIfPrototype(Handle<JSObject> object);
2203 // Retrieve interceptors.
2204 InterceptorInfo* GetNamedInterceptor();
2205 InterceptorInfo* GetIndexedInterceptor();
2207 // Used from JSReceiver.
2208 MUST_USE_RESULT static Maybe<PropertyAttributes>
2209 GetPropertyAttributesWithInterceptor(Handle<JSObject> holder,
2210 Handle<Object> receiver,
2212 MUST_USE_RESULT static Maybe<PropertyAttributes>
2213 GetPropertyAttributesWithFailedAccessCheck(LookupIterator* it);
2214 MUST_USE_RESULT static Maybe<PropertyAttributes>
2215 GetElementAttributeWithReceiver(Handle<JSObject> object,
2216 Handle<JSReceiver> receiver,
2217 uint32_t index, bool check_prototype);
2219 // Retrieves an AccessorPair property from the given object. Might return
2220 // undefined if the property doesn't exist or is of a different kind.
2221 MUST_USE_RESULT static MaybeHandle<Object> GetAccessor(
2222 Handle<JSObject> object,
2224 AccessorComponent component);
2226 // Defines an AccessorPair property on the given object.
2227 // TODO(mstarzinger): Rename to SetAccessor().
2228 static MaybeHandle<Object> DefineAccessor(Handle<JSObject> object,
2230 Handle<Object> getter,
2231 Handle<Object> setter,
2232 PropertyAttributes attributes);
2234 // Defines an AccessorInfo property on the given object.
2235 MUST_USE_RESULT static MaybeHandle<Object> SetAccessor(
2236 Handle<JSObject> object,
2237 Handle<AccessorInfo> info);
2239 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithInterceptor(
2240 Handle<JSObject> object,
2241 Handle<Object> receiver,
2244 // Returns true if this is an instance of an api function and has
2245 // been modified since it was created. May give false positives.
2248 // Accessors for hidden properties object.
2250 // Hidden properties are not own properties of the object itself.
2251 // Instead they are stored in an auxiliary structure kept as an own
2252 // property with a special name Heap::hidden_string(). But if the
2253 // receiver is a JSGlobalProxy then the auxiliary object is a property
2254 // of its prototype, and if it's a detached proxy, then you can't have
2255 // hidden properties.
2257 // Sets a hidden property on this object. Returns this object if successful,
2258 // undefined if called on a detached proxy.
2259 static Handle<Object> SetHiddenProperty(Handle<JSObject> object,
2261 Handle<Object> value);
2262 // Gets the value of a hidden property with the given key. Returns the hole
2263 // if the property doesn't exist (or if called on a detached proxy),
2264 // otherwise returns the value set for the key.
2265 Object* GetHiddenProperty(Handle<Name> key);
2266 // Deletes a hidden property. Deleting a non-existing property is
2267 // considered successful.
2268 static void DeleteHiddenProperty(Handle<JSObject> object,
2270 // Returns true if the object has a property with the hidden string as name.
2271 static bool HasHiddenProperties(Handle<JSObject> object);
2273 static void SetIdentityHash(Handle<JSObject> object, Handle<Smi> hash);
2275 static inline void ValidateElements(Handle<JSObject> object);
2277 // Makes sure that this object can contain HeapObject as elements.
2278 static inline void EnsureCanContainHeapObjectElements(Handle<JSObject> obj);
2280 // Makes sure that this object can contain the specified elements.
2281 static inline void EnsureCanContainElements(
2282 Handle<JSObject> object,
2285 EnsureElementsMode mode);
2286 static inline void EnsureCanContainElements(
2287 Handle<JSObject> object,
2288 Handle<FixedArrayBase> elements,
2290 EnsureElementsMode mode);
2291 static void EnsureCanContainElements(
2292 Handle<JSObject> object,
2293 Arguments* arguments,
2296 EnsureElementsMode mode);
2298 // Would we convert a fast elements array to dictionary mode given
2299 // an access at key?
2300 bool WouldConvertToSlowElements(Handle<Object> key);
2301 // Do we want to keep the elements in fast case when increasing the
2303 bool ShouldConvertToSlowElements(int new_capacity);
2304 // Returns true if the backing storage for the slow-case elements of
2305 // this object takes up nearly as much space as a fast-case backing
2306 // storage would. In that case the JSObject should have fast
2308 bool ShouldConvertToFastElements();
2309 // Returns true if the elements of JSObject contains only values that can be
2310 // represented in a FixedDoubleArray and has at least one value that can only
2311 // be represented as a double and not a Smi.
2312 bool ShouldConvertToFastDoubleElements(bool* has_smi_only_elements);
2314 // Computes the new capacity when expanding the elements of a JSObject.
2315 static int NewElementsCapacity(int old_capacity) {
2316 // (old_capacity + 50%) + 16
2317 return old_capacity + (old_capacity >> 1) + 16;
2320 // These methods do not perform access checks!
2321 MUST_USE_RESULT static MaybeHandle<AccessorPair> GetOwnElementAccessorPair(
2322 Handle<JSObject> object,
2325 MUST_USE_RESULT static MaybeHandle<Object> SetFastElement(
2326 Handle<JSObject> object,
2328 Handle<Object> value,
2329 StrictMode strict_mode,
2330 bool check_prototype);
2332 MUST_USE_RESULT static MaybeHandle<Object> SetOwnElement(
2333 Handle<JSObject> object,
2335 Handle<Object> value,
2336 StrictMode strict_mode);
2338 // Empty handle is returned if the element cannot be set to the given value.
2339 MUST_USE_RESULT static MaybeHandle<Object> SetElement(
2340 Handle<JSObject> object,
2342 Handle<Object> value,
2343 PropertyAttributes attributes,
2344 StrictMode strict_mode,
2345 bool check_prototype = true,
2346 SetPropertyMode set_mode = SET_PROPERTY);
2348 // Returns the index'th element.
2349 // The undefined object if index is out of bounds.
2350 MUST_USE_RESULT static MaybeHandle<Object> GetElementWithInterceptor(
2351 Handle<JSObject> object,
2352 Handle<Object> receiver,
2355 enum SetFastElementsCapacitySmiMode {
2358 kDontAllowSmiElements
2361 // Replace the elements' backing store with fast elements of the given
2362 // capacity. Update the length for JSArrays. Returns the new backing
2364 static Handle<FixedArray> SetFastElementsCapacityAndLength(
2365 Handle<JSObject> object,
2368 SetFastElementsCapacitySmiMode smi_mode);
2369 static void SetFastDoubleElementsCapacityAndLength(
2370 Handle<JSObject> object,
2374 // Lookup interceptors are used for handling properties controlled by host
2376 inline bool HasNamedInterceptor();
2377 inline bool HasIndexedInterceptor();
2379 // Computes the enumerable keys from interceptors. Used for debug mirrors and
2380 // by JSReceiver::GetKeys.
2381 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForNamedInterceptor(
2382 Handle<JSObject> object,
2383 Handle<JSReceiver> receiver);
2384 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForIndexedInterceptor(
2385 Handle<JSObject> object,
2386 Handle<JSReceiver> receiver);
2388 // Support functions for v8 api (needed for correct interceptor behavior).
2389 MUST_USE_RESULT static Maybe<bool> HasRealNamedProperty(
2390 Handle<JSObject> object, Handle<Name> key);
2391 MUST_USE_RESULT static Maybe<bool> HasRealElementProperty(
2392 Handle<JSObject> object, uint32_t index);
2393 MUST_USE_RESULT static Maybe<bool> HasRealNamedCallbackProperty(
2394 Handle<JSObject> object, Handle<Name> key);
2396 // Get the header size for a JSObject. Used to compute the index of
2397 // internal fields as well as the number of internal fields.
2398 inline int GetHeaderSize();
2400 inline int GetInternalFieldCount();
2401 inline int GetInternalFieldOffset(int index);
2402 inline Object* GetInternalField(int index);
2403 inline void SetInternalField(int index, Object* value);
2404 inline void SetInternalField(int index, Smi* value);
2406 // The following lookup functions skip interceptors.
2407 void LookupOwnRealNamedProperty(Handle<Name> name, LookupResult* result);
2408 void LookupRealNamedProperty(Handle<Name> name, LookupResult* result);
2409 void LookupRealNamedPropertyInPrototypes(Handle<Name> name,
2410 LookupResult* result);
2412 // Returns the number of properties on this object filtering out properties
2413 // with the specified attributes (ignoring interceptors).
2414 int NumberOfOwnProperties(PropertyAttributes filter = NONE);
2415 // Fill in details for properties into storage starting at the specified
2417 void GetOwnPropertyNames(
2418 FixedArray* storage, int index, PropertyAttributes filter = NONE);
2420 // Returns the number of properties on this object filtering out properties
2421 // with the specified attributes (ignoring interceptors).
2422 int NumberOfOwnElements(PropertyAttributes filter);
2423 // Returns the number of enumerable elements (ignoring interceptors).
2424 int NumberOfEnumElements();
2425 // Returns the number of elements on this object filtering out elements
2426 // with the specified attributes (ignoring interceptors).
2427 int GetOwnElementKeys(FixedArray* storage, PropertyAttributes filter);
2428 // Count and fill in the enumerable elements into storage.
2429 // (storage->length() == NumberOfEnumElements()).
2430 // If storage is NULL, will count the elements without adding
2431 // them to any storage.
2432 // Returns the number of enumerable elements.
2433 int GetEnumElementKeys(FixedArray* storage);
2435 // Returns a new map with all transitions dropped from the object's current
2436 // map and the ElementsKind set.
2437 static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
2438 ElementsKind to_kind);
2439 static void TransitionElementsKind(Handle<JSObject> object,
2440 ElementsKind to_kind);
2442 static void MigrateToMap(Handle<JSObject> object, Handle<Map> new_map);
2444 // Convert the object to use the canonical dictionary
2445 // representation. If the object is expected to have additional properties
2446 // added this number can be indicated to have the backing store allocated to
2447 // an initial capacity for holding these properties.
2448 static void NormalizeProperties(Handle<JSObject> object,
2449 PropertyNormalizationMode mode,
2450 int expected_additional_properties);
2452 // Convert and update the elements backing store to be a
2453 // SeededNumberDictionary dictionary. Returns the backing after conversion.
2454 static Handle<SeededNumberDictionary> NormalizeElements(
2455 Handle<JSObject> object);
2457 // Transform slow named properties to fast variants.
2458 static void MigrateSlowToFast(Handle<JSObject> object,
2459 int unused_property_fields);
2461 // Access fast-case object properties at index.
2462 static Handle<Object> FastPropertyAt(Handle<JSObject> object,
2463 Representation representation,
2465 inline Object* RawFastPropertyAt(FieldIndex index);
2466 inline void FastPropertyAtPut(FieldIndex index, Object* value);
2467 void WriteToField(int descriptor, Object* value);
2469 // Access to in object properties.
2470 inline int GetInObjectPropertyOffset(int index);
2471 inline Object* InObjectPropertyAt(int index);
2472 inline Object* InObjectPropertyAtPut(int index,
2474 WriteBarrierMode mode
2475 = UPDATE_WRITE_BARRIER);
2477 // Set the object's prototype (only JSReceiver and null are allowed values).
2478 MUST_USE_RESULT static MaybeHandle<Object> SetPrototype(
2479 Handle<JSObject> object, Handle<Object> value, bool from_javascript);
2481 // Initializes the body after properties slot, properties slot is
2482 // initialized by set_properties. Fill the pre-allocated fields with
2483 // pre_allocated_value and the rest with filler_value.
2484 // Note: this call does not update write barrier, the caller is responsible
2485 // to ensure that |filler_value| can be collected without WB here.
2486 inline void InitializeBody(Map* map,
2487 Object* pre_allocated_value,
2488 Object* filler_value);
2490 // Check whether this object references another object
2491 bool ReferencesObject(Object* obj);
2493 // Disalow further properties to be added to the object.
2494 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensions(
2495 Handle<JSObject> object);
2497 // ES5 Object.freeze
2498 MUST_USE_RESULT static MaybeHandle<Object> Freeze(Handle<JSObject> object);
2500 // Called the first time an object is observed with ES7 Object.observe.
2501 static void SetObserved(Handle<JSObject> object);
2504 enum DeepCopyHints { kNoHints = 0, kObjectIsShallow = 1 };
2506 static Handle<JSObject> Copy(Handle<JSObject> object);
2507 MUST_USE_RESULT static MaybeHandle<JSObject> DeepCopy(
2508 Handle<JSObject> object,
2509 AllocationSiteUsageContext* site_context,
2510 DeepCopyHints hints = kNoHints);
2511 MUST_USE_RESULT static MaybeHandle<JSObject> DeepWalk(
2512 Handle<JSObject> object,
2513 AllocationSiteCreationContext* site_context);
2515 static Handle<Object> GetDataProperty(Handle<JSObject> object,
2518 DECLARE_CAST(JSObject)
2520 // Dispatched behavior.
2521 void JSObjectShortPrint(StringStream* accumulator);
2522 DECLARE_PRINTER(JSObject)
2523 DECLARE_VERIFIER(JSObject)
2525 void PrintProperties(OStream& os); // NOLINT
2526 void PrintElements(OStream& os); // NOLINT
2527 void PrintTransitions(OStream& os); // NOLINT
2530 static void PrintElementsTransition(
2531 FILE* file, Handle<JSObject> object,
2532 ElementsKind from_kind, Handle<FixedArrayBase> from_elements,
2533 ElementsKind to_kind, Handle<FixedArrayBase> to_elements);
2535 void PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map);
2538 // Structure for collecting spill information about JSObjects.
2539 class SpillInformation {
2543 int number_of_objects_;
2544 int number_of_objects_with_fast_properties_;
2545 int number_of_objects_with_fast_elements_;
2546 int number_of_fast_used_fields_;
2547 int number_of_fast_unused_fields_;
2548 int number_of_slow_used_properties_;
2549 int number_of_slow_unused_properties_;
2550 int number_of_fast_used_elements_;
2551 int number_of_fast_unused_elements_;
2552 int number_of_slow_used_elements_;
2553 int number_of_slow_unused_elements_;
2556 void IncrementSpillStatistics(SpillInformation* info);
2560 // If a GC was caused while constructing this object, the elements pointer
2561 // may point to a one pointer filler map. The object won't be rooted, but
2562 // our heap verification code could stumble across it.
2563 bool ElementsAreSafeToExamine();
2566 Object* SlowReverseLookup(Object* value);
2568 // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2569 // Also maximal value of JSArray's length property.
2570 static const uint32_t kMaxElementCount = 0xffffffffu;
2572 // Constants for heuristics controlling conversion of fast elements
2573 // to slow elements.
2575 // Maximal gap that can be introduced by adding an element beyond
2576 // the current elements length.
2577 static const uint32_t kMaxGap = 1024;
2579 // Maximal length of fast elements array that won't be checked for
2580 // being dense enough on expansion.
2581 static const int kMaxUncheckedFastElementsLength = 5000;
2583 // Same as above but for old arrays. This limit is more strict. We
2584 // don't want to be wasteful with long lived objects.
2585 static const int kMaxUncheckedOldFastElementsLength = 500;
2587 // Note that Page::kMaxRegularHeapObjectSize puts a limit on
2588 // permissible values (see the DCHECK in heap.cc).
2589 static const int kInitialMaxFastElementArray = 100000;
2591 // This constant applies only to the initial map of "$Object" aka
2592 // "global.Object" and not to arbitrary other JSObject maps.
2593 static const int kInitialGlobalObjectUnusedPropertiesCount = 4;
2595 static const int kMaxInstanceSize = 255 * kPointerSize;
2596 // When extending the backing storage for property values, we increase
2597 // its size by more than the 1 entry necessary, so sequentially adding fields
2598 // to the same object requires fewer allocations and copies.
2599 static const int kFieldsAdded = 3;
2601 // Layout description.
2602 static const int kPropertiesOffset = HeapObject::kHeaderSize;
2603 static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2604 static const int kHeaderSize = kElementsOffset + kPointerSize;
2606 STATIC_ASSERT(kHeaderSize == Internals::kJSObjectHeaderSize);
2608 class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2610 static inline int SizeOf(Map* map, HeapObject* object);
2613 Context* GetCreationContext();
2615 // Enqueue change record for Object.observe. May cause GC.
2616 static void EnqueueChangeRecord(Handle<JSObject> object,
2619 Handle<Object> old_value);
2621 static void MigrateToNewProperty(Handle<JSObject> object,
2622 Handle<Map> transition,
2623 Handle<Object> value);
2626 friend class DictionaryElementsAccessor;
2627 friend class JSReceiver;
2628 friend class Object;
2630 static void MigrateFastToFast(Handle<JSObject> object, Handle<Map> new_map);
2631 static void MigrateFastToSlow(Handle<JSObject> object,
2632 Handle<Map> new_map,
2633 int expected_additional_properties);
2635 static void SetPropertyToField(LookupResult* lookup, Handle<Object> value);
2637 static void ConvertAndSetOwnProperty(LookupResult* lookup,
2639 Handle<Object> value,
2640 PropertyAttributes attributes);
2642 static void SetPropertyToFieldWithAttributes(LookupResult* lookup,
2644 Handle<Object> value,
2645 PropertyAttributes attributes);
2646 static void GeneralizeFieldRepresentation(Handle<JSObject> object,
2648 Representation new_representation,
2649 Handle<HeapType> new_field_type);
2651 static void UpdateAllocationSite(Handle<JSObject> object,
2652 ElementsKind to_kind);
2654 // Used from Object::GetProperty().
2655 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithFailedAccessCheck(
2656 LookupIterator* it);
2658 MUST_USE_RESULT static MaybeHandle<Object> GetElementWithCallback(
2659 Handle<JSObject> object,
2660 Handle<Object> receiver,
2661 Handle<Object> structure,
2663 Handle<Object> holder);
2665 MUST_USE_RESULT static Maybe<PropertyAttributes>
2666 GetElementAttributeWithInterceptor(Handle<JSObject> object,
2667 Handle<JSReceiver> receiver,
2668 uint32_t index, bool continue_search);
2669 MUST_USE_RESULT static Maybe<PropertyAttributes>
2670 GetElementAttributeWithoutInterceptor(Handle<JSObject> object,
2671 Handle<JSReceiver> receiver,
2673 bool continue_search);
2674 MUST_USE_RESULT static MaybeHandle<Object> SetElementWithCallback(
2675 Handle<JSObject> object,
2676 Handle<Object> structure,
2678 Handle<Object> value,
2679 Handle<JSObject> holder,
2680 StrictMode strict_mode);
2681 MUST_USE_RESULT static MaybeHandle<Object> SetElementWithInterceptor(
2682 Handle<JSObject> object,
2684 Handle<Object> value,
2685 PropertyAttributes attributes,
2686 StrictMode strict_mode,
2687 bool check_prototype,
2688 SetPropertyMode set_mode);
2689 MUST_USE_RESULT static MaybeHandle<Object> SetElementWithoutInterceptor(
2690 Handle<JSObject> object,
2692 Handle<Object> value,
2693 PropertyAttributes attributes,
2694 StrictMode strict_mode,
2695 bool check_prototype,
2696 SetPropertyMode set_mode);
2698 static MaybeHandle<Object> SetElementWithCallbackSetterInPrototypes(
2699 Handle<JSObject> object,
2701 Handle<Object> value,
2703 StrictMode strict_mode);
2704 MUST_USE_RESULT static MaybeHandle<Object> SetDictionaryElement(
2705 Handle<JSObject> object,
2707 Handle<Object> value,
2708 PropertyAttributes attributes,
2709 StrictMode strict_mode,
2710 bool check_prototype,
2711 SetPropertyMode set_mode = SET_PROPERTY);
2712 MUST_USE_RESULT static MaybeHandle<Object> SetFastDoubleElement(
2713 Handle<JSObject> object,
2715 Handle<Object> value,
2716 StrictMode strict_mode,
2717 bool check_prototype = true);
2719 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyUsingTransition(
2720 Handle<JSObject> object,
2721 LookupResult* lookup,
2723 Handle<Object> value,
2724 PropertyAttributes attributes);
2725 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithFailedAccessCheck(
2726 LookupIterator* it, Handle<Object> value, StrictMode strict_mode);
2728 // Add a property to an object.
2729 MUST_USE_RESULT static MaybeHandle<Object> AddPropertyInternal(
2730 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
2731 PropertyAttributes attributes, StoreFromKeyed store_mode,
2732 ExtensibilityCheck extensibility_check, TransitionFlag flag);
2734 // Add a property to a fast-case object.
2735 static void AddFastProperty(Handle<JSObject> object,
2737 Handle<Object> value,
2738 PropertyAttributes attributes,
2739 StoreFromKeyed store_mode,
2740 TransitionFlag flag);
2742 // Add a property to a slow-case object.
2743 static void AddSlowProperty(Handle<JSObject> object,
2745 Handle<Object> value,
2746 PropertyAttributes attributes);
2748 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
2749 Handle<JSObject> object,
2752 static Handle<Object> DeletePropertyPostInterceptor(Handle<JSObject> object,
2755 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithInterceptor(
2756 Handle<JSObject> object,
2759 // Deletes the named property in a normalized object.
2760 static Handle<Object> DeleteNormalizedProperty(Handle<JSObject> object,
2764 MUST_USE_RESULT static MaybeHandle<Object> DeleteElement(
2765 Handle<JSObject> object,
2768 MUST_USE_RESULT static MaybeHandle<Object> DeleteElementWithInterceptor(
2769 Handle<JSObject> object,
2772 bool ReferencesObjectFromElements(FixedArray* elements,
2776 // Returns true if most of the elements backing storage is used.
2777 bool HasDenseElements();
2779 // Gets the current elements capacity and the number of used elements.
2780 void GetElementsCapacityAndUsage(int* capacity, int* used);
2782 static bool CanSetCallback(Handle<JSObject> object, Handle<Name> name);
2783 static void SetElementCallback(Handle<JSObject> object,
2785 Handle<Object> structure,
2786 PropertyAttributes attributes);
2787 static void SetPropertyCallback(Handle<JSObject> object,
2789 Handle<Object> structure,
2790 PropertyAttributes attributes);
2791 static void DefineElementAccessor(Handle<JSObject> object,
2793 Handle<Object> getter,
2794 Handle<Object> setter,
2795 PropertyAttributes attributes);
2796 static Handle<AccessorPair> CreateAccessorPairFor(Handle<JSObject> object,
2798 static void DefinePropertyAccessor(Handle<JSObject> object,
2800 Handle<Object> getter,
2801 Handle<Object> setter,
2802 PropertyAttributes attributes);
2804 // Try to define a single accessor paying attention to map transitions.
2805 // Returns false if this was not possible and we have to use the slow case.
2806 static bool DefineFastAccessor(Handle<JSObject> object,
2808 AccessorComponent component,
2809 Handle<Object> accessor,
2810 PropertyAttributes attributes);
2813 // Return the hash table backing store or the inline stored identity hash,
2814 // whatever is found.
2815 MUST_USE_RESULT Object* GetHiddenPropertiesHashTable();
2817 // Return the hash table backing store for hidden properties. If there is no
2818 // backing store, allocate one.
2819 static Handle<ObjectHashTable> GetOrCreateHiddenPropertiesHashtable(
2820 Handle<JSObject> object);
2822 // Set the hidden property backing store to either a hash table or
2823 // the inline-stored identity hash.
2824 static Handle<Object> SetHiddenPropertiesHashTable(
2825 Handle<JSObject> object,
2826 Handle<Object> value);
2828 MUST_USE_RESULT Object* GetIdentityHash();
2830 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSObject> object);
2832 DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
2836 // Common superclass for FixedArrays that allow implementations to share
2837 // common accessors and some code paths.
2838 class FixedArrayBase: public HeapObject {
2840 // [length]: length of the array.
2841 inline int length() const;
2842 inline void set_length(int value);
2844 // Get and set the length using acquire loads and release stores.
2845 inline int synchronized_length() const;
2846 inline void synchronized_set_length(int value);
2848 DECLARE_CAST(FixedArrayBase)
2850 // Layout description.
2851 // Length is smi tagged when it is stored.
2852 static const int kLengthOffset = HeapObject::kHeaderSize;
2853 static const int kHeaderSize = kLengthOffset + kPointerSize;
2857 class FixedDoubleArray;
2858 class IncrementalMarking;
2861 // FixedArray describes fixed-sized arrays with element type Object*.
2862 class FixedArray: public FixedArrayBase {
2864 // Setter and getter for elements.
2865 inline Object* get(int index);
2866 static inline Handle<Object> get(Handle<FixedArray> array, int index);
2867 // Setter that uses write barrier.
2868 inline void set(int index, Object* value);
2869 inline bool is_the_hole(int index);
2871 // Setter that doesn't need write barrier.
2872 inline void set(int index, Smi* value);
2873 // Setter with explicit barrier mode.
2874 inline void set(int index, Object* value, WriteBarrierMode mode);
2876 // Setters for frequently used oddballs located in old space.
2877 inline void set_undefined(int index);
2878 inline void set_null(int index);
2879 inline void set_the_hole(int index);
2881 inline Object** GetFirstElementAddress();
2882 inline bool ContainsOnlySmisOrHoles();
2884 // Gives access to raw memory which stores the array's data.
2885 inline Object** data_start();
2887 inline void FillWithHoles(int from, int to);
2889 // Shrink length and insert filler objects.
2890 void Shrink(int length);
2893 static Handle<FixedArray> CopySize(Handle<FixedArray> array,
2895 PretenureFlag pretenure = NOT_TENURED);
2897 // Add the elements of a JSArray to this FixedArray.
2898 MUST_USE_RESULT static MaybeHandle<FixedArray> AddKeysFromArrayLike(
2899 Handle<FixedArray> content,
2900 Handle<JSObject> array);
2902 // Computes the union of keys and return the result.
2903 // Used for implementing "for (n in object) { }"
2904 MUST_USE_RESULT static MaybeHandle<FixedArray> UnionOfKeys(
2905 Handle<FixedArray> first,
2906 Handle<FixedArray> second);
2908 // Copy a sub array from the receiver to dest.
2909 void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
2911 // Garbage collection support.
2912 static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
2914 // Code Generation support.
2915 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2917 // Garbage collection support.
2918 Object** RawFieldOfElementAt(int index) {
2919 return HeapObject::RawField(this, OffsetOfElementAt(index));
2922 DECLARE_CAST(FixedArray)
2924 // Maximal allowed size, in bytes, of a single FixedArray.
2925 // Prevents overflowing size computations, as well as extreme memory
2927 static const int kMaxSize = 128 * MB * kPointerSize;
2928 // Maximally allowed length of a FixedArray.
2929 static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
2931 // Dispatched behavior.
2932 DECLARE_PRINTER(FixedArray)
2933 DECLARE_VERIFIER(FixedArray)
2935 // Checks if two FixedArrays have identical contents.
2936 bool IsEqualTo(FixedArray* other);
2939 // Swap two elements in a pair of arrays. If this array and the
2940 // numbers array are the same object, the elements are only swapped
2942 void SwapPairs(FixedArray* numbers, int i, int j);
2944 // Sort prefix of this array and the numbers array as pairs wrt. the
2945 // numbers. If the numbers array and the this array are the same
2946 // object, the prefix of this array is sorted.
2947 void SortPairs(FixedArray* numbers, uint32_t len);
2949 class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
2951 static inline int SizeOf(Map* map, HeapObject* object) {
2952 return SizeFor(reinterpret_cast<FixedArray*>(object)->length());
2957 // Set operation on FixedArray without using write barriers. Can
2958 // only be used for storing old space objects or smis.
2959 static inline void NoWriteBarrierSet(FixedArray* array,
2963 // Set operation on FixedArray without incremental write barrier. Can
2964 // only be used if the object is guaranteed to be white (whiteness witness
2966 static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
2971 STATIC_ASSERT(kHeaderSize == Internals::kFixedArrayHeaderSize);
2973 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
2977 // FixedDoubleArray describes fixed-sized arrays with element type double.
2978 class FixedDoubleArray: public FixedArrayBase {
2980 // Setter and getter for elements.
2981 inline double get_scalar(int index);
2982 inline int64_t get_representation(int index);
2983 static inline Handle<Object> get(Handle<FixedDoubleArray> array, int index);
2984 inline void set(int index, double value);
2985 inline void set_the_hole(int index);
2987 // Checking for the hole.
2988 inline bool is_the_hole(int index);
2990 // Garbage collection support.
2991 inline static int SizeFor(int length) {
2992 return kHeaderSize + length * kDoubleSize;
2995 // Gives access to raw memory which stores the array's data.
2996 inline double* data_start();
2998 inline void FillWithHoles(int from, int to);
3000 // Code Generation support.
3001 static int OffsetOfElementAt(int index) { return SizeFor(index); }
3003 inline static bool is_the_hole_nan(double value);
3004 inline static double hole_nan_as_double();
3005 inline static double canonical_not_the_hole_nan_as_double();
3007 DECLARE_CAST(FixedDoubleArray)
3009 // Maximal allowed size, in bytes, of a single FixedDoubleArray.
3010 // Prevents overflowing size computations, as well as extreme memory
3012 static const int kMaxSize = 512 * MB;
3013 // Maximally allowed length of a FixedArray.
3014 static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
3016 // Dispatched behavior.
3017 DECLARE_PRINTER(FixedDoubleArray)
3018 DECLARE_VERIFIER(FixedDoubleArray)
3021 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
3025 // ConstantPoolArray describes a fixed-sized array containing constant pool
3028 // A ConstantPoolArray can be structured in two different ways depending upon
3029 // whether it is extended or small. The is_extended_layout() method can be used
3030 // to discover which layout the constant pool has.
3032 // The format of a small constant pool is:
3033 // [kSmallLayout1Offset] : Small section layout bitmap 1
3034 // [kSmallLayout2Offset] : Small section layout bitmap 2
3035 // [first_index(INT64, SMALL_SECTION)] : 64 bit entries
3037 // [first_index(CODE_PTR, SMALL_SECTION)] : code pointer entries
3039 // [first_index(HEAP_PTR, SMALL_SECTION)] : heap pointer entries
3041 // [first_index(INT32, SMALL_SECTION)] : 32 bit entries
3044 // If the constant pool has an extended layout, the extended section constant
3045 // pool also contains an extended section, which has the following format at
3046 // location get_extended_section_header_offset():
3047 // [kExtendedInt64CountOffset] : count of extended 64 bit entries
3048 // [kExtendedCodePtrCountOffset] : count of extended code pointers
3049 // [kExtendedHeapPtrCountOffset] : count of extended heap pointers
3050 // [kExtendedInt32CountOffset] : count of extended 32 bit entries
3051 // [first_index(INT64, EXTENDED_SECTION)] : 64 bit entries
3053 // [first_index(CODE_PTR, EXTENDED_SECTION)]: code pointer entries
3055 // [first_index(HEAP_PTR, EXTENDED_SECTION)]: heap pointer entries
3057 // [first_index(INT32, EXTENDED_SECTION)] : 32 bit entries
3060 class ConstantPoolArray: public HeapObject {
3062 enum WeakObjectState {
3064 WEAK_OBJECTS_IN_OPTIMIZED_CODE,
3073 // Number of types stored by the ConstantPoolArrays.
3079 enum LayoutSection {
3082 NUMBER_OF_LAYOUT_SECTIONS
3085 class NumberOfEntries BASE_EMBEDDED {
3087 inline NumberOfEntries() {
3088 for (int i = 0; i < NUMBER_OF_TYPES; i++) {
3089 element_counts_[i] = 0;
3093 inline NumberOfEntries(int int64_count, int code_ptr_count,
3094 int heap_ptr_count, int int32_count) {
3095 element_counts_[INT64] = int64_count;
3096 element_counts_[CODE_PTR] = code_ptr_count;
3097 element_counts_[HEAP_PTR] = heap_ptr_count;
3098 element_counts_[INT32] = int32_count;
3101 inline NumberOfEntries(ConstantPoolArray* array, LayoutSection section) {
3102 element_counts_[INT64] = array->number_of_entries(INT64, section);
3103 element_counts_[CODE_PTR] = array->number_of_entries(CODE_PTR, section);
3104 element_counts_[HEAP_PTR] = array->number_of_entries(HEAP_PTR, section);
3105 element_counts_[INT32] = array->number_of_entries(INT32, section);
3108 inline void increment(Type type);
3109 inline int equals(const NumberOfEntries& other) const;
3110 inline bool is_empty() const;
3111 inline int count_of(Type type) const;
3112 inline int base_of(Type type) const;
3113 inline int total_count() const;
3114 inline int are_in_range(int min, int max) const;
3117 int element_counts_[NUMBER_OF_TYPES];
3120 class Iterator BASE_EMBEDDED {
3122 inline Iterator(ConstantPoolArray* array, Type type)
3125 final_section_(array->final_section()),
3126 current_section_(SMALL_SECTION),
3127 next_index_(array->first_index(type, SMALL_SECTION)) {
3131 inline Iterator(ConstantPoolArray* array, Type type, LayoutSection section)
3134 final_section_(section),
3135 current_section_(section),
3136 next_index_(array->first_index(type, section)) {
3140 inline int next_index();
3141 inline bool is_finished();
3144 inline void update_section();
3145 ConstantPoolArray* array_;
3147 const LayoutSection final_section_;
3149 LayoutSection current_section_;
3153 // Getters for the first index, the last index and the count of entries of
3154 // a given type for a given layout section.
3155 inline int first_index(Type type, LayoutSection layout_section);
3156 inline int last_index(Type type, LayoutSection layout_section);
3157 inline int number_of_entries(Type type, LayoutSection layout_section);
3159 // Returns the type of the entry at the given index.
3160 inline Type get_type(int index);
3161 inline bool offset_is_type(int offset, Type type);
3163 // Setter and getter for pool elements.
3164 inline Address get_code_ptr_entry(int index);
3165 inline Object* get_heap_ptr_entry(int index);
3166 inline int64_t get_int64_entry(int index);
3167 inline int32_t get_int32_entry(int index);
3168 inline double get_int64_entry_as_double(int index);
3170 inline void set(int index, Address value);
3171 inline void set(int index, Object* value);
3172 inline void set(int index, int64_t value);
3173 inline void set(int index, double value);
3174 inline void set(int index, int32_t value);
3176 // Setters which take a raw offset rather than an index (for code generation).
3177 inline void set_at_offset(int offset, int32_t value);
3178 inline void set_at_offset(int offset, int64_t value);
3179 inline void set_at_offset(int offset, double value);
3180 inline void set_at_offset(int offset, Address value);
3181 inline void set_at_offset(int offset, Object* value);
3183 // Setter and getter for weak objects state
3184 inline void set_weak_object_state(WeakObjectState state);
3185 inline WeakObjectState get_weak_object_state();
3187 // Returns true if the constant pool has an extended layout, false if it has
3188 // only the small layout.
3189 inline bool is_extended_layout();
3191 // Returns the last LayoutSection in this constant pool array.
3192 inline LayoutSection final_section();
3194 // Set up initial state for a small layout constant pool array.
3195 inline void Init(const NumberOfEntries& small);
3197 // Set up initial state for an extended layout constant pool array.
3198 inline void InitExtended(const NumberOfEntries& small,
3199 const NumberOfEntries& extended);
3201 // Clears the pointer entries with GC safe values.
3202 void ClearPtrEntries(Isolate* isolate);
3204 // returns the total number of entries in the constant pool array.
3205 inline int length();
3207 // Garbage collection support.
3211 inline static int MaxInt64Offset(int number_of_int64) {
3212 return kFirstEntryOffset + (number_of_int64 * kInt64Size);
3215 inline static int SizeFor(const NumberOfEntries& small) {
3216 int size = kFirstEntryOffset +
3217 (small.count_of(INT64) * kInt64Size) +
3218 (small.count_of(CODE_PTR) * kPointerSize) +
3219 (small.count_of(HEAP_PTR) * kPointerSize) +
3220 (small.count_of(INT32) * kInt32Size);
3221 return RoundUp(size, kPointerSize);
3224 inline static int SizeForExtended(const NumberOfEntries& small,
3225 const NumberOfEntries& extended) {
3226 int size = SizeFor(small);
3227 size = RoundUp(size, kInt64Size); // Align extended header to 64 bits.
3228 size += kExtendedFirstOffset +
3229 (extended.count_of(INT64) * kInt64Size) +
3230 (extended.count_of(CODE_PTR) * kPointerSize) +
3231 (extended.count_of(HEAP_PTR) * kPointerSize) +
3232 (extended.count_of(INT32) * kInt32Size);
3233 return RoundUp(size, kPointerSize);
3236 inline static int entry_size(Type type) {
3244 return kPointerSize;
3251 // Code Generation support.
3252 inline int OffsetOfElementAt(int index) {
3254 LayoutSection section;
3255 if (is_extended_layout() && index >= first_extended_section_index()) {
3256 section = EXTENDED_SECTION;
3257 offset = get_extended_section_header_offset() + kExtendedFirstOffset;
3259 section = SMALL_SECTION;
3260 offset = kFirstEntryOffset;
3263 // Add offsets for the preceding type sections.
3264 DCHECK(index <= last_index(LAST_TYPE, section));
3265 for (Type type = FIRST_TYPE; index > last_index(type, section);
3266 type = next_type(type)) {
3267 offset += entry_size(type) * number_of_entries(type, section);
3270 // Add offset for the index in it's type.
3271 Type type = get_type(index);
3272 offset += entry_size(type) * (index - first_index(type, section));
3276 DECLARE_CAST(ConstantPoolArray)
3278 // Garbage collection support.
3279 Object** RawFieldOfElementAt(int index) {
3280 return HeapObject::RawField(this, OffsetOfElementAt(index));
3283 // Small Layout description.
3284 static const int kSmallLayout1Offset = HeapObject::kHeaderSize;
3285 static const int kSmallLayout2Offset = kSmallLayout1Offset + kInt32Size;
3286 static const int kHeaderSize = kSmallLayout2Offset + kInt32Size;
3287 static const int kFirstEntryOffset = ROUND_UP(kHeaderSize, kInt64Size);
3289 static const int kSmallLayoutCountBits = 10;
3290 static const int kMaxSmallEntriesPerType = (1 << kSmallLayoutCountBits) - 1;
3292 // Fields in kSmallLayout1Offset.
3293 class Int64CountField: public BitField<int, 1, kSmallLayoutCountBits> {};
3294 class CodePtrCountField: public BitField<int, 11, kSmallLayoutCountBits> {};
3295 class HeapPtrCountField: public BitField<int, 21, kSmallLayoutCountBits> {};
3296 class IsExtendedField: public BitField<bool, 31, 1> {};
3298 // Fields in kSmallLayout2Offset.
3299 class Int32CountField: public BitField<int, 1, kSmallLayoutCountBits> {};
3300 class TotalCountField: public BitField<int, 11, 12> {};
3301 class WeakObjectStateField: public BitField<WeakObjectState, 23, 2> {};
3303 // Extended layout description, which starts at
3304 // get_extended_section_header_offset().
3305 static const int kExtendedInt64CountOffset = 0;
3306 static const int kExtendedCodePtrCountOffset =
3307 kExtendedInt64CountOffset + kPointerSize;
3308 static const int kExtendedHeapPtrCountOffset =
3309 kExtendedCodePtrCountOffset + kPointerSize;
3310 static const int kExtendedInt32CountOffset =
3311 kExtendedHeapPtrCountOffset + kPointerSize;
3312 static const int kExtendedFirstOffset =
3313 kExtendedInt32CountOffset + kPointerSize;
3315 // Dispatched behavior.
3316 void ConstantPoolIterateBody(ObjectVisitor* v);
3318 DECLARE_PRINTER(ConstantPoolArray)
3319 DECLARE_VERIFIER(ConstantPoolArray)
3322 inline int first_extended_section_index();
3323 inline int get_extended_section_header_offset();
3325 inline static Type next_type(Type type) {
3326 DCHECK(type >= FIRST_TYPE && type < NUMBER_OF_TYPES);
3327 int type_int = static_cast<int>(type);
3328 return static_cast<Type>(++type_int);
3331 DISALLOW_IMPLICIT_CONSTRUCTORS(ConstantPoolArray);
3335 // DescriptorArrays are fixed arrays used to hold instance descriptors.
3336 // The format of the these objects is:
3337 // [0]: Number of descriptors
3338 // [1]: Either Smi(0) if uninitialized, or a pointer to small fixed array:
3339 // [0]: pointer to fixed array with enum cache
3340 // [1]: either Smi(0) or pointer to fixed array with indices
3342 // [2 + number of descriptors * kDescriptorSize]: start of slack
3343 class DescriptorArray: public FixedArray {
3345 // Returns true for both shared empty_descriptor_array and for smis, which the
3346 // map uses to encode additional bit fields when the descriptor array is not
3348 inline bool IsEmpty();
3350 // Returns the number of descriptors in the array.
3351 int number_of_descriptors() {
3352 DCHECK(length() >= kFirstIndex || IsEmpty());
3354 return len == 0 ? 0 : Smi::cast(get(kDescriptorLengthIndex))->value();
3357 int number_of_descriptors_storage() {
3359 return len == 0 ? 0 : (len - kFirstIndex) / kDescriptorSize;
3362 int NumberOfSlackDescriptors() {
3363 return number_of_descriptors_storage() - number_of_descriptors();
3366 inline void SetNumberOfDescriptors(int number_of_descriptors);
3367 inline int number_of_entries() { return number_of_descriptors(); }
3369 bool HasEnumCache() {
3370 return !IsEmpty() && !get(kEnumCacheIndex)->IsSmi();
3373 void CopyEnumCacheFrom(DescriptorArray* array) {
3374 set(kEnumCacheIndex, array->get(kEnumCacheIndex));
3377 FixedArray* GetEnumCache() {
3378 DCHECK(HasEnumCache());
3379 FixedArray* bridge = FixedArray::cast(get(kEnumCacheIndex));
3380 return FixedArray::cast(bridge->get(kEnumCacheBridgeCacheIndex));
3383 bool HasEnumIndicesCache() {
3384 if (IsEmpty()) return false;
3385 Object* object = get(kEnumCacheIndex);
3386 if (object->IsSmi()) return false;
3387 FixedArray* bridge = FixedArray::cast(object);
3388 return !bridge->get(kEnumCacheBridgeIndicesCacheIndex)->IsSmi();
3391 FixedArray* GetEnumIndicesCache() {
3392 DCHECK(HasEnumIndicesCache());
3393 FixedArray* bridge = FixedArray::cast(get(kEnumCacheIndex));
3394 return FixedArray::cast(bridge->get(kEnumCacheBridgeIndicesCacheIndex));
3397 Object** GetEnumCacheSlot() {
3398 DCHECK(HasEnumCache());
3399 return HeapObject::RawField(reinterpret_cast<HeapObject*>(this),
3403 void ClearEnumCache();
3405 // Initialize or change the enum cache,
3406 // using the supplied storage for the small "bridge".
3407 void SetEnumCache(FixedArray* bridge_storage,
3408 FixedArray* new_cache,
3409 Object* new_index_cache);
3411 bool CanHoldValue(int descriptor, Object* value);
3413 // Accessors for fetching instance descriptor at descriptor number.
3414 inline Name* GetKey(int descriptor_number);
3415 inline Object** GetKeySlot(int descriptor_number);
3416 inline Object* GetValue(int descriptor_number);
3417 inline void SetValue(int descriptor_number, Object* value);
3418 inline Object** GetValueSlot(int descriptor_number);
3419 static inline int GetValueOffset(int descriptor_number);
3420 inline Object** GetDescriptorStartSlot(int descriptor_number);
3421 inline Object** GetDescriptorEndSlot(int descriptor_number);
3422 inline PropertyDetails GetDetails(int descriptor_number);
3423 inline PropertyType GetType(int descriptor_number);
3424 inline int GetFieldIndex(int descriptor_number);
3425 inline HeapType* GetFieldType(int descriptor_number);
3426 inline Object* GetConstant(int descriptor_number);
3427 inline Object* GetCallbacksObject(int descriptor_number);
3428 inline AccessorDescriptor* GetCallbacks(int descriptor_number);
3430 inline Name* GetSortedKey(int descriptor_number);
3431 inline int GetSortedKeyIndex(int descriptor_number);
3432 inline void SetSortedKey(int pointer, int descriptor_number);
3433 inline void SetRepresentation(int descriptor_number,
3434 Representation representation);
3436 // Accessor for complete descriptor.
3437 inline void Get(int descriptor_number, Descriptor* desc);
3438 inline void Set(int descriptor_number, Descriptor* desc);
3439 void Replace(int descriptor_number, Descriptor* descriptor);
3441 // Append automatically sets the enumeration index. This should only be used
3442 // to add descriptors in bulk at the end, followed by sorting the descriptor
3444 inline void Append(Descriptor* desc);
3446 static Handle<DescriptorArray> CopyUpTo(Handle<DescriptorArray> desc,
3447 int enumeration_index,
3450 static Handle<DescriptorArray> CopyUpToAddAttributes(
3451 Handle<DescriptorArray> desc,
3452 int enumeration_index,
3453 PropertyAttributes attributes,
3456 // Sort the instance descriptors by the hash codes of their keys.
3459 // Search the instance descriptors for given name.
3460 INLINE(int Search(Name* name, int number_of_own_descriptors));
3462 // As the above, but uses DescriptorLookupCache and updates it when
3464 INLINE(int SearchWithCache(Name* name, Map* map));
3466 // Allocates a DescriptorArray, but returns the singleton
3467 // empty descriptor array object if number_of_descriptors is 0.
3468 static Handle<DescriptorArray> Allocate(Isolate* isolate,
3469 int number_of_descriptors,
3472 DECLARE_CAST(DescriptorArray)
3474 // Constant for denoting key was not found.
3475 static const int kNotFound = -1;
3477 static const int kDescriptorLengthIndex = 0;
3478 static const int kEnumCacheIndex = 1;
3479 static const int kFirstIndex = 2;
3481 // The length of the "bridge" to the enum cache.
3482 static const int kEnumCacheBridgeLength = 2;
3483 static const int kEnumCacheBridgeCacheIndex = 0;
3484 static const int kEnumCacheBridgeIndicesCacheIndex = 1;
3486 // Layout description.
3487 static const int kDescriptorLengthOffset = FixedArray::kHeaderSize;
3488 static const int kEnumCacheOffset = kDescriptorLengthOffset + kPointerSize;
3489 static const int kFirstOffset = kEnumCacheOffset + kPointerSize;
3491 // Layout description for the bridge array.
3492 static const int kEnumCacheBridgeCacheOffset = FixedArray::kHeaderSize;
3494 // Layout of descriptor.
3495 static const int kDescriptorKey = 0;
3496 static const int kDescriptorDetails = 1;
3497 static const int kDescriptorValue = 2;
3498 static const int kDescriptorSize = 3;
3501 // Print all the descriptors.
3502 void PrintDescriptors(OStream& os); // NOLINT
3506 // Is the descriptor array sorted and without duplicates?
3507 bool IsSortedNoDuplicates(int valid_descriptors = -1);
3509 // Is the descriptor array consistent with the back pointers in targets?
3510 bool IsConsistentWithBackPointers(Map* current_map);
3512 // Are two DescriptorArrays equal?
3513 bool IsEqualTo(DescriptorArray* other);
3516 // Returns the fixed array length required to hold number_of_descriptors
3518 static int LengthFor(int number_of_descriptors) {
3519 return ToKeyIndex(number_of_descriptors);
3523 // WhitenessWitness is used to prove that a descriptor array is white
3524 // (unmarked), so incremental write barriers can be skipped because the
3525 // marking invariant cannot be broken and slots pointing into evacuation
3526 // candidates will be discovered when the object is scanned. A witness is
3527 // always stack-allocated right after creating an array. By allocating a
3528 // witness, incremental marking is globally disabled. The witness is then
3529 // passed along wherever needed to statically prove that the array is known to
3531 class WhitenessWitness {
3533 inline explicit WhitenessWitness(DescriptorArray* array);
3534 inline ~WhitenessWitness();
3537 IncrementalMarking* marking_;
3540 // An entry in a DescriptorArray, represented as an (array, index) pair.
3543 inline explicit Entry(DescriptorArray* descs, int index) :
3544 descs_(descs), index_(index) { }
3546 inline PropertyType type() { return descs_->GetType(index_); }
3547 inline Object* GetCallbackObject() { return descs_->GetValue(index_); }
3550 DescriptorArray* descs_;
3554 // Conversion from descriptor number to array indices.
3555 static int ToKeyIndex(int descriptor_number) {
3556 return kFirstIndex +
3557 (descriptor_number * kDescriptorSize) +
3561 static int ToDetailsIndex(int descriptor_number) {
3562 return kFirstIndex +
3563 (descriptor_number * kDescriptorSize) +
3567 static int ToValueIndex(int descriptor_number) {
3568 return kFirstIndex +
3569 (descriptor_number * kDescriptorSize) +
3573 // Transfer a complete descriptor from the src descriptor array to this
3574 // descriptor array.
3575 void CopyFrom(int index,
3576 DescriptorArray* src,
3577 const WhitenessWitness&);
3579 inline void Set(int descriptor_number,
3581 const WhitenessWitness&);
3583 inline void Append(Descriptor* desc, const WhitenessWitness&);
3585 // Swap first and second descriptor.
3586 inline void SwapSortedKeys(int first, int second);
3588 DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
3592 enum SearchMode { ALL_ENTRIES, VALID_ENTRIES };
3594 template<SearchMode search_mode, typename T>
3595 inline int LinearSearch(T* array, Name* name, int len, int valid_entries);
3598 template<SearchMode search_mode, typename T>
3599 inline int Search(T* array, Name* name, int valid_entries = 0);
3602 // HashTable is a subclass of FixedArray that implements a hash table
3603 // that uses open addressing and quadratic probing.
3605 // In order for the quadratic probing to work, elements that have not
3606 // yet been used and elements that have been deleted are
3607 // distinguished. Probing continues when deleted elements are
3608 // encountered and stops when unused elements are encountered.
3610 // - Elements with key == undefined have not been used yet.
3611 // - Elements with key == the_hole have been deleted.
3613 // The hash table class is parameterized with a Shape and a Key.
3614 // Shape must be a class with the following interface:
3615 // class ExampleShape {
3617 // // Tells whether key matches other.
3618 // static bool IsMatch(Key key, Object* other);
3619 // // Returns the hash value for key.
3620 // static uint32_t Hash(Key key);
3621 // // Returns the hash value for object.
3622 // static uint32_t HashForObject(Key key, Object* object);
3623 // // Convert key to an object.
3624 // static inline Handle<Object> AsHandle(Isolate* isolate, Key key);
3625 // // The prefix size indicates number of elements in the beginning
3626 // // of the backing storage.
3627 // static const int kPrefixSize = ..;
3628 // // The Element size indicates number of elements per entry.
3629 // static const int kEntrySize = ..;
3631 // The prefix size indicates an amount of memory in the
3632 // beginning of the backing storage that can be used for non-element
3633 // information by subclasses.
3635 template<typename Key>
3638 static const bool UsesSeed = false;
3639 static uint32_t Hash(Key key) { return 0; }
3640 static uint32_t SeededHash(Key key, uint32_t seed) {
3644 static uint32_t HashForObject(Key key, Object* object) { return 0; }
3645 static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
3647 return HashForObject(key, object);
3651 template<typename Derived, typename Shape, typename Key>
3652 class HashTable: public FixedArray {
3655 inline uint32_t Hash(Key key) {
3656 if (Shape::UsesSeed) {
3657 return Shape::SeededHash(key, GetHeap()->HashSeed());
3659 return Shape::Hash(key);
3663 inline uint32_t HashForObject(Key key, Object* object) {
3664 if (Shape::UsesSeed) {
3665 return Shape::SeededHashForObject(key, GetHeap()->HashSeed(), object);
3667 return Shape::HashForObject(key, object);
3671 // Returns the number of elements in the hash table.
3672 int NumberOfElements() {
3673 return Smi::cast(get(kNumberOfElementsIndex))->value();
3676 // Returns the number of deleted elements in the hash table.
3677 int NumberOfDeletedElements() {
3678 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3681 // Returns the capacity of the hash table.
3683 return Smi::cast(get(kCapacityIndex))->value();
3686 // ElementAdded should be called whenever an element is added to a
3688 void ElementAdded() { SetNumberOfElements(NumberOfElements() + 1); }
3690 // ElementRemoved should be called whenever an element is removed from
3692 void ElementRemoved() {
3693 SetNumberOfElements(NumberOfElements() - 1);
3694 SetNumberOfDeletedElements(NumberOfDeletedElements() + 1);
3696 void ElementsRemoved(int n) {
3697 SetNumberOfElements(NumberOfElements() - n);
3698 SetNumberOfDeletedElements(NumberOfDeletedElements() + n);
3701 // Returns a new HashTable object.
3702 MUST_USE_RESULT static Handle<Derived> New(
3704 int at_least_space_for,
3705 MinimumCapacity capacity_option = USE_DEFAULT_MINIMUM_CAPACITY,
3706 PretenureFlag pretenure = NOT_TENURED);
3708 // Computes the required capacity for a table holding the given
3709 // number of elements. May be more than HashTable::kMaxCapacity.
3710 static int ComputeCapacity(int at_least_space_for);
3712 // Returns the key at entry.
3713 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3715 // Tells whether k is a real key. The hole and undefined are not allowed
3716 // as keys and can be used to indicate missing or deleted elements.
3717 bool IsKey(Object* k) {
3718 return !k->IsTheHole() && !k->IsUndefined();
3721 // Garbage collection support.
3722 void IteratePrefix(ObjectVisitor* visitor);
3723 void IterateElements(ObjectVisitor* visitor);
3725 DECLARE_CAST(HashTable)
3727 // Compute the probe offset (quadratic probing).
3728 INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
3729 return (n + n * n) >> 1;
3732 static const int kNumberOfElementsIndex = 0;
3733 static const int kNumberOfDeletedElementsIndex = 1;
3734 static const int kCapacityIndex = 2;
3735 static const int kPrefixStartIndex = 3;
3736 static const int kElementsStartIndex =
3737 kPrefixStartIndex + Shape::kPrefixSize;
3738 static const int kEntrySize = Shape::kEntrySize;
3739 static const int kElementsStartOffset =
3740 kHeaderSize + kElementsStartIndex * kPointerSize;
3741 static const int kCapacityOffset =
3742 kHeaderSize + kCapacityIndex * kPointerSize;
3744 // Constant used for denoting a absent entry.
3745 static const int kNotFound = -1;
3747 // Maximal capacity of HashTable. Based on maximal length of underlying
3748 // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
3750 static const int kMaxCapacity =
3751 (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
3753 // Find entry for key otherwise return kNotFound.
3754 inline int FindEntry(Key key);
3755 int FindEntry(Isolate* isolate, Key key);
3757 // Rehashes the table in-place.
3758 void Rehash(Key key);
3761 friend class ObjectHashTable;
3763 // Find the entry at which to insert element with the given key that
3764 // has the given hash value.
3765 uint32_t FindInsertionEntry(uint32_t hash);
3767 // Returns the index for an entry (of the key)
3768 static inline int EntryToIndex(int entry) {
3769 return (entry * kEntrySize) + kElementsStartIndex;
3772 // Update the number of elements in the hash table.
3773 void SetNumberOfElements(int nof) {
3774 set(kNumberOfElementsIndex, Smi::FromInt(nof));
3777 // Update the number of deleted elements in the hash table.
3778 void SetNumberOfDeletedElements(int nod) {
3779 set(kNumberOfDeletedElementsIndex, Smi::FromInt(nod));
3782 // Sets the capacity of the hash table.
3783 void SetCapacity(int capacity) {
3784 // To scale a computed hash code to fit within the hash table, we
3785 // use bit-wise AND with a mask, so the capacity must be positive
3787 DCHECK(capacity > 0);
3788 DCHECK(capacity <= kMaxCapacity);
3789 set(kCapacityIndex, Smi::FromInt(capacity));
3793 // Returns probe entry.
3794 static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
3795 DCHECK(IsPowerOf2(size));
3796 return (hash + GetProbeOffset(number)) & (size - 1);
3799 inline static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
3800 return hash & (size - 1);
3803 inline static uint32_t NextProbe(
3804 uint32_t last, uint32_t number, uint32_t size) {
3805 return (last + number) & (size - 1);
3808 // Attempt to shrink hash table after removal of key.
3809 MUST_USE_RESULT static Handle<Derived> Shrink(Handle<Derived> table, Key key);
3811 // Ensure enough space for n additional elements.
3812 MUST_USE_RESULT static Handle<Derived> EnsureCapacity(
3813 Handle<Derived> table,
3816 PretenureFlag pretenure = NOT_TENURED);
3819 // Returns _expected_ if one of entries given by the first _probe_ probes is
3820 // equal to _expected_. Otherwise, returns the entry given by the probe
3822 uint32_t EntryForProbe(Key key, Object* k, int probe, uint32_t expected);
3824 void Swap(uint32_t entry1, uint32_t entry2, WriteBarrierMode mode);
3826 // Rehashes this hash-table into the new table.
3827 void Rehash(Handle<Derived> new_table, Key key);
3831 // HashTableKey is an abstract superclass for virtual key behavior.
3832 class HashTableKey {
3834 // Returns whether the other object matches this key.
3835 virtual bool IsMatch(Object* other) = 0;
3836 // Returns the hash value for this key.
3837 virtual uint32_t Hash() = 0;
3838 // Returns the hash value for object.
3839 virtual uint32_t HashForObject(Object* key) = 0;
3840 // Returns the key object for storing into the hash table.
3841 MUST_USE_RESULT virtual Handle<Object> AsHandle(Isolate* isolate) = 0;
3843 virtual ~HashTableKey() {}
3847 class StringTableShape : public BaseShape<HashTableKey*> {
3849 static inline bool IsMatch(HashTableKey* key, Object* value) {
3850 return key->IsMatch(value);
3853 static inline uint32_t Hash(HashTableKey* key) {
3857 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3858 return key->HashForObject(object);
3861 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3863 static const int kPrefixSize = 0;
3864 static const int kEntrySize = 1;
3867 class SeqOneByteString;
3871 // No special elements in the prefix and the element size is 1
3872 // because only the string itself (the key) needs to be stored.
3873 class StringTable: public HashTable<StringTable,
3877 // Find string in the string table. If it is not there yet, it is
3878 // added. The return value is the string found.
3879 static Handle<String> LookupString(Isolate* isolate, Handle<String> key);
3880 static Handle<String> LookupKey(Isolate* isolate, HashTableKey* key);
3882 // Tries to internalize given string and returns string handle on success
3883 // or an empty handle otherwise.
3884 MUST_USE_RESULT static MaybeHandle<String> InternalizeStringIfExists(
3886 Handle<String> string);
3888 // Looks up a string that is equal to the given string and returns
3889 // string handle if it is found, or an empty handle otherwise.
3890 MUST_USE_RESULT static MaybeHandle<String> LookupStringIfExists(
3892 Handle<String> str);
3893 MUST_USE_RESULT static MaybeHandle<String> LookupTwoCharsStringIfExists(
3898 DECLARE_CAST(StringTable)
3901 template <bool seq_ascii> friend class JsonParser;
3903 DISALLOW_IMPLICIT_CONSTRUCTORS(StringTable);
3907 class MapCacheShape : public BaseShape<HashTableKey*> {
3909 static inline bool IsMatch(HashTableKey* key, Object* value) {
3910 return key->IsMatch(value);
3913 static inline uint32_t Hash(HashTableKey* key) {
3917 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3918 return key->HashForObject(object);
3921 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3923 static const int kPrefixSize = 0;
3924 static const int kEntrySize = 2;
3930 // Maps keys that are a fixed array of unique names to a map.
3931 // Used for canonicalize maps for object literals.
3932 class MapCache: public HashTable<MapCache, MapCacheShape, HashTableKey*> {
3934 // Find cached value for a name key, otherwise return null.
3935 Object* Lookup(FixedArray* key);
3936 static Handle<MapCache> Put(
3937 Handle<MapCache> map_cache, Handle<FixedArray> key, Handle<Map> value);
3938 DECLARE_CAST(MapCache)
3941 DISALLOW_IMPLICIT_CONSTRUCTORS(MapCache);
3945 template <typename Derived, typename Shape, typename Key>
3946 class Dictionary: public HashTable<Derived, Shape, Key> {
3948 typedef HashTable<Derived, Shape, Key> DerivedHashTable;
3951 // Returns the value at entry.
3952 Object* ValueAt(int entry) {
3953 return this->get(DerivedHashTable::EntryToIndex(entry) + 1);
3956 // Set the value for entry.
3957 void ValueAtPut(int entry, Object* value) {
3958 this->set(DerivedHashTable::EntryToIndex(entry) + 1, value);
3961 // Returns the property details for the property at entry.
3962 PropertyDetails DetailsAt(int entry) {
3963 DCHECK(entry >= 0); // Not found is -1, which is not caught by get().
3964 return PropertyDetails(
3965 Smi::cast(this->get(DerivedHashTable::EntryToIndex(entry) + 2)));
3968 // Set the details for entry.
3969 void DetailsAtPut(int entry, PropertyDetails value) {
3970 this->set(DerivedHashTable::EntryToIndex(entry) + 2, value.AsSmi());
3974 void CopyValuesTo(FixedArray* elements);
3976 // Delete a property from the dictionary.
3977 static Handle<Object> DeleteProperty(
3978 Handle<Derived> dictionary,
3980 JSObject::DeleteMode mode);
3982 // Attempt to shrink the dictionary after deletion of key.
3983 MUST_USE_RESULT static inline Handle<Derived> Shrink(
3984 Handle<Derived> dictionary,
3986 return DerivedHashTable::Shrink(dictionary, key);
3989 // Returns the number of elements in the dictionary filtering out properties
3990 // with the specified attributes.
3991 int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3993 // Returns the number of enumerable elements in the dictionary.
3994 int NumberOfEnumElements();
3996 enum SortMode { UNSORTED, SORTED };
3997 // Copies keys to preallocated fixed array.
3998 void CopyKeysTo(FixedArray* storage,
3999 PropertyAttributes filter,
4000 SortMode sort_mode);
4001 // Fill in details for properties into storage.
4002 void CopyKeysTo(FixedArray* storage,
4004 PropertyAttributes filter,
4005 SortMode sort_mode);
4007 // Accessors for next enumeration index.
4008 void SetNextEnumerationIndex(int index) {
4010 this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
4013 int NextEnumerationIndex() {
4014 return Smi::cast(this->get(kNextEnumerationIndexIndex))->value();
4017 // Creates a new dictionary.
4018 MUST_USE_RESULT static Handle<Derived> New(
4020 int at_least_space_for,
4021 PretenureFlag pretenure = NOT_TENURED);
4023 // Ensure enough space for n additional elements.
4024 static Handle<Derived> EnsureCapacity(Handle<Derived> obj, int n, Key key);
4027 void Print(OStream& os); // NOLINT
4029 // Returns the key (slow).
4030 Object* SlowReverseLookup(Object* value);
4032 // Sets the entry to (key, value) pair.
4033 inline void SetEntry(int entry,
4035 Handle<Object> value);
4036 inline void SetEntry(int entry,
4038 Handle<Object> value,
4039 PropertyDetails details);
4041 MUST_USE_RESULT static Handle<Derived> Add(
4042 Handle<Derived> dictionary,
4044 Handle<Object> value,
4045 PropertyDetails details);
4048 // Generic at put operation.
4049 MUST_USE_RESULT static Handle<Derived> AtPut(
4050 Handle<Derived> dictionary,
4052 Handle<Object> value);
4054 // Add entry to dictionary.
4055 static void AddEntry(
4056 Handle<Derived> dictionary,
4058 Handle<Object> value,
4059 PropertyDetails details,
4062 // Generate new enumeration indices to avoid enumeration index overflow.
4063 static void GenerateNewEnumerationIndices(Handle<Derived> dictionary);
4064 static const int kMaxNumberKeyIndex = DerivedHashTable::kPrefixStartIndex;
4065 static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
4069 class NameDictionaryShape : public BaseShape<Handle<Name> > {
4071 static inline bool IsMatch(Handle<Name> key, Object* other);
4072 static inline uint32_t Hash(Handle<Name> key);
4073 static inline uint32_t HashForObject(Handle<Name> key, Object* object);
4074 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Name> key);
4075 static const int kPrefixSize = 2;
4076 static const int kEntrySize = 3;
4077 static const bool kIsEnumerable = true;
4081 class NameDictionary: public Dictionary<NameDictionary,
4082 NameDictionaryShape,
4085 NameDictionary, NameDictionaryShape, Handle<Name> > DerivedDictionary;
4088 DECLARE_CAST(NameDictionary)
4090 // Copies enumerable keys to preallocated fixed array.
4091 void CopyEnumKeysTo(FixedArray* storage);
4092 inline static void DoGenerateNewEnumerationIndices(
4093 Handle<NameDictionary> dictionary);
4095 // Find entry for key, otherwise return kNotFound. Optimized version of
4096 // HashTable::FindEntry.
4097 int FindEntry(Handle<Name> key);
4101 class NumberDictionaryShape : public BaseShape<uint32_t> {
4103 static inline bool IsMatch(uint32_t key, Object* other);
4104 static inline Handle<Object> AsHandle(Isolate* isolate, uint32_t key);
4105 static const int kEntrySize = 3;
4106 static const bool kIsEnumerable = false;
4110 class SeededNumberDictionaryShape : public NumberDictionaryShape {
4112 static const bool UsesSeed = true;
4113 static const int kPrefixSize = 2;
4115 static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
4116 static inline uint32_t SeededHashForObject(uint32_t key,
4122 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
4124 static const int kPrefixSize = 0;
4126 static inline uint32_t Hash(uint32_t key);
4127 static inline uint32_t HashForObject(uint32_t key, Object* object);
4131 class SeededNumberDictionary
4132 : public Dictionary<SeededNumberDictionary,
4133 SeededNumberDictionaryShape,
4136 DECLARE_CAST(SeededNumberDictionary)
4138 // Type specific at put (default NONE attributes is used when adding).
4139 MUST_USE_RESULT static Handle<SeededNumberDictionary> AtNumberPut(
4140 Handle<SeededNumberDictionary> dictionary,
4142 Handle<Object> value);
4143 MUST_USE_RESULT static Handle<SeededNumberDictionary> AddNumberEntry(
4144 Handle<SeededNumberDictionary> dictionary,
4146 Handle<Object> value,
4147 PropertyDetails details);
4149 // Set an existing entry or add a new one if needed.
4150 // Return the updated dictionary.
4151 MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
4152 Handle<SeededNumberDictionary> dictionary,
4154 Handle<Object> value,
4155 PropertyDetails details);
4157 void UpdateMaxNumberKey(uint32_t key);
4159 // If slow elements are required we will never go back to fast-case
4160 // for the elements kept in this dictionary. We require slow
4161 // elements if an element has been added at an index larger than
4162 // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
4163 // when defining a getter or setter with a number key.
4164 inline bool requires_slow_elements();
4165 inline void set_requires_slow_elements();
4167 // Get the value of the max number key that has been added to this
4168 // dictionary. max_number_key can only be called if
4169 // requires_slow_elements returns false.
4170 inline uint32_t max_number_key();
4173 static const int kRequiresSlowElementsMask = 1;
4174 static const int kRequiresSlowElementsTagSize = 1;
4175 static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
4179 class UnseededNumberDictionary
4180 : public Dictionary<UnseededNumberDictionary,
4181 UnseededNumberDictionaryShape,
4184 DECLARE_CAST(UnseededNumberDictionary)
4186 // Type specific at put (default NONE attributes is used when adding).
4187 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AtNumberPut(
4188 Handle<UnseededNumberDictionary> dictionary,
4190 Handle<Object> value);
4191 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AddNumberEntry(
4192 Handle<UnseededNumberDictionary> dictionary,
4194 Handle<Object> value);
4196 // Set an existing entry or add a new one if needed.
4197 // Return the updated dictionary.
4198 MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
4199 Handle<UnseededNumberDictionary> dictionary,
4201 Handle<Object> value);
4205 class ObjectHashTableShape : public BaseShape<Handle<Object> > {
4207 static inline bool IsMatch(Handle<Object> key, Object* other);
4208 static inline uint32_t Hash(Handle<Object> key);
4209 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
4210 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
4211 static const int kPrefixSize = 0;
4212 static const int kEntrySize = 2;
4216 // ObjectHashTable maps keys that are arbitrary objects to object values by
4217 // using the identity hash of the key for hashing purposes.
4218 class ObjectHashTable: public HashTable<ObjectHashTable,
4219 ObjectHashTableShape,
4222 ObjectHashTable, ObjectHashTableShape, Handle<Object> > DerivedHashTable;
4224 DECLARE_CAST(ObjectHashTable)
4226 // Attempt to shrink hash table after removal of key.
4227 MUST_USE_RESULT static inline Handle<ObjectHashTable> Shrink(
4228 Handle<ObjectHashTable> table,
4229 Handle<Object> key);
4231 // Looks up the value associated with the given key. The hole value is
4232 // returned in case the key is not present.
4233 Object* Lookup(Handle<Object> key);
4235 // Adds (or overwrites) the value associated with the given key.
4236 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
4238 Handle<Object> value);
4240 // Returns an ObjectHashTable (possibly |table|) where |key| has been removed.
4241 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
4246 friend class MarkCompactCollector;
4248 void AddEntry(int entry, Object* key, Object* value);
4249 void RemoveEntry(int entry);
4251 // Returns the index to the value of an entry.
4252 static inline int EntryToValueIndex(int entry) {
4253 return EntryToIndex(entry) + 1;
4258 // OrderedHashTable is a HashTable with Object keys that preserves
4259 // insertion order. There are Map and Set interfaces (OrderedHashMap
4260 // and OrderedHashTable, below). It is meant to be used by JSMap/JSSet.
4262 // Only Object* keys are supported, with Object::SameValueZero() used as the
4263 // equality operator and Object::GetHash() for the hash function.
4265 // Based on the "Deterministic Hash Table" as described by Jason Orendorff at
4266 // https://wiki.mozilla.org/User:Jorend/Deterministic_hash_tables
4267 // Originally attributed to Tyler Close.
4270 // [0]: bucket count
4271 // [1]: element count
4272 // [2]: deleted element count
4273 // [3..(3 + NumberOfBuckets() - 1)]: "hash table", where each item is an
4274 // offset into the data table (see below) where the
4275 // first item in this bucket is stored.
4276 // [3 + NumberOfBuckets()..length]: "data table", an array of length
4277 // Capacity() * kEntrySize, where the first entrysize
4278 // items are handled by the derived class and the
4279 // item at kChainOffset is another entry into the
4280 // data table indicating the next entry in this hash
4283 // When we transition the table to a new version we obsolete it and reuse parts
4284 // of the memory to store information how to transition an iterator to the new
4287 // Memory layout for obsolete table:
4288 // [0]: bucket count
4289 // [1]: Next newer table
4290 // [2]: Number of removed holes or -1 when the table was cleared.
4291 // [3..(3 + NumberOfRemovedHoles() - 1)]: The indexes of the removed holes.
4292 // [3 + NumberOfRemovedHoles()..length]: Not used
4294 template<class Derived, class Iterator, int entrysize>
4295 class OrderedHashTable: public FixedArray {
4297 // Returns an OrderedHashTable with a capacity of at least |capacity|.
4298 static Handle<Derived> Allocate(
4299 Isolate* isolate, int capacity, PretenureFlag pretenure = NOT_TENURED);
4301 // Returns an OrderedHashTable (possibly |table|) with enough space
4302 // to add at least one new element.
4303 static Handle<Derived> EnsureGrowable(Handle<Derived> table);
4305 // Returns an OrderedHashTable (possibly |table|) that's shrunken
4307 static Handle<Derived> Shrink(Handle<Derived> table);
4309 // Returns a new empty OrderedHashTable and records the clearing so that
4310 // exisiting iterators can be updated.
4311 static Handle<Derived> Clear(Handle<Derived> table);
4313 // Returns an OrderedHashTable (possibly |table|) where |key| has been
4315 static Handle<Derived> Remove(Handle<Derived> table, Handle<Object> key,
4318 // Returns kNotFound if the key isn't present.
4319 int FindEntry(Handle<Object> key, int hash);
4321 // Like the above, but doesn't require the caller to provide a hash.
4322 int FindEntry(Handle<Object> key);
4324 int NumberOfElements() {
4325 return Smi::cast(get(kNumberOfElementsIndex))->value();
4328 int NumberOfDeletedElements() {
4329 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
4332 int UsedCapacity() { return NumberOfElements() + NumberOfDeletedElements(); }
4334 int NumberOfBuckets() {
4335 return Smi::cast(get(kNumberOfBucketsIndex))->value();
4338 // Returns the index into the data table where the new entry
4339 // should be placed. The table is assumed to have enough space
4341 int AddEntry(int hash);
4343 // Removes the entry, and puts the_hole in entrysize pointers
4344 // (leaving the hash table chain intact).
4345 void RemoveEntry(int entry);
4347 // Returns an index into |this| for the given entry.
4348 int EntryToIndex(int entry) {
4349 return kHashTableStartIndex + NumberOfBuckets() + (entry * kEntrySize);
4352 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
4355 return !get(kNextTableIndex)->IsSmi();
4358 // The next newer table. This is only valid if the table is obsolete.
4359 Derived* NextTable() {
4360 return Derived::cast(get(kNextTableIndex));
4363 // When the table is obsolete we store the indexes of the removed holes.
4364 int RemovedIndexAt(int index) {
4365 return Smi::cast(get(kRemovedHolesIndex + index))->value();
4368 static const int kNotFound = -1;
4369 static const int kMinCapacity = 4;
4372 static Handle<Derived> Rehash(Handle<Derived> table, int new_capacity);
4374 void SetNumberOfBuckets(int num) {
4375 set(kNumberOfBucketsIndex, Smi::FromInt(num));
4378 void SetNumberOfElements(int num) {
4379 set(kNumberOfElementsIndex, Smi::FromInt(num));
4382 void SetNumberOfDeletedElements(int num) {
4383 set(kNumberOfDeletedElementsIndex, Smi::FromInt(num));
4387 return NumberOfBuckets() * kLoadFactor;
4390 // Returns the next entry for the given entry.
4391 int ChainAt(int entry) {
4392 return Smi::cast(get(EntryToIndex(entry) + kChainOffset))->value();
4395 int HashToBucket(int hash) {
4396 return hash & (NumberOfBuckets() - 1);
4399 int HashToEntry(int hash) {
4400 int bucket = HashToBucket(hash);
4401 return Smi::cast(get(kHashTableStartIndex + bucket))->value();
4404 void SetNextTable(Derived* next_table) {
4405 set(kNextTableIndex, next_table);
4408 void SetRemovedIndexAt(int index, int removed_index) {
4409 return set(kRemovedHolesIndex + index, Smi::FromInt(removed_index));
4412 static const int kNumberOfBucketsIndex = 0;
4413 static const int kNumberOfElementsIndex = kNumberOfBucketsIndex + 1;
4414 static const int kNumberOfDeletedElementsIndex = kNumberOfElementsIndex + 1;
4415 static const int kHashTableStartIndex = kNumberOfDeletedElementsIndex + 1;
4417 static const int kNextTableIndex = kNumberOfElementsIndex;
4418 static const int kRemovedHolesIndex = kHashTableStartIndex;
4420 static const int kEntrySize = entrysize + 1;
4421 static const int kChainOffset = entrysize;
4423 static const int kLoadFactor = 2;
4424 static const int kMaxCapacity =
4425 (FixedArray::kMaxLength - kHashTableStartIndex)
4426 / (1 + (kEntrySize * kLoadFactor));
4430 class JSSetIterator;
4433 class OrderedHashSet: public OrderedHashTable<
4434 OrderedHashSet, JSSetIterator, 1> {
4436 DECLARE_CAST(OrderedHashSet)
4438 bool Contains(Handle<Object> key);
4439 static Handle<OrderedHashSet> Add(
4440 Handle<OrderedHashSet> table, Handle<Object> key);
4444 class JSMapIterator;
4447 class OrderedHashMap:public OrderedHashTable<
4448 OrderedHashMap, JSMapIterator, 2> {
4450 DECLARE_CAST(OrderedHashMap)
4452 Object* Lookup(Handle<Object> key);
4453 static Handle<OrderedHashMap> Put(
4454 Handle<OrderedHashMap> table,
4456 Handle<Object> value);
4458 Object* ValueAt(int entry) {
4459 return get(EntryToIndex(entry) + kValueOffset);
4463 static const int kValueOffset = 1;
4467 template <int entrysize>
4468 class WeakHashTableShape : public BaseShape<Handle<Object> > {
4470 static inline bool IsMatch(Handle<Object> key, Object* other);
4471 static inline uint32_t Hash(Handle<Object> key);
4472 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
4473 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
4474 static const int kPrefixSize = 0;
4475 static const int kEntrySize = entrysize;
4479 // WeakHashTable maps keys that are arbitrary objects to object values.
4480 // It is used for the global weak hash table that maps objects
4481 // embedded in optimized code to dependent code lists.
4482 class WeakHashTable: public HashTable<WeakHashTable,
4483 WeakHashTableShape<2>,
4486 WeakHashTable, WeakHashTableShape<2>, Handle<Object> > DerivedHashTable;
4488 DECLARE_CAST(WeakHashTable)
4490 // Looks up the value associated with the given key. The hole value is
4491 // returned in case the key is not present.
4492 Object* Lookup(Handle<Object> key);
4494 // Adds (or overwrites) the value associated with the given key. Mapping a
4495 // key to the hole value causes removal of the whole entry.
4496 MUST_USE_RESULT static Handle<WeakHashTable> Put(Handle<WeakHashTable> table,
4498 Handle<Object> value);
4500 // This function is called when heap verification is turned on.
4501 void Zap(Object* value) {
4502 int capacity = Capacity();
4503 for (int i = 0; i < capacity; i++) {
4504 set(EntryToIndex(i), value);
4505 set(EntryToValueIndex(i), value);
4510 friend class MarkCompactCollector;
4512 void AddEntry(int entry, Handle<Object> key, Handle<Object> value);
4514 // Returns the index to the value of an entry.
4515 static inline int EntryToValueIndex(int entry) {
4516 return EntryToIndex(entry) + 1;
4521 // JSFunctionResultCache caches results of some JSFunction invocation.
4522 // It is a fixed array with fixed structure:
4523 // [0]: factory function
4524 // [1]: finger index
4525 // [2]: current cache size
4526 // [3]: dummy field.
4527 // The rest of array are key/value pairs.
4528 class JSFunctionResultCache: public FixedArray {
4530 static const int kFactoryIndex = 0;
4531 static const int kFingerIndex = kFactoryIndex + 1;
4532 static const int kCacheSizeIndex = kFingerIndex + 1;
4533 static const int kDummyIndex = kCacheSizeIndex + 1;
4534 static const int kEntriesIndex = kDummyIndex + 1;
4536 static const int kEntrySize = 2; // key + value
4538 static const int kFactoryOffset = kHeaderSize;
4539 static const int kFingerOffset = kFactoryOffset + kPointerSize;
4540 static const int kCacheSizeOffset = kFingerOffset + kPointerSize;
4542 inline void MakeZeroSize();
4543 inline void Clear();
4546 inline void set_size(int size);
4547 inline int finger_index();
4548 inline void set_finger_index(int finger_index);
4550 DECLARE_CAST(JSFunctionResultCache)
4552 DECLARE_VERIFIER(JSFunctionResultCache)
4556 // ScopeInfo represents information about different scopes of a source
4557 // program and the allocation of the scope's variables. Scope information
4558 // is stored in a compressed form in ScopeInfo objects and is used
4559 // at runtime (stack dumps, deoptimization, etc.).
4561 // This object provides quick access to scope info details for runtime
4563 class ScopeInfo : public FixedArray {
4565 DECLARE_CAST(ScopeInfo)
4567 // Return the type of this scope.
4568 ScopeType scope_type();
4570 // Does this scope call eval?
4573 // Return the strict mode of this scope.
4574 StrictMode strict_mode();
4576 // Does this scope make a sloppy eval call?
4577 bool CallsSloppyEval() { return CallsEval() && strict_mode() == SLOPPY; }
4579 // Return the total number of locals allocated on the stack and in the
4580 // context. This includes the parameters that are allocated in the context.
4583 // Return the number of stack slots for code. This number consists of two
4585 // 1. One stack slot per stack allocated local.
4586 // 2. One stack slot for the function name if it is stack allocated.
4587 int StackSlotCount();
4589 // Return the number of context slots for code if a context is allocated. This
4590 // number consists of three parts:
4591 // 1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
4592 // 2. One context slot per context allocated local.
4593 // 3. One context slot for the function name if it is context allocated.
4594 // Parameters allocated in the context count as context allocated locals. If
4595 // no contexts are allocated for this scope ContextLength returns 0.
4596 int ContextLength();
4598 // Is this scope the scope of a named function expression?
4599 bool HasFunctionName();
4601 // Return if this has context allocated locals.
4602 bool HasHeapAllocatedLocals();
4604 // Return if contexts are allocated for this scope.
4607 // Return the function_name if present.
4608 String* FunctionName();
4610 // Return the name of the given parameter.
4611 String* ParameterName(int var);
4613 // Return the name of the given local.
4614 String* LocalName(int var);
4616 // Return the name of the given stack local.
4617 String* StackLocalName(int var);
4619 // Return the name of the given context local.
4620 String* ContextLocalName(int var);
4622 // Return the mode of the given context local.
4623 VariableMode ContextLocalMode(int var);
4625 // Return the initialization flag of the given context local.
4626 InitializationFlag ContextLocalInitFlag(int var);
4628 // Return the initialization flag of the given context local.
4629 MaybeAssignedFlag ContextLocalMaybeAssignedFlag(int var);
4631 // Return true if this local was introduced by the compiler, and should not be
4632 // exposed to the user in a debugger.
4633 bool LocalIsSynthetic(int var);
4635 // Lookup support for serialized scope info. Returns the
4636 // the stack slot index for a given slot name if the slot is
4637 // present; otherwise returns a value < 0. The name must be an internalized
4639 int StackSlotIndex(String* name);
4641 // Lookup support for serialized scope info. Returns the
4642 // context slot index for a given slot name if the slot is present; otherwise
4643 // returns a value < 0. The name must be an internalized string.
4644 // If the slot is present and mode != NULL, sets *mode to the corresponding
4645 // mode for that variable.
4646 static int ContextSlotIndex(Handle<ScopeInfo> scope_info, Handle<String> name,
4647 VariableMode* mode, InitializationFlag* init_flag,
4648 MaybeAssignedFlag* maybe_assigned_flag);
4650 // Lookup support for serialized scope info. Returns the
4651 // parameter index for a given parameter name if the parameter is present;
4652 // otherwise returns a value < 0. The name must be an internalized string.
4653 int ParameterIndex(String* name);
4655 // Lookup support for serialized scope info. Returns the function context
4656 // slot index if the function name is present and context-allocated (named
4657 // function expressions, only), otherwise returns a value < 0. The name
4658 // must be an internalized string.
4659 int FunctionContextSlotIndex(String* name, VariableMode* mode);
4662 // Copies all the context locals into an object used to materialize a scope.
4663 static bool CopyContextLocalsToScopeObject(Handle<ScopeInfo> scope_info,
4664 Handle<Context> context,
4665 Handle<JSObject> scope_object);
4668 static Handle<ScopeInfo> Create(Scope* scope, Zone* zone);
4670 // Serializes empty scope info.
4671 static ScopeInfo* Empty(Isolate* isolate);
4677 // The layout of the static part of a ScopeInfo is as follows. Each entry is
4678 // numeric and occupies one array slot.
4679 // 1. A set of properties of the scope
4680 // 2. The number of parameters. This only applies to function scopes. For
4681 // non-function scopes this is 0.
4682 // 3. The number of non-parameter variables allocated on the stack.
4683 // 4. The number of non-parameter and parameter variables allocated in the
4685 #define FOR_EACH_NUMERIC_FIELD(V) \
4688 V(StackLocalCount) \
4689 V(ContextLocalCount)
4691 #define FIELD_ACCESSORS(name) \
4692 void Set##name(int value) { \
4693 set(k##name, Smi::FromInt(value)); \
4696 if (length() > 0) { \
4697 return Smi::cast(get(k##name))->value(); \
4702 FOR_EACH_NUMERIC_FIELD(FIELD_ACCESSORS)
4703 #undef FIELD_ACCESSORS
4707 #define DECL_INDEX(name) k##name,
4708 FOR_EACH_NUMERIC_FIELD(DECL_INDEX)
4710 #undef FOR_EACH_NUMERIC_FIELD
4714 // The layout of the variable part of a ScopeInfo is as follows:
4715 // 1. ParameterEntries:
4716 // This part stores the names of the parameters for function scopes. One
4717 // slot is used per parameter, so in total this part occupies
4718 // ParameterCount() slots in the array. For other scopes than function
4719 // scopes ParameterCount() is 0.
4720 // 2. StackLocalEntries:
4721 // Contains the names of local variables that are allocated on the stack,
4722 // in increasing order of the stack slot index. One slot is used per stack
4723 // local, so in total this part occupies StackLocalCount() slots in the
4725 // 3. ContextLocalNameEntries:
4726 // Contains the names of local variables and parameters that are allocated
4727 // in the context. They are stored in increasing order of the context slot
4728 // index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
4729 // context local, so in total this part occupies ContextLocalCount() slots
4731 // 4. ContextLocalInfoEntries:
4732 // Contains the variable modes and initialization flags corresponding to
4733 // the context locals in ContextLocalNameEntries. One slot is used per
4734 // context local, so in total this part occupies ContextLocalCount()
4735 // slots in the array.
4736 // 5. FunctionNameEntryIndex:
4737 // If the scope belongs to a named function expression this part contains
4738 // information about the function variable. It always occupies two array
4739 // slots: a. The name of the function variable.
4740 // b. The context or stack slot index for the variable.
4741 int ParameterEntriesIndex();
4742 int StackLocalEntriesIndex();
4743 int ContextLocalNameEntriesIndex();
4744 int ContextLocalInfoEntriesIndex();
4745 int FunctionNameEntryIndex();
4747 // Location of the function variable for named function expressions.
4748 enum FunctionVariableInfo {
4749 NONE, // No function name present.
4755 // Properties of scopes.
4756 class ScopeTypeField: public BitField<ScopeType, 0, 3> {};
4757 class CallsEvalField: public BitField<bool, 3, 1> {};
4758 class StrictModeField: public BitField<StrictMode, 4, 1> {};
4759 class FunctionVariableField: public BitField<FunctionVariableInfo, 5, 2> {};
4760 class FunctionVariableMode: public BitField<VariableMode, 7, 3> {};
4762 // BitFields representing the encoded information for context locals in the
4763 // ContextLocalInfoEntries part.
4764 class ContextLocalMode: public BitField<VariableMode, 0, 3> {};
4765 class ContextLocalInitFlag: public BitField<InitializationFlag, 3, 1> {};
4766 class ContextLocalMaybeAssignedFlag
4767 : public BitField<MaybeAssignedFlag, 4, 1> {};
4771 // The cache for maps used by normalized (dictionary mode) objects.
4772 // Such maps do not have property descriptors, so a typical program
4773 // needs very limited number of distinct normalized maps.
4774 class NormalizedMapCache: public FixedArray {
4776 static Handle<NormalizedMapCache> New(Isolate* isolate);
4778 MUST_USE_RESULT MaybeHandle<Map> Get(Handle<Map> fast_map,
4779 PropertyNormalizationMode mode);
4780 void Set(Handle<Map> fast_map, Handle<Map> normalized_map);
4784 DECLARE_CAST(NormalizedMapCache)
4786 static inline bool IsNormalizedMapCache(const Object* obj);
4788 DECLARE_VERIFIER(NormalizedMapCache)
4790 static const int kEntries = 64;
4792 static inline int GetIndex(Handle<Map> map);
4794 // The following declarations hide base class methods.
4795 Object* get(int index);
4796 void set(int index, Object* value);
4800 // ByteArray represents fixed sized byte arrays. Used for the relocation info
4801 // that is attached to code objects.
4802 class ByteArray: public FixedArrayBase {
4804 inline int Size() { return RoundUp(length() + kHeaderSize, kPointerSize); }
4806 // Setter and getter.
4807 inline byte get(int index);
4808 inline void set(int index, byte value);
4810 // Treat contents as an int array.
4811 inline int get_int(int index);
4813 static int SizeFor(int length) {
4814 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4816 // We use byte arrays for free blocks in the heap. Given a desired size in
4817 // bytes that is a multiple of the word size and big enough to hold a byte
4818 // array, this function returns the number of elements a byte array should
4820 static int LengthFor(int size_in_bytes) {
4821 DCHECK(IsAligned(size_in_bytes, kPointerSize));
4822 DCHECK(size_in_bytes >= kHeaderSize);
4823 return size_in_bytes - kHeaderSize;
4826 // Returns data start address.
4827 inline Address GetDataStartAddress();
4829 // Returns a pointer to the ByteArray object for a given data start address.
4830 static inline ByteArray* FromDataStartAddress(Address address);
4832 DECLARE_CAST(ByteArray)
4834 // Dispatched behavior.
4835 inline int ByteArraySize() {
4836 return SizeFor(this->length());
4838 DECLARE_PRINTER(ByteArray)
4839 DECLARE_VERIFIER(ByteArray)
4841 // Layout description.
4842 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4844 // Maximal memory consumption for a single ByteArray.
4845 static const int kMaxSize = 512 * MB;
4846 // Maximal length of a single ByteArray.
4847 static const int kMaxLength = kMaxSize - kHeaderSize;
4850 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4854 // FreeSpace represents fixed sized areas of the heap that are not currently in
4855 // use. Used by the heap and GC.
4856 class FreeSpace: public HeapObject {
4858 // [size]: size of the free space including the header.
4859 inline int size() const;
4860 inline void set_size(int value);
4862 inline int nobarrier_size() const;
4863 inline void nobarrier_set_size(int value);
4865 inline int Size() { return size(); }
4867 DECLARE_CAST(FreeSpace)
4869 // Dispatched behavior.
4870 DECLARE_PRINTER(FreeSpace)
4871 DECLARE_VERIFIER(FreeSpace)
4873 // Layout description.
4874 // Size is smi tagged when it is stored.
4875 static const int kSizeOffset = HeapObject::kHeaderSize;
4876 static const int kHeaderSize = kSizeOffset + kPointerSize;
4878 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4881 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
4885 // V has parameters (Type, type, TYPE, C type, element_size)
4886 #define TYPED_ARRAYS(V) \
4887 V(Uint8, uint8, UINT8, uint8_t, 1) \
4888 V(Int8, int8, INT8, int8_t, 1) \
4889 V(Uint16, uint16, UINT16, uint16_t, 2) \
4890 V(Int16, int16, INT16, int16_t, 2) \
4891 V(Uint32, uint32, UINT32, uint32_t, 4) \
4892 V(Int32, int32, INT32, int32_t, 4) \
4893 V(Float32, float32, FLOAT32, float, 4) \
4894 V(Float64, float64, FLOAT64, double, 8) \
4895 V(Uint8Clamped, uint8_clamped, UINT8_CLAMPED, uint8_t, 1)
4899 // An ExternalArray represents a fixed-size array of primitive values
4900 // which live outside the JavaScript heap. Its subclasses are used to
4901 // implement the CanvasArray types being defined in the WebGL
4902 // specification. As of this writing the first public draft is not yet
4903 // available, but Khronos members can access the draft at:
4904 // https://cvs.khronos.org/svn/repos/3dweb/trunk/doc/spec/WebGL-spec.html
4906 // The semantics of these arrays differ from CanvasPixelArray.
4907 // Out-of-range values passed to the setter are converted via a C
4908 // cast, not clamping. Out-of-range indices cause exceptions to be
4909 // raised rather than being silently ignored.
4910 class ExternalArray: public FixedArrayBase {
4912 inline bool is_the_hole(int index) { return false; }
4914 // [external_pointer]: The pointer to the external memory area backing this
4916 DECL_ACCESSORS(external_pointer, void) // Pointer to the data store.
4918 DECLARE_CAST(ExternalArray)
4920 // Maximal acceptable length for an external array.
4921 static const int kMaxLength = 0x3fffffff;
4923 // ExternalArray headers are not quadword aligned.
4924 static const int kExternalPointerOffset =
4925 POINTER_SIZE_ALIGN(FixedArrayBase::kLengthOffset + kPointerSize);
4926 static const int kHeaderSize = kExternalPointerOffset + kPointerSize;
4927 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4930 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalArray);
4934 // A ExternalUint8ClampedArray represents a fixed-size byte array with special
4935 // semantics used for implementing the CanvasPixelArray object. Please see the
4936 // specification at:
4938 // http://www.whatwg.org/specs/web-apps/current-work/
4939 // multipage/the-canvas-element.html#canvaspixelarray
4940 // In particular, write access clamps the value written to 0 or 255 if the
4941 // value written is outside this range.
4942 class ExternalUint8ClampedArray: public ExternalArray {
4944 inline uint8_t* external_uint8_clamped_pointer();
4946 // Setter and getter.
4947 inline uint8_t get_scalar(int index);
4948 static inline Handle<Object> get(Handle<ExternalUint8ClampedArray> array,
4950 inline void set(int index, uint8_t value);
4952 // This accessor applies the correct conversion from Smi, HeapNumber
4953 // and undefined and clamps the converted value between 0 and 255.
4954 static Handle<Object> SetValue(Handle<ExternalUint8ClampedArray> array,
4956 Handle<Object> value);
4958 DECLARE_CAST(ExternalUint8ClampedArray)
4960 // Dispatched behavior.
4961 DECLARE_PRINTER(ExternalUint8ClampedArray)
4962 DECLARE_VERIFIER(ExternalUint8ClampedArray)
4965 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint8ClampedArray);
4969 class ExternalInt8Array: public ExternalArray {
4971 // Setter and getter.
4972 inline int8_t get_scalar(int index);
4973 static inline Handle<Object> get(Handle<ExternalInt8Array> array, int index);
4974 inline void set(int index, int8_t value);
4976 // This accessor applies the correct conversion from Smi, HeapNumber
4978 static Handle<Object> SetValue(Handle<ExternalInt8Array> array,
4980 Handle<Object> value);
4982 DECLARE_CAST(ExternalInt8Array)
4984 // Dispatched behavior.
4985 DECLARE_PRINTER(ExternalInt8Array)
4986 DECLARE_VERIFIER(ExternalInt8Array)
4989 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt8Array);
4993 class ExternalUint8Array: public ExternalArray {
4995 // Setter and getter.
4996 inline uint8_t get_scalar(int index);
4997 static inline Handle<Object> get(Handle<ExternalUint8Array> array, int index);
4998 inline void set(int index, uint8_t value);
5000 // This accessor applies the correct conversion from Smi, HeapNumber
5002 static Handle<Object> SetValue(Handle<ExternalUint8Array> array,
5004 Handle<Object> value);
5006 DECLARE_CAST(ExternalUint8Array)
5008 // Dispatched behavior.
5009 DECLARE_PRINTER(ExternalUint8Array)
5010 DECLARE_VERIFIER(ExternalUint8Array)
5013 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint8Array);
5017 class ExternalInt16Array: public ExternalArray {
5019 // Setter and getter.
5020 inline int16_t get_scalar(int index);
5021 static inline Handle<Object> get(Handle<ExternalInt16Array> array, int index);
5022 inline void set(int index, int16_t value);
5024 // This accessor applies the correct conversion from Smi, HeapNumber
5026 static Handle<Object> SetValue(Handle<ExternalInt16Array> array,
5028 Handle<Object> value);
5030 DECLARE_CAST(ExternalInt16Array)
5032 // Dispatched behavior.
5033 DECLARE_PRINTER(ExternalInt16Array)
5034 DECLARE_VERIFIER(ExternalInt16Array)
5037 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt16Array);
5041 class ExternalUint16Array: public ExternalArray {
5043 // Setter and getter.
5044 inline uint16_t get_scalar(int index);
5045 static inline Handle<Object> get(Handle<ExternalUint16Array> array,
5047 inline void set(int index, uint16_t value);
5049 // This accessor applies the correct conversion from Smi, HeapNumber
5051 static Handle<Object> SetValue(Handle<ExternalUint16Array> array,
5053 Handle<Object> value);
5055 DECLARE_CAST(ExternalUint16Array)
5057 // Dispatched behavior.
5058 DECLARE_PRINTER(ExternalUint16Array)
5059 DECLARE_VERIFIER(ExternalUint16Array)
5062 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint16Array);
5066 class ExternalInt32Array: public ExternalArray {
5068 // Setter and getter.
5069 inline int32_t get_scalar(int index);
5070 static inline Handle<Object> get(Handle<ExternalInt32Array> array, int index);
5071 inline void set(int index, int32_t value);
5073 // This accessor applies the correct conversion from Smi, HeapNumber
5075 static Handle<Object> SetValue(Handle<ExternalInt32Array> array,
5077 Handle<Object> value);
5079 DECLARE_CAST(ExternalInt32Array)
5081 // Dispatched behavior.
5082 DECLARE_PRINTER(ExternalInt32Array)
5083 DECLARE_VERIFIER(ExternalInt32Array)
5086 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt32Array);
5090 class ExternalUint32Array: public ExternalArray {
5092 // Setter and getter.
5093 inline uint32_t get_scalar(int index);
5094 static inline Handle<Object> get(Handle<ExternalUint32Array> array,
5096 inline void set(int index, uint32_t value);
5098 // This accessor applies the correct conversion from Smi, HeapNumber
5100 static Handle<Object> SetValue(Handle<ExternalUint32Array> array,
5102 Handle<Object> value);
5104 DECLARE_CAST(ExternalUint32Array)
5106 // Dispatched behavior.
5107 DECLARE_PRINTER(ExternalUint32Array)
5108 DECLARE_VERIFIER(ExternalUint32Array)
5111 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint32Array);
5115 class ExternalFloat32Array: public ExternalArray {
5117 // Setter and getter.
5118 inline float get_scalar(int index);
5119 static inline Handle<Object> get(Handle<ExternalFloat32Array> array,
5121 inline void set(int index, float value);
5123 // This accessor applies the correct conversion from Smi, HeapNumber
5125 static Handle<Object> SetValue(Handle<ExternalFloat32Array> array,
5127 Handle<Object> value);
5129 DECLARE_CAST(ExternalFloat32Array)
5131 // Dispatched behavior.
5132 DECLARE_PRINTER(ExternalFloat32Array)
5133 DECLARE_VERIFIER(ExternalFloat32Array)
5136 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalFloat32Array);
5140 class ExternalFloat64Array: public ExternalArray {
5142 // Setter and getter.
5143 inline double get_scalar(int index);
5144 static inline Handle<Object> get(Handle<ExternalFloat64Array> array,
5146 inline void set(int index, double value);
5148 // This accessor applies the correct conversion from Smi, HeapNumber
5150 static Handle<Object> SetValue(Handle<ExternalFloat64Array> array,
5152 Handle<Object> value);
5154 DECLARE_CAST(ExternalFloat64Array)
5156 // Dispatched behavior.
5157 DECLARE_PRINTER(ExternalFloat64Array)
5158 DECLARE_VERIFIER(ExternalFloat64Array)
5161 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalFloat64Array);
5165 class FixedTypedArrayBase: public FixedArrayBase {
5167 DECLARE_CAST(FixedTypedArrayBase)
5169 static const int kDataOffset = kHeaderSize;
5173 inline int TypedArraySize(InstanceType type);
5175 // Use with care: returns raw pointer into heap.
5176 inline void* DataPtr();
5178 inline int DataSize();
5181 inline int DataSize(InstanceType type);
5183 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
5187 template <class Traits>
5188 class FixedTypedArray: public FixedTypedArrayBase {
5190 typedef typename Traits::ElementType ElementType;
5191 static const InstanceType kInstanceType = Traits::kInstanceType;
5193 DECLARE_CAST(FixedTypedArray<Traits>)
5195 static inline int ElementOffset(int index) {
5196 return kDataOffset + index * sizeof(ElementType);
5199 static inline int SizeFor(int length) {
5200 return ElementOffset(length);
5203 inline ElementType get_scalar(int index);
5204 static inline Handle<Object> get(Handle<FixedTypedArray> array, int index);
5205 inline void set(int index, ElementType value);
5207 static inline ElementType from_int(int value);
5208 static inline ElementType from_double(double value);
5210 // This accessor applies the correct conversion from Smi, HeapNumber
5212 static Handle<Object> SetValue(Handle<FixedTypedArray<Traits> > array,
5214 Handle<Object> value);
5216 DECLARE_PRINTER(FixedTypedArray)
5217 DECLARE_VERIFIER(FixedTypedArray)
5220 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
5223 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size) \
5224 class Type##ArrayTraits { \
5225 public: /* NOLINT */ \
5226 typedef elementType ElementType; \
5227 static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE; \
5228 static const char* Designator() { return #type " array"; } \
5229 static inline Handle<Object> ToHandle(Isolate* isolate, \
5230 elementType scalar); \
5231 static inline elementType defaultValue(); \
5234 typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
5236 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
5238 #undef FIXED_TYPED_ARRAY_TRAITS
5240 // DeoptimizationInputData is a fixed array used to hold the deoptimization
5241 // data for code generated by the Hydrogen/Lithium compiler. It also
5242 // contains information about functions that were inlined. If N different
5243 // functions were inlined then first N elements of the literal array will
5244 // contain these functions.
5247 class DeoptimizationInputData: public FixedArray {
5249 // Layout description. Indices in the array.
5250 static const int kDeoptEntryCountIndex = 0;
5251 static const int kReturnAddressPatchEntryCountIndex = 1;
5252 static const int kTranslationByteArrayIndex = 2;
5253 static const int kInlinedFunctionCountIndex = 3;
5254 static const int kLiteralArrayIndex = 4;
5255 static const int kOsrAstIdIndex = 5;
5256 static const int kOsrPcOffsetIndex = 6;
5257 static const int kOptimizationIdIndex = 7;
5258 static const int kSharedFunctionInfoIndex = 8;
5259 static const int kFirstDeoptEntryIndex = 9;
5261 // Offsets of deopt entry elements relative to the start of the entry.
5262 static const int kAstIdRawOffset = 0;
5263 static const int kTranslationIndexOffset = 1;
5264 static const int kArgumentsStackHeightOffset = 2;
5265 static const int kPcOffset = 3;
5266 static const int kDeoptEntrySize = 4;
5268 // Offsets of return address patch entry elements relative to the start of the
5270 static const int kReturnAddressPcOffset = 0;
5271 static const int kPatchedAddressPcOffset = 1;
5272 static const int kReturnAddressPatchEntrySize = 2;
5274 // Simple element accessors.
5275 #define DEFINE_ELEMENT_ACCESSORS(name, type) \
5277 return type::cast(get(k##name##Index)); \
5279 void Set##name(type* value) { \
5280 set(k##name##Index, value); \
5283 DEFINE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
5284 DEFINE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
5285 DEFINE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
5286 DEFINE_ELEMENT_ACCESSORS(OsrAstId, Smi)
5287 DEFINE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
5288 DEFINE_ELEMENT_ACCESSORS(OptimizationId, Smi)
5289 DEFINE_ELEMENT_ACCESSORS(SharedFunctionInfo, Object)
5291 #undef DEFINE_ELEMENT_ACCESSORS
5293 // Accessors for elements of the ith deoptimization entry.
5294 #define DEFINE_DEOPT_ENTRY_ACCESSORS(name, type) \
5295 type* name(int i) { \
5296 return type::cast(get(IndexForEntry(i) + k##name##Offset)); \
5298 void Set##name(int i, type* value) { \
5299 set(IndexForEntry(i) + k##name##Offset, value); \
5302 DEFINE_DEOPT_ENTRY_ACCESSORS(AstIdRaw, Smi)
5303 DEFINE_DEOPT_ENTRY_ACCESSORS(TranslationIndex, Smi)
5304 DEFINE_DEOPT_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
5305 DEFINE_DEOPT_ENTRY_ACCESSORS(Pc, Smi)
5307 #undef DEFINE_DEOPT_ENTRY_ACCESSORS
5309 // Accessors for elements of the ith deoptimization entry.
5310 #define DEFINE_PATCH_ENTRY_ACCESSORS(name, type) \
5311 type* name(int i) { \
5312 return type::cast( \
5313 get(IndexForReturnAddressPatchEntry(i) + k##name##Offset)); \
5315 void Set##name(int i, type* value) { \
5316 set(IndexForReturnAddressPatchEntry(i) + k##name##Offset, value); \
5319 DEFINE_PATCH_ENTRY_ACCESSORS(ReturnAddressPc, Smi)
5320 DEFINE_PATCH_ENTRY_ACCESSORS(PatchedAddressPc, Smi)
5322 #undef DEFINE_PATCH_ENTRY_ACCESSORS
5324 BailoutId AstId(int i) {
5325 return BailoutId(AstIdRaw(i)->value());
5328 void SetAstId(int i, BailoutId value) {
5329 SetAstIdRaw(i, Smi::FromInt(value.ToInt()));
5333 return length() == 0 ? 0 : Smi::cast(get(kDeoptEntryCountIndex))->value();
5336 int ReturnAddressPatchCount() {
5337 return length() == 0
5339 : Smi::cast(get(kReturnAddressPatchEntryCountIndex))->value();
5342 // Allocates a DeoptimizationInputData.
5343 static Handle<DeoptimizationInputData> New(Isolate* isolate,
5344 int deopt_entry_count,
5345 int return_address_patch_count,
5346 PretenureFlag pretenure);
5348 DECLARE_CAST(DeoptimizationInputData)
5350 #ifdef ENABLE_DISASSEMBLER
5351 void DeoptimizationInputDataPrint(OStream& os); // NOLINT
5355 friend class Object; // For accessing LengthFor.
5357 static int IndexForEntry(int i) {
5358 return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
5361 int IndexForReturnAddressPatchEntry(int i) {
5362 return kFirstDeoptEntryIndex + (DeoptCount() * kDeoptEntrySize) +
5363 (i * kReturnAddressPatchEntrySize);
5366 static int LengthFor(int deopt_count, int return_address_patch_count) {
5367 return kFirstDeoptEntryIndex + (deopt_count * kDeoptEntrySize) +
5368 (return_address_patch_count * kReturnAddressPatchEntrySize);
5373 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
5374 // data for code generated by the full compiler.
5375 // The format of the these objects is
5376 // [i * 2]: Ast ID for ith deoptimization.
5377 // [i * 2 + 1]: PC and state of ith deoptimization
5378 class DeoptimizationOutputData: public FixedArray {
5380 int DeoptPoints() { return length() / 2; }
5382 BailoutId AstId(int index) {
5383 return BailoutId(Smi::cast(get(index * 2))->value());
5386 void SetAstId(int index, BailoutId id) {
5387 set(index * 2, Smi::FromInt(id.ToInt()));
5390 Smi* PcAndState(int index) { return Smi::cast(get(1 + index * 2)); }
5391 void SetPcAndState(int index, Smi* offset) { set(1 + index * 2, offset); }
5393 static int LengthOfFixedArray(int deopt_points) {
5394 return deopt_points * 2;
5397 // Allocates a DeoptimizationOutputData.
5398 static Handle<DeoptimizationOutputData> New(Isolate* isolate,
5399 int number_of_deopt_points,
5400 PretenureFlag pretenure);
5402 DECLARE_CAST(DeoptimizationOutputData)
5404 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
5405 void DeoptimizationOutputDataPrint(OStream& os); // NOLINT
5410 // Forward declaration.
5413 class SafepointEntry;
5414 class TypeFeedbackInfo;
5416 // Code describes objects with on-the-fly generated machine code.
5417 class Code: public HeapObject {
5419 // Opaque data type for encapsulating code flags like kind, inline
5420 // cache state, and arguments count.
5421 typedef uint32_t Flags;
5423 #define NON_IC_KIND_LIST(V) \
5425 V(OPTIMIZED_FUNCTION) \
5431 #define IC_KIND_LIST(V) \
5442 #define CODE_KIND_LIST(V) \
5443 NON_IC_KIND_LIST(V) \
5447 #define DEFINE_CODE_KIND_ENUM(name) name,
5448 CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
5449 #undef DEFINE_CODE_KIND_ENUM
5453 // No more than 16 kinds. The value is currently encoded in four bits in
5455 STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
5457 static const char* Kind2String(Kind kind);
5465 static const int kPrologueOffsetNotSet = -1;
5467 #ifdef ENABLE_DISASSEMBLER
5469 static const char* ICState2String(InlineCacheState state);
5470 static const char* StubType2String(StubType type);
5471 static void PrintExtraICState(OStream& os, // NOLINT
5472 Kind kind, ExtraICState extra);
5473 void Disassemble(const char* name, OStream& os); // NOLINT
5474 #endif // ENABLE_DISASSEMBLER
5476 // [instruction_size]: Size of the native instructions
5477 inline int instruction_size() const;
5478 inline void set_instruction_size(int value);
5480 // [relocation_info]: Code relocation information
5481 DECL_ACCESSORS(relocation_info, ByteArray)
5482 void InvalidateRelocation();
5483 void InvalidateEmbeddedObjects();
5485 // [handler_table]: Fixed array containing offsets of exception handlers.
5486 DECL_ACCESSORS(handler_table, FixedArray)
5488 // [deoptimization_data]: Array containing data for deopt.
5489 DECL_ACCESSORS(deoptimization_data, FixedArray)
5491 // [raw_type_feedback_info]: This field stores various things, depending on
5492 // the kind of the code object.
5493 // FUNCTION => type feedback information.
5494 // STUB and ICs => major/minor key as Smi.
5495 DECL_ACCESSORS(raw_type_feedback_info, Object)
5496 inline Object* type_feedback_info();
5497 inline void set_type_feedback_info(
5498 Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5499 inline uint32_t stub_key();
5500 inline void set_stub_key(uint32_t key);
5502 // [next_code_link]: Link for lists of optimized or deoptimized code.
5503 // Note that storage for this field is overlapped with typefeedback_info.
5504 DECL_ACCESSORS(next_code_link, Object)
5506 // [gc_metadata]: Field used to hold GC related metadata. The contents of this
5507 // field does not have to be traced during garbage collection since
5508 // it is only used by the garbage collector itself.
5509 DECL_ACCESSORS(gc_metadata, Object)
5511 // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
5512 // at the moment when this object was created.
5513 inline void set_ic_age(int count);
5514 inline int ic_age() const;
5516 // [prologue_offset]: Offset of the function prologue, used for aging
5517 // FUNCTIONs and OPTIMIZED_FUNCTIONs.
5518 inline int prologue_offset() const;
5519 inline void set_prologue_offset(int offset);
5521 // Unchecked accessors to be used during GC.
5522 inline ByteArray* unchecked_relocation_info();
5524 inline int relocation_size();
5526 // [flags]: Various code flags.
5527 inline Flags flags();
5528 inline void set_flags(Flags flags);
5530 // [flags]: Access to specific code flags.
5532 inline InlineCacheState ic_state(); // Only valid for IC stubs.
5533 inline ExtraICState extra_ic_state(); // Only valid for IC stubs.
5535 inline StubType type(); // Only valid for monomorphic IC stubs.
5537 // Testers for IC stub kinds.
5538 inline bool is_inline_cache_stub();
5539 inline bool is_debug_stub();
5540 inline bool is_handler() { return kind() == HANDLER; }
5541 inline bool is_load_stub() { return kind() == LOAD_IC; }
5542 inline bool is_keyed_load_stub() { return kind() == KEYED_LOAD_IC; }
5543 inline bool is_store_stub() { return kind() == STORE_IC; }
5544 inline bool is_keyed_store_stub() { return kind() == KEYED_STORE_IC; }
5545 inline bool is_call_stub() { return kind() == CALL_IC; }
5546 inline bool is_binary_op_stub() { return kind() == BINARY_OP_IC; }
5547 inline bool is_compare_ic_stub() { return kind() == COMPARE_IC; }
5548 inline bool is_compare_nil_ic_stub() { return kind() == COMPARE_NIL_IC; }
5549 inline bool is_to_boolean_ic_stub() { return kind() == TO_BOOLEAN_IC; }
5550 inline bool is_keyed_stub();
5551 inline bool is_optimized_code() { return kind() == OPTIMIZED_FUNCTION; }
5552 inline bool is_weak_stub();
5553 inline void mark_as_weak_stub();
5554 inline bool is_invalidated_weak_stub();
5555 inline void mark_as_invalidated_weak_stub();
5557 inline bool CanBeWeakStub() {
5559 return (k == LOAD_IC || k == STORE_IC || k == KEYED_LOAD_IC ||
5560 k == KEYED_STORE_IC || k == COMPARE_NIL_IC) &&
5561 ic_state() == MONOMORPHIC;
5564 inline bool IsCodeStubOrIC();
5566 inline void set_raw_kind_specific_flags1(int value);
5567 inline void set_raw_kind_specific_flags2(int value);
5569 // [is_crankshafted]: For kind STUB or ICs, tells whether or not a code
5570 // object was generated by either the hydrogen or the TurboFan optimizing
5571 // compiler (but it may not be an optimized function).
5572 inline bool is_crankshafted();
5573 inline bool is_hydrogen_stub(); // Crankshafted, but not a function.
5574 inline void set_is_crankshafted(bool value);
5576 // [is_turbofanned]: For kind STUB or OPTIMIZED_FUNCTION, tells whether the
5577 // code object was generated by the TurboFan optimizing compiler.
5578 inline bool is_turbofanned();
5579 inline void set_is_turbofanned(bool value);
5581 // [optimizable]: For FUNCTION kind, tells if it is optimizable.
5582 inline bool optimizable();
5583 inline void set_optimizable(bool value);
5585 // [has_deoptimization_support]: For FUNCTION kind, tells if it has
5586 // deoptimization support.
5587 inline bool has_deoptimization_support();
5588 inline void set_has_deoptimization_support(bool value);
5590 // [has_debug_break_slots]: For FUNCTION kind, tells if it has
5591 // been compiled with debug break slots.
5592 inline bool has_debug_break_slots();
5593 inline void set_has_debug_break_slots(bool value);
5595 // [compiled_with_optimizing]: For FUNCTION kind, tells if it has
5596 // been compiled with IsOptimizing set to true.
5597 inline bool is_compiled_optimizable();
5598 inline void set_compiled_optimizable(bool value);
5600 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
5601 // how long the function has been marked for OSR and therefore which
5602 // level of loop nesting we are willing to do on-stack replacement
5604 inline void set_allow_osr_at_loop_nesting_level(int level);
5605 inline int allow_osr_at_loop_nesting_level();
5607 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
5608 // the code object was seen on the stack with no IC patching going on.
5609 inline int profiler_ticks();
5610 inline void set_profiler_ticks(int ticks);
5612 // [builtin_index]: For BUILTIN kind, tells which builtin index it has.
5613 inline int builtin_index();
5614 inline void set_builtin_index(int id);
5616 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
5617 // reserved in the code prologue.
5618 inline unsigned stack_slots();
5619 inline void set_stack_slots(unsigned slots);
5621 // [safepoint_table_start]: For kind OPTIMIZED_FUNCTION, the offset in
5622 // the instruction stream where the safepoint table starts.
5623 inline unsigned safepoint_table_offset();
5624 inline void set_safepoint_table_offset(unsigned offset);
5626 // [back_edge_table_start]: For kind FUNCTION, the offset in the
5627 // instruction stream where the back edge table starts.
5628 inline unsigned back_edge_table_offset();
5629 inline void set_back_edge_table_offset(unsigned offset);
5631 inline bool back_edges_patched_for_osr();
5633 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
5634 inline byte to_boolean_state();
5636 // [has_function_cache]: For kind STUB tells whether there is a function
5637 // cache is passed to the stub.
5638 inline bool has_function_cache();
5639 inline void set_has_function_cache(bool flag);
5642 // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
5643 // the code is going to be deoptimized because of dead embedded maps.
5644 inline bool marked_for_deoptimization();
5645 inline void set_marked_for_deoptimization(bool flag);
5647 // [constant_pool]: The constant pool for this function.
5648 inline ConstantPoolArray* constant_pool();
5649 inline void set_constant_pool(Object* constant_pool);
5651 // Get the safepoint entry for the given pc.
5652 SafepointEntry GetSafepointEntry(Address pc);
5654 // Find an object in a stub with a specified map
5655 Object* FindNthObject(int n, Map* match_map);
5657 // Find the first allocation site in an IC stub.
5658 AllocationSite* FindFirstAllocationSite();
5660 // Find the first map in an IC stub.
5661 Map* FindFirstMap();
5662 void FindAllMaps(MapHandleList* maps);
5664 // Find the first handler in an IC stub.
5665 Code* FindFirstHandler();
5667 // Find |length| handlers and put them into |code_list|. Returns false if not
5668 // enough handlers can be found.
5669 bool FindHandlers(CodeHandleList* code_list, int length = -1);
5671 // Find the handler for |map|.
5672 MaybeHandle<Code> FindHandlerForMap(Map* map);
5674 // Find the first name in an IC stub.
5675 Name* FindFirstName();
5677 class FindAndReplacePattern;
5678 // For each (map-to-find, object-to-replace) pair in the pattern, this
5679 // function replaces the corresponding placeholder in the code with the
5680 // object-to-replace. The function assumes that pairs in the pattern come in
5681 // the same order as the placeholders in the code.
5682 void FindAndReplace(const FindAndReplacePattern& pattern);
5684 // The entire code object including its header is copied verbatim to the
5685 // snapshot so that it can be written in one, fast, memcpy during
5686 // deserialization. The deserializer will overwrite some pointers, rather
5687 // like a runtime linker, but the random allocation addresses used in the
5688 // mksnapshot process would still be present in the unlinked snapshot data,
5689 // which would make snapshot production non-reproducible. This method wipes
5690 // out the to-be-overwritten header data for reproducible snapshots.
5691 inline void WipeOutHeader();
5693 // Flags operations.
5694 static inline Flags ComputeFlags(
5695 Kind kind, InlineCacheState ic_state = UNINITIALIZED,
5696 ExtraICState extra_ic_state = kNoExtraICState, StubType type = NORMAL,
5697 CacheHolderFlag holder = kCacheOnReceiver);
5699 static inline Flags ComputeMonomorphicFlags(
5700 Kind kind, ExtraICState extra_ic_state = kNoExtraICState,
5701 CacheHolderFlag holder = kCacheOnReceiver, StubType type = NORMAL);
5703 static inline Flags ComputeHandlerFlags(
5704 Kind handler_kind, StubType type = NORMAL,
5705 CacheHolderFlag holder = kCacheOnReceiver);
5707 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
5708 static inline StubType ExtractTypeFromFlags(Flags flags);
5709 static inline CacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
5710 static inline Kind ExtractKindFromFlags(Flags flags);
5711 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
5713 static inline Flags RemoveTypeFromFlags(Flags flags);
5714 static inline Flags RemoveTypeAndHolderFromFlags(Flags flags);
5716 // Convert a target address into a code object.
5717 static inline Code* GetCodeFromTargetAddress(Address address);
5719 // Convert an entry address into an object.
5720 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
5722 // Returns the address of the first instruction.
5723 inline byte* instruction_start();
5725 // Returns the address right after the last instruction.
5726 inline byte* instruction_end();
5728 // Returns the size of the instructions, padding, and relocation information.
5729 inline int body_size();
5731 // Returns the address of the first relocation info (read backwards!).
5732 inline byte* relocation_start();
5734 // Code entry point.
5735 inline byte* entry();
5737 // Returns true if pc is inside this object's instructions.
5738 inline bool contains(byte* pc);
5740 // Relocate the code by delta bytes. Called to signal that this code
5741 // object has been moved by delta bytes.
5742 void Relocate(intptr_t delta);
5744 // Migrate code described by desc.
5745 void CopyFrom(const CodeDesc& desc);
5747 // Returns the object size for a given body (used for allocation).
5748 static int SizeFor(int body_size) {
5749 DCHECK_SIZE_TAG_ALIGNED(body_size);
5750 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
5753 // Calculate the size of the code object to report for log events. This takes
5754 // the layout of the code object into account.
5755 int ExecutableSize() {
5756 // Check that the assumptions about the layout of the code object holds.
5757 DCHECK_EQ(static_cast<int>(instruction_start() - address()),
5759 return instruction_size() + Code::kHeaderSize;
5762 // Locating source position.
5763 int SourcePosition(Address pc);
5764 int SourceStatementPosition(Address pc);
5768 // Dispatched behavior.
5769 int CodeSize() { return SizeFor(body_size()); }
5770 inline void CodeIterateBody(ObjectVisitor* v);
5772 template<typename StaticVisitor>
5773 inline void CodeIterateBody(Heap* heap);
5775 DECLARE_PRINTER(Code)
5776 DECLARE_VERIFIER(Code)
5778 void ClearInlineCaches();
5779 void ClearInlineCaches(Kind kind);
5781 BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
5782 uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
5784 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
5786 kNotExecutedCodeAge = -2,
5787 kExecutedOnceCodeAge = -1,
5789 CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
5791 kFirstCodeAge = kNotExecutedCodeAge,
5792 kLastCodeAge = kAfterLastCodeAge - 1,
5793 kCodeAgeCount = kAfterLastCodeAge - kNotExecutedCodeAge - 1,
5794 kIsOldCodeAge = kSexagenarianCodeAge,
5795 kPreAgedCodeAge = kIsOldCodeAge - 1
5797 #undef DECLARE_CODE_AGE_ENUM
5799 // Code aging. Indicates how many full GCs this code has survived without
5800 // being entered through the prologue. Used to determine when it is
5801 // relatively safe to flush this code object and replace it with the lazy
5802 // compilation stub.
5803 static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
5804 static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
5805 void MakeOlder(MarkingParity);
5806 static bool IsYoungSequence(Isolate* isolate, byte* sequence);
5809 // Gets the raw code age, including psuedo code-age values such as
5810 // kNotExecutedCodeAge and kExecutedOnceCodeAge.
5812 static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
5813 return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
5816 void PrintDeoptLocation(FILE* out, int bailout_id);
5817 bool CanDeoptAt(Address pc);
5820 void VerifyEmbeddedObjectsDependency();
5823 inline bool CanContainWeakObjects() {
5824 return is_optimized_code() || is_weak_stub();
5827 inline bool IsWeakObject(Object* object) {
5828 return (is_optimized_code() && !is_turbofanned() &&
5829 IsWeakObjectInOptimizedCode(object)) ||
5830 (is_weak_stub() && IsWeakObjectInIC(object));
5833 static inline bool IsWeakObjectInOptimizedCode(Object* object);
5834 static inline bool IsWeakObjectInIC(Object* object);
5836 // Max loop nesting marker used to postpose OSR. We don't take loop
5837 // nesting that is deeper than 5 levels into account.
5838 static const int kMaxLoopNestingMarker = 6;
5840 // Layout description.
5841 static const int kInstructionSizeOffset = HeapObject::kHeaderSize;
5842 static const int kRelocationInfoOffset = kInstructionSizeOffset + kIntSize;
5843 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
5844 static const int kDeoptimizationDataOffset =
5845 kHandlerTableOffset + kPointerSize;
5846 // For FUNCTION kind, we store the type feedback info here.
5847 static const int kTypeFeedbackInfoOffset =
5848 kDeoptimizationDataOffset + kPointerSize;
5849 static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
5850 static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
5851 static const int kICAgeOffset =
5852 kGCMetadataOffset + kPointerSize;
5853 static const int kFlagsOffset = kICAgeOffset + kIntSize;
5854 static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
5855 static const int kKindSpecificFlags2Offset =
5856 kKindSpecificFlags1Offset + kIntSize;
5857 // Note: We might be able to squeeze this into the flags above.
5858 static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
5859 static const int kConstantPoolOffset = kPrologueOffset + kPointerSize;
5861 static const int kHeaderPaddingStart = kConstantPoolOffset + kIntSize;
5863 // Add padding to align the instruction start following right after
5864 // the Code object header.
5865 static const int kHeaderSize =
5866 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
5868 // Byte offsets within kKindSpecificFlags1Offset.
5869 static const int kOptimizableOffset = kKindSpecificFlags1Offset;
5871 static const int kFullCodeFlags = kOptimizableOffset + 1;
5872 class FullCodeFlagsHasDeoptimizationSupportField:
5873 public BitField<bool, 0, 1> {}; // NOLINT
5874 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
5875 class FullCodeFlagsIsCompiledOptimizable: public BitField<bool, 2, 1> {};
5877 static const int kProfilerTicksOffset = kFullCodeFlags + 1;
5879 // Flags layout. BitField<type, shift, size>.
5880 class ICStateField : public BitField<InlineCacheState, 0, 4> {};
5881 class TypeField : public BitField<StubType, 4, 1> {};
5882 class CacheHolderField : public BitField<CacheHolderFlag, 5, 2> {};
5883 class KindField : public BitField<Kind, 7, 4> {};
5884 class ExtraICStateField: public BitField<ExtraICState, 11,
5885 PlatformSmiTagging::kSmiValueSize - 11 + 1> {}; // NOLINT
5887 // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
5888 static const int kStackSlotsFirstBit = 0;
5889 static const int kStackSlotsBitCount = 24;
5890 static const int kHasFunctionCacheBit =
5891 kStackSlotsFirstBit + kStackSlotsBitCount;
5892 static const int kMarkedForDeoptimizationBit = kHasFunctionCacheBit + 1;
5893 static const int kWeakStubBit = kMarkedForDeoptimizationBit + 1;
5894 static const int kInvalidatedWeakStubBit = kWeakStubBit + 1;
5895 static const int kIsTurbofannedBit = kInvalidatedWeakStubBit + 1;
5897 STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
5898 STATIC_ASSERT(kIsTurbofannedBit + 1 <= 32);
5900 class StackSlotsField: public BitField<int,
5901 kStackSlotsFirstBit, kStackSlotsBitCount> {}; // NOLINT
5902 class HasFunctionCacheField : public BitField<bool, kHasFunctionCacheBit, 1> {
5904 class MarkedForDeoptimizationField
5905 : public BitField<bool, kMarkedForDeoptimizationBit, 1> {}; // NOLINT
5906 class WeakStubField : public BitField<bool, kWeakStubBit, 1> {}; // NOLINT
5907 class InvalidatedWeakStubField
5908 : public BitField<bool, kInvalidatedWeakStubBit, 1> {}; // NOLINT
5909 class IsTurbofannedField : public BitField<bool, kIsTurbofannedBit, 1> {
5912 // KindSpecificFlags2 layout (ALL)
5913 static const int kIsCrankshaftedBit = 0;
5914 class IsCrankshaftedField: public BitField<bool,
5915 kIsCrankshaftedBit, 1> {}; // NOLINT
5917 // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
5918 static const int kSafepointTableOffsetFirstBit = kIsCrankshaftedBit + 1;
5919 static const int kSafepointTableOffsetBitCount = 24;
5921 STATIC_ASSERT(kSafepointTableOffsetFirstBit +
5922 kSafepointTableOffsetBitCount <= 32);
5923 STATIC_ASSERT(1 + kSafepointTableOffsetBitCount <= 32);
5925 class SafepointTableOffsetField: public BitField<int,
5926 kSafepointTableOffsetFirstBit,
5927 kSafepointTableOffsetBitCount> {}; // NOLINT
5929 // KindSpecificFlags2 layout (FUNCTION)
5930 class BackEdgeTableOffsetField: public BitField<int,
5931 kIsCrankshaftedBit + 1, 27> {}; // NOLINT
5932 class AllowOSRAtLoopNestingLevelField: public BitField<int,
5933 kIsCrankshaftedBit + 1 + 27, 4> {}; // NOLINT
5934 STATIC_ASSERT(AllowOSRAtLoopNestingLevelField::kMax >= kMaxLoopNestingMarker);
5936 static const int kArgumentsBits = 16;
5937 static const int kMaxArguments = (1 << kArgumentsBits) - 1;
5939 // This constant should be encodable in an ARM instruction.
5940 static const int kFlagsNotUsedInLookup =
5941 TypeField::kMask | CacheHolderField::kMask;
5944 friend class RelocIterator;
5945 friend class Deoptimizer; // For FindCodeAgeSequence.
5947 void ClearInlineCaches(Kind* kind);
5950 byte* FindCodeAgeSequence();
5951 static void GetCodeAgeAndParity(Code* code, Age* age,
5952 MarkingParity* parity);
5953 static void GetCodeAgeAndParity(Isolate* isolate, byte* sequence, Age* age,
5954 MarkingParity* parity);
5955 static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
5957 // Code aging -- platform-specific
5958 static void PatchPlatformCodeAge(Isolate* isolate,
5959 byte* sequence, Age age,
5960 MarkingParity parity);
5962 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5966 class CompilationInfo;
5968 // This class describes the layout of dependent codes array of a map. The
5969 // array is partitioned into several groups of dependent codes. Each group
5970 // contains codes with the same dependency on the map. The array has the
5971 // following layout for n dependency groups:
5973 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5974 // | C1 | C2 | ... | Cn | group 1 | group 2 | ... | group n | undefined |
5975 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5977 // The first n elements are Smis, each of them specifies the number of codes
5978 // in the corresponding group. The subsequent elements contain grouped code
5979 // objects. The suffix of the array can be filled with the undefined value if
5980 // the number of codes is less than the length of the array. The order of the
5981 // code objects within a group is not preserved.
5983 // All code indexes used in the class are counted starting from the first
5984 // code object of the first group. In other words, code index 0 corresponds
5985 // to array index n = kCodesStartIndex.
5987 class DependentCode: public FixedArray {
5989 enum DependencyGroup {
5990 // Group of IC stubs that weakly embed this map and depend on being
5991 // invalidated when the map is garbage collected. Dependent IC stubs form
5992 // a linked list. This group stores only the head of the list. This means
5993 // that the number_of_entries(kWeakICGroup) is 0 or 1.
5995 // Group of code that weakly embed this map and depend on being
5996 // deoptimized when the map is garbage collected.
5998 // Group of code that embed a transition to this map, and depend on being
5999 // deoptimized when the transition is replaced by a new version.
6001 // Group of code that omit run-time prototype checks for prototypes
6002 // described by this map. The group is deoptimized whenever an object
6003 // described by this map changes shape (and transitions to a new map),
6004 // possibly invalidating the assumptions embedded in the code.
6005 kPrototypeCheckGroup,
6006 // Group of code that depends on elements not being added to objects with
6008 kElementsCantBeAddedGroup,
6009 // Group of code that depends on global property values in property cells
6010 // not being changed.
6011 kPropertyCellChangedGroup,
6012 // Group of code that omit run-time type checks for the field(s) introduced
6015 // Group of code that omit run-time type checks for initial maps of
6017 kInitialMapChangedGroup,
6018 // Group of code that depends on tenuring information in AllocationSites
6019 // not being changed.
6020 kAllocationSiteTenuringChangedGroup,
6021 // Group of code that depends on element transition information in
6022 // AllocationSites not being changed.
6023 kAllocationSiteTransitionChangedGroup,
6024 kGroupCount = kAllocationSiteTransitionChangedGroup + 1
6027 // Array for holding the index of the first code object of each group.
6028 // The last element stores the total number of code objects.
6029 class GroupStartIndexes {
6031 explicit GroupStartIndexes(DependentCode* entries);
6032 void Recompute(DependentCode* entries);
6033 int at(int i) { return start_indexes_[i]; }
6034 int number_of_entries() { return start_indexes_[kGroupCount]; }
6036 int start_indexes_[kGroupCount + 1];
6039 bool Contains(DependencyGroup group, Code* code);
6040 static Handle<DependentCode> Insert(Handle<DependentCode> entries,
6041 DependencyGroup group,
6042 Handle<Object> object);
6043 void UpdateToFinishedCode(DependencyGroup group,
6044 CompilationInfo* info,
6046 void RemoveCompilationInfo(DependentCode::DependencyGroup group,
6047 CompilationInfo* info);
6049 void DeoptimizeDependentCodeGroup(Isolate* isolate,
6050 DependentCode::DependencyGroup group);
6052 bool MarkCodeForDeoptimization(Isolate* isolate,
6053 DependentCode::DependencyGroup group);
6054 void AddToDependentICList(Handle<Code> stub);
6056 // The following low-level accessors should only be used by this class
6057 // and the mark compact collector.
6058 inline int number_of_entries(DependencyGroup group);
6059 inline void set_number_of_entries(DependencyGroup group, int value);
6060 inline bool is_code_at(int i);
6061 inline Code* code_at(int i);
6062 inline CompilationInfo* compilation_info_at(int i);
6063 inline void set_object_at(int i, Object* object);
6064 inline Object** slot_at(int i);
6065 inline Object* object_at(int i);
6066 inline void clear_at(int i);
6067 inline void copy(int from, int to);
6068 DECLARE_CAST(DependentCode)
6070 static DependentCode* ForObject(Handle<HeapObject> object,
6071 DependencyGroup group);
6074 // Make a room at the end of the given group by moving out the first
6075 // code objects of the subsequent groups.
6076 inline void ExtendGroup(DependencyGroup group);
6077 static const int kCodesStartIndex = kGroupCount;
6081 // All heap objects have a Map that describes their structure.
6082 // A Map contains information about:
6083 // - Size information about the object
6084 // - How to iterate over an object (for garbage collection)
6085 class Map: public HeapObject {
6088 // Size in bytes or kVariableSizeSentinel if instances do not have
6090 inline int instance_size();
6091 inline void set_instance_size(int value);
6093 // Count of properties allocated in the object.
6094 inline int inobject_properties();
6095 inline void set_inobject_properties(int value);
6097 // Count of property fields pre-allocated in the object when first allocated.
6098 inline int pre_allocated_property_fields();
6099 inline void set_pre_allocated_property_fields(int value);
6102 inline InstanceType instance_type();
6103 inline void set_instance_type(InstanceType value);
6105 // Tells how many unused property fields are available in the
6106 // instance (only used for JSObject in fast mode).
6107 inline int unused_property_fields();
6108 inline void set_unused_property_fields(int value);
6111 inline byte bit_field();
6112 inline void set_bit_field(byte value);
6115 inline byte bit_field2();
6116 inline void set_bit_field2(byte value);
6119 inline uint32_t bit_field3();
6120 inline void set_bit_field3(uint32_t bits);
6122 class EnumLengthBits: public BitField<int,
6123 0, kDescriptorIndexBitCount> {}; // NOLINT
6124 class NumberOfOwnDescriptorsBits: public BitField<int,
6125 kDescriptorIndexBitCount, kDescriptorIndexBitCount> {}; // NOLINT
6126 STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
6127 class DictionaryMap : public BitField<bool, 20, 1> {};
6128 class OwnsDescriptors : public BitField<bool, 21, 1> {};
6129 class HasInstanceCallHandler : public BitField<bool, 22, 1> {};
6130 class Deprecated : public BitField<bool, 23, 1> {};
6131 class IsFrozen : public BitField<bool, 24, 1> {};
6132 class IsUnstable : public BitField<bool, 25, 1> {};
6133 class IsMigrationTarget : public BitField<bool, 26, 1> {};
6134 class DoneInobjectSlackTracking : public BitField<bool, 27, 1> {};
6137 // Keep this bit field at the very end for better code in
6138 // Builtins::kJSConstructStubGeneric stub.
6139 class ConstructionCount: public BitField<int, 29, 3> {};
6141 // Tells whether the object in the prototype property will be used
6142 // for instances created from this function. If the prototype
6143 // property is set to a value that is not a JSObject, the prototype
6144 // property will not be used to create instances of the function.
6145 // See ECMA-262, 13.2.2.
6146 inline void set_non_instance_prototype(bool value);
6147 inline bool has_non_instance_prototype();
6149 // Tells whether function has special prototype property. If not, prototype
6150 // property will not be created when accessed (will return undefined),
6151 // and construction from this function will not be allowed.
6152 inline void set_function_with_prototype(bool value);
6153 inline bool function_with_prototype();
6155 // Tells whether the instance with this map should be ignored by the
6156 // Object.getPrototypeOf() function and the __proto__ accessor.
6157 inline void set_is_hidden_prototype() {
6158 set_bit_field(bit_field() | (1 << kIsHiddenPrototype));
6161 inline bool is_hidden_prototype() {
6162 return ((1 << kIsHiddenPrototype) & bit_field()) != 0;
6165 // Records and queries whether the instance has a named interceptor.
6166 inline void set_has_named_interceptor() {
6167 set_bit_field(bit_field() | (1 << kHasNamedInterceptor));
6170 inline bool has_named_interceptor() {
6171 return ((1 << kHasNamedInterceptor) & bit_field()) != 0;
6174 // Records and queries whether the instance has an indexed interceptor.
6175 inline void set_has_indexed_interceptor() {
6176 set_bit_field(bit_field() | (1 << kHasIndexedInterceptor));
6179 inline bool has_indexed_interceptor() {
6180 return ((1 << kHasIndexedInterceptor) & bit_field()) != 0;
6183 // Tells whether the instance is undetectable.
6184 // An undetectable object is a special class of JSObject: 'typeof' operator
6185 // returns undefined, ToBoolean returns false. Otherwise it behaves like
6186 // a normal JS object. It is useful for implementing undetectable
6187 // document.all in Firefox & Safari.
6188 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
6189 inline void set_is_undetectable() {
6190 set_bit_field(bit_field() | (1 << kIsUndetectable));
6193 inline bool is_undetectable() {
6194 return ((1 << kIsUndetectable) & bit_field()) != 0;
6197 // Tells whether the instance has a call-as-function handler.
6198 inline void set_is_observed() {
6199 set_bit_field(bit_field() | (1 << kIsObserved));
6202 inline bool is_observed() {
6203 return ((1 << kIsObserved) & bit_field()) != 0;
6206 inline void set_is_extensible(bool value);
6207 inline bool is_extensible();
6208 inline void set_is_prototype_map(bool value);
6209 inline bool is_prototype_map();
6211 inline void set_elements_kind(ElementsKind elements_kind) {
6212 DCHECK(elements_kind < kElementsKindCount);
6213 DCHECK(kElementsKindCount <= (1 << Map::ElementsKindBits::kSize));
6214 set_bit_field2(Map::ElementsKindBits::update(bit_field2(), elements_kind));
6215 DCHECK(this->elements_kind() == elements_kind);
6218 inline ElementsKind elements_kind() {
6219 return Map::ElementsKindBits::decode(bit_field2());
6222 // Tells whether the instance has fast elements that are only Smis.
6223 inline bool has_fast_smi_elements() {
6224 return IsFastSmiElementsKind(elements_kind());
6227 // Tells whether the instance has fast elements.
6228 inline bool has_fast_object_elements() {
6229 return IsFastObjectElementsKind(elements_kind());
6232 inline bool has_fast_smi_or_object_elements() {
6233 return IsFastSmiOrObjectElementsKind(elements_kind());
6236 inline bool has_fast_double_elements() {
6237 return IsFastDoubleElementsKind(elements_kind());
6240 inline bool has_fast_elements() {
6241 return IsFastElementsKind(elements_kind());
6244 inline bool has_sloppy_arguments_elements() {
6245 return elements_kind() == SLOPPY_ARGUMENTS_ELEMENTS;
6248 inline bool has_external_array_elements() {
6249 return IsExternalArrayElementsKind(elements_kind());
6252 inline bool has_fixed_typed_array_elements() {
6253 return IsFixedTypedArrayElementsKind(elements_kind());
6256 inline bool has_dictionary_elements() {
6257 return IsDictionaryElementsKind(elements_kind());
6260 inline bool has_slow_elements_kind() {
6261 return elements_kind() == DICTIONARY_ELEMENTS
6262 || elements_kind() == SLOPPY_ARGUMENTS_ELEMENTS;
6265 static bool IsValidElementsTransition(ElementsKind from_kind,
6266 ElementsKind to_kind);
6268 // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
6269 // map with DICTIONARY_ELEMENTS was found in the prototype chain.
6270 bool DictionaryElementsInPrototypeChainOnly();
6272 inline bool HasTransitionArray() const;
6273 inline bool HasElementsTransition();
6274 inline Map* elements_transition_map();
6276 inline Map* GetTransition(int transition_index);
6277 inline int SearchTransition(Name* name);
6278 inline FixedArrayBase* GetInitialElements();
6280 DECL_ACCESSORS(transitions, TransitionArray)
6282 static inline Handle<String> ExpectedTransitionKey(Handle<Map> map);
6283 static inline Handle<Map> ExpectedTransitionTarget(Handle<Map> map);
6285 // Try to follow an existing transition to a field with attributes NONE. The
6286 // return value indicates whether the transition was successful.
6287 static inline Handle<Map> FindTransitionToField(Handle<Map> map,
6291 Map* FindFieldOwner(int descriptor);
6293 inline int GetInObjectPropertyOffset(int index);
6295 int NumberOfFields();
6297 // TODO(ishell): candidate with JSObject::MigrateToMap().
6298 bool InstancesNeedRewriting(Map* target, int target_number_of_fields,
6299 int target_inobject, int target_unused,
6300 int* old_number_of_fields);
6301 // TODO(ishell): moveit!
6302 static Handle<Map> GeneralizeAllFieldRepresentations(Handle<Map> map);
6303 MUST_USE_RESULT static Handle<HeapType> GeneralizeFieldType(
6304 Handle<HeapType> type1,
6305 Handle<HeapType> type2,
6307 static void GeneralizeFieldType(Handle<Map> map,
6309 Handle<HeapType> new_field_type);
6310 static Handle<Map> GeneralizeRepresentation(
6313 Representation new_representation,
6314 Handle<HeapType> new_field_type,
6315 StoreMode store_mode);
6316 static Handle<Map> CopyGeneralizeAllRepresentations(
6319 StoreMode store_mode,
6320 PropertyAttributes attributes,
6321 const char* reason);
6322 static Handle<Map> CopyGeneralizeAllRepresentations(
6325 StoreMode store_mode,
6326 const char* reason);
6328 static Handle<Map> PrepareForDataProperty(Handle<Map> old_map,
6329 int descriptor_number,
6330 Handle<Object> value);
6332 static Handle<Map> Normalize(Handle<Map> map, PropertyNormalizationMode mode);
6334 // Returns the constructor name (the name (possibly, inferred name) of the
6335 // function that was used to instantiate the object).
6336 String* constructor_name();
6338 // Tells whether the map is used for JSObjects in dictionary mode (ie
6339 // normalized objects, ie objects for which HasFastProperties returns false).
6340 // A map can never be used for both dictionary mode and fast mode JSObjects.
6341 // False by default and for HeapObjects that are not JSObjects.
6342 inline void set_dictionary_map(bool value);
6343 inline bool is_dictionary_map();
6345 // Tells whether the instance needs security checks when accessing its
6347 inline void set_is_access_check_needed(bool access_check_needed);
6348 inline bool is_access_check_needed();
6350 // Returns true if map has a non-empty stub code cache.
6351 inline bool has_code_cache();
6353 // [prototype]: implicit prototype object.
6354 DECL_ACCESSORS(prototype, Object)
6356 // [constructor]: points back to the function responsible for this map.
6357 DECL_ACCESSORS(constructor, Object)
6359 // [instance descriptors]: describes the object.
6360 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
6361 inline void InitializeDescriptors(DescriptorArray* descriptors);
6363 // [stub cache]: contains stubs compiled for this map.
6364 DECL_ACCESSORS(code_cache, Object)
6366 // [dependent code]: list of optimized codes that weakly embed this map.
6367 DECL_ACCESSORS(dependent_code, DependentCode)
6369 // [back pointer]: points back to the parent map from which a transition
6370 // leads to this map. The field overlaps with prototype transitions and the
6371 // back pointer will be moved into the prototype transitions array if
6373 inline Object* GetBackPointer();
6374 inline void SetBackPointer(Object* value,
6375 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
6376 inline void init_back_pointer(Object* undefined);
6378 // [prototype transitions]: cache of prototype transitions.
6379 // Prototype transition is a transition that happens
6380 // when we change object's prototype to a new one.
6382 // 0: finger - index of the first free cell in the cache
6383 // 1: back pointer that overlaps with prototype transitions field.
6384 // 2 + 2 * i: prototype
6385 // 3 + 2 * i: target map
6386 inline FixedArray* GetPrototypeTransitions();
6387 inline bool HasPrototypeTransitions();
6389 static const int kProtoTransitionHeaderSize = 1;
6390 static const int kProtoTransitionNumberOfEntriesOffset = 0;
6391 static const int kProtoTransitionElementsPerEntry = 2;
6392 static const int kProtoTransitionPrototypeOffset = 0;
6393 static const int kProtoTransitionMapOffset = 1;
6395 inline int NumberOfProtoTransitions() {
6396 FixedArray* cache = GetPrototypeTransitions();
6397 if (cache->length() == 0) return 0;
6399 Smi::cast(cache->get(kProtoTransitionNumberOfEntriesOffset))->value();
6402 inline void SetNumberOfProtoTransitions(int value) {
6403 FixedArray* cache = GetPrototypeTransitions();
6404 DCHECK(cache->length() != 0);
6405 cache->set(kProtoTransitionNumberOfEntriesOffset, Smi::FromInt(value));
6408 // Lookup in the map's instance descriptors and fill out the result
6409 // with the given holder if the name is found. The holder may be
6410 // NULL when this function is used from the compiler.
6411 inline void LookupDescriptor(JSObject* holder,
6413 LookupResult* result);
6415 inline void LookupTransition(JSObject* holder,
6417 LookupResult* result);
6419 inline PropertyDetails GetLastDescriptorDetails();
6421 // The size of transition arrays are limited so they do not end up in large
6422 // object space. Otherwise ClearNonLiveTransitions would leak memory while
6423 // applying in-place right trimming.
6424 inline bool CanHaveMoreTransitions();
6427 int number_of_own_descriptors = NumberOfOwnDescriptors();
6428 DCHECK(number_of_own_descriptors > 0);
6429 return number_of_own_descriptors - 1;
6432 int NumberOfOwnDescriptors() {
6433 return NumberOfOwnDescriptorsBits::decode(bit_field3());
6436 void SetNumberOfOwnDescriptors(int number) {
6437 DCHECK(number <= instance_descriptors()->number_of_descriptors());
6438 set_bit_field3(NumberOfOwnDescriptorsBits::update(bit_field3(), number));
6441 inline Cell* RetrieveDescriptorsPointer();
6444 return EnumLengthBits::decode(bit_field3());
6447 void SetEnumLength(int length) {
6448 if (length != kInvalidEnumCacheSentinel) {
6449 DCHECK(length >= 0);
6450 DCHECK(length == 0 || instance_descriptors()->HasEnumCache());
6451 DCHECK(length <= NumberOfOwnDescriptors());
6453 set_bit_field3(EnumLengthBits::update(bit_field3(), length));
6456 inline bool owns_descriptors();
6457 inline void set_owns_descriptors(bool owns_descriptors);
6458 inline bool has_instance_call_handler();
6459 inline void set_has_instance_call_handler();
6460 inline void freeze();
6461 inline bool is_frozen();
6462 inline void mark_unstable();
6463 inline bool is_stable();
6464 inline void set_migration_target(bool value);
6465 inline bool is_migration_target();
6466 inline void set_done_inobject_slack_tracking(bool value);
6467 inline bool done_inobject_slack_tracking();
6468 inline void set_construction_count(int value);
6469 inline int construction_count();
6470 inline void deprecate();
6471 inline bool is_deprecated();
6472 inline bool CanBeDeprecated();
6473 // Returns a non-deprecated version of the input. If the input was not
6474 // deprecated, it is directly returned. Otherwise, the non-deprecated version
6475 // is found by re-transitioning from the root of the transition tree using the
6476 // descriptor array of the map. Returns NULL if no updated map is found.
6477 // This method also applies any pending migrations along the prototype chain.
6478 static MaybeHandle<Map> TryUpdate(Handle<Map> map) V8_WARN_UNUSED_RESULT;
6479 // Same as above, but does not touch the prototype chain.
6480 static MaybeHandle<Map> TryUpdateInternal(Handle<Map> map)
6481 V8_WARN_UNUSED_RESULT;
6483 // Returns a non-deprecated version of the input. This method may deprecate
6484 // existing maps along the way if encodings conflict. Not for use while
6485 // gathering type feedback. Use TryUpdate in those cases instead.
6486 static Handle<Map> Update(Handle<Map> map);
6488 static Handle<Map> CopyDropDescriptors(Handle<Map> map);
6489 static Handle<Map> CopyInsertDescriptor(Handle<Map> map,
6490 Descriptor* descriptor,
6491 TransitionFlag flag);
6493 MUST_USE_RESULT static MaybeHandle<Map> CopyWithField(
6496 Handle<HeapType> type,
6497 PropertyAttributes attributes,
6498 Representation representation,
6499 TransitionFlag flag);
6501 MUST_USE_RESULT static MaybeHandle<Map> CopyWithConstant(
6504 Handle<Object> constant,
6505 PropertyAttributes attributes,
6506 TransitionFlag flag);
6508 // Returns a new map with all transitions dropped from the given map and
6509 // the ElementsKind set.
6510 static Handle<Map> TransitionElementsTo(Handle<Map> map,
6511 ElementsKind to_kind);
6513 static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
6515 static Handle<Map> CopyAsElementsKind(Handle<Map> map,
6517 TransitionFlag flag);
6519 static Handle<Map> CopyForObserved(Handle<Map> map);
6521 static Handle<Map> CopyForFreeze(Handle<Map> map);
6522 // Maximal number of fast properties. Used to restrict the number of map
6523 // transitions to avoid an explosion in the number of maps for objects used as
6525 inline bool TooManyFastProperties(StoreFromKeyed store_mode);
6526 static Handle<Map> TransitionToDataProperty(Handle<Map> map,
6528 Handle<Object> value,
6529 PropertyAttributes attributes,
6530 StoreFromKeyed store_mode);
6532 inline void AppendDescriptor(Descriptor* desc);
6534 // Returns a copy of the map, with all transitions dropped from the
6535 // instance descriptors.
6536 static Handle<Map> Copy(Handle<Map> map);
6537 static Handle<Map> Create(Handle<JSFunction> constructor,
6538 int extra_inobject_properties);
6540 // Returns the next free property index (only valid for FAST MODE).
6541 int NextFreePropertyIndex();
6543 // Returns the number of properties described in instance_descriptors
6544 // filtering out properties with the specified attributes.
6545 int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
6546 PropertyAttributes filter = NONE);
6548 // Returns the number of slots allocated for the initial properties
6549 // backing storage for instances of this map.
6550 int InitialPropertiesLength() {
6551 return pre_allocated_property_fields() + unused_property_fields() -
6552 inobject_properties();
6557 // Code cache operations.
6559 // Clears the code cache.
6560 inline void ClearCodeCache(Heap* heap);
6562 // Update code cache.
6563 static void UpdateCodeCache(Handle<Map> map,
6567 // Extend the descriptor array of the map with the list of descriptors.
6568 // In case of duplicates, the latest descriptor is used.
6569 static void AppendCallbackDescriptors(Handle<Map> map,
6570 Handle<Object> descriptors);
6572 static void EnsureDescriptorSlack(Handle<Map> map, int slack);
6574 // Returns the found code or undefined if absent.
6575 Object* FindInCodeCache(Name* name, Code::Flags flags);
6577 // Returns the non-negative index of the code object if it is in the
6578 // cache and -1 otherwise.
6579 int IndexInCodeCache(Object* name, Code* code);
6581 // Removes a code object from the code cache at the given index.
6582 void RemoveFromCodeCache(Name* name, Code* code, int index);
6584 // Set all map transitions from this map to dead maps to null. Also clear
6585 // back pointers in transition targets so that we do not process this map
6586 // again while following back pointers.
6587 void ClearNonLiveTransitions(Heap* heap);
6589 // Computes a hash value for this map, to be used in HashTables and such.
6592 // Returns the map that this map transitions to if its elements_kind
6593 // is changed to |elements_kind|, or NULL if no such map is cached yet.
6594 // |safe_to_add_transitions| is set to false if adding transitions is not
6596 Map* LookupElementsTransitionMap(ElementsKind elements_kind);
6598 // Returns the transitioned map for this map with the most generic
6599 // elements_kind that's found in |candidates|, or null handle if no match is
6601 Handle<Map> FindTransitionedMap(MapHandleList* candidates);
6603 bool CanTransition() {
6604 // Only JSObject and subtypes have map transitions and back pointers.
6605 STATIC_ASSERT(LAST_TYPE == LAST_JS_OBJECT_TYPE);
6606 return instance_type() >= FIRST_JS_OBJECT_TYPE;
6609 bool IsJSObjectMap() {
6610 return instance_type() >= FIRST_JS_OBJECT_TYPE;
6612 bool IsJSProxyMap() {
6613 InstanceType type = instance_type();
6614 return FIRST_JS_PROXY_TYPE <= type && type <= LAST_JS_PROXY_TYPE;
6616 bool IsJSGlobalProxyMap() {
6617 return instance_type() == JS_GLOBAL_PROXY_TYPE;
6619 bool IsJSGlobalObjectMap() {
6620 return instance_type() == JS_GLOBAL_OBJECT_TYPE;
6622 bool IsGlobalObjectMap() {
6623 const InstanceType type = instance_type();
6624 return type == JS_GLOBAL_OBJECT_TYPE || type == JS_BUILTINS_OBJECT_TYPE;
6627 inline bool CanOmitMapChecks();
6629 static void AddDependentCompilationInfo(Handle<Map> map,
6630 DependentCode::DependencyGroup group,
6631 CompilationInfo* info);
6633 static void AddDependentCode(Handle<Map> map,
6634 DependentCode::DependencyGroup group,
6636 static void AddDependentIC(Handle<Map> map,
6639 bool IsMapInArrayPrototypeChain();
6641 // Dispatched behavior.
6642 DECLARE_PRINTER(Map)
6643 DECLARE_VERIFIER(Map)
6646 void DictionaryMapVerify();
6647 void VerifyOmittedMapChecks();
6650 inline int visitor_id();
6651 inline void set_visitor_id(int visitor_id);
6653 typedef void (*TraverseCallback)(Map* map, void* data);
6655 void TraverseTransitionTree(TraverseCallback callback, void* data);
6657 // When you set the prototype of an object using the __proto__ accessor you
6658 // need a new map for the object (the prototype is stored in the map). In
6659 // order not to multiply maps unnecessarily we store these as transitions in
6660 // the original map. That way we can transition to the same map if the same
6661 // prototype is set, rather than creating a new map every time. The
6662 // transitions are in the form of a map where the keys are prototype objects
6663 // and the values are the maps the are transitioned to.
6664 static const int kMaxCachedPrototypeTransitions = 256;
6665 static Handle<Map> TransitionToPrototype(Handle<Map> map,
6666 Handle<Object> prototype);
6668 static const int kMaxPreAllocatedPropertyFields = 255;
6670 // Layout description.
6671 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
6672 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
6673 static const int kBitField3Offset = kInstanceAttributesOffset + kIntSize;
6674 static const int kPrototypeOffset = kBitField3Offset + kPointerSize;
6675 static const int kConstructorOffset = kPrototypeOffset + kPointerSize;
6676 // Storage for the transition array is overloaded to directly contain a back
6677 // pointer if unused. When the map has transitions, the back pointer is
6678 // transferred to the transition array and accessed through an extra
6680 static const int kTransitionsOrBackPointerOffset =
6681 kConstructorOffset + kPointerSize;
6682 static const int kDescriptorsOffset =
6683 kTransitionsOrBackPointerOffset + kPointerSize;
6684 static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
6685 static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
6686 static const int kSize = kDependentCodeOffset + kPointerSize;
6688 // Layout of pointer fields. Heap iteration code relies on them
6689 // being continuously allocated.
6690 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
6691 static const int kPointerFieldsEndOffset = kSize;
6693 // Byte offsets within kInstanceSizesOffset.
6694 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
6695 static const int kInObjectPropertiesByte = 1;
6696 static const int kInObjectPropertiesOffset =
6697 kInstanceSizesOffset + kInObjectPropertiesByte;
6698 static const int kPreAllocatedPropertyFieldsByte = 2;
6699 static const int kPreAllocatedPropertyFieldsOffset =
6700 kInstanceSizesOffset + kPreAllocatedPropertyFieldsByte;
6701 static const int kVisitorIdByte = 3;
6702 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
6704 // Byte offsets within kInstanceAttributesOffset attributes.
6705 #if V8_TARGET_LITTLE_ENDIAN
6706 // Order instance type and bit field together such that they can be loaded
6707 // together as a 16-bit word with instance type in the lower 8 bits regardless
6708 // of endianess. Also provide endian-independent offset to that 16-bit word.
6709 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
6710 static const int kBitFieldOffset = kInstanceAttributesOffset + 1;
6712 static const int kBitFieldOffset = kInstanceAttributesOffset + 0;
6713 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 1;
6715 static const int kInstanceTypeAndBitFieldOffset =
6716 kInstanceAttributesOffset + 0;
6717 static const int kBitField2Offset = kInstanceAttributesOffset + 2;
6718 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 3;
6720 STATIC_ASSERT(kInstanceTypeAndBitFieldOffset ==
6721 Internals::kMapInstanceTypeAndBitFieldOffset);
6723 // Bit positions for bit field.
6724 static const int kHasNonInstancePrototype = 0;
6725 static const int kIsHiddenPrototype = 1;
6726 static const int kHasNamedInterceptor = 2;
6727 static const int kHasIndexedInterceptor = 3;
6728 static const int kIsUndetectable = 4;
6729 static const int kIsObserved = 5;
6730 static const int kIsAccessCheckNeeded = 6;
6731 class FunctionWithPrototype: public BitField<bool, 7, 1> {};
6733 // Bit positions for bit field 2
6734 static const int kIsExtensible = 0;
6735 static const int kStringWrapperSafeForDefaultValueOf = 1;
6736 class IsPrototypeMapBits : public BitField<bool, 2, 1> {};
6737 class ElementsKindBits: public BitField<ElementsKind, 3, 5> {};
6739 // Derived values from bit field 2
6740 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
6741 (FAST_ELEMENTS + 1) << Map::ElementsKindBits::kShift) - 1;
6742 static const int8_t kMaximumBitField2FastSmiElementValue =
6743 static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
6744 Map::ElementsKindBits::kShift) - 1;
6745 static const int8_t kMaximumBitField2FastHoleyElementValue =
6746 static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
6747 Map::ElementsKindBits::kShift) - 1;
6748 static const int8_t kMaximumBitField2FastHoleySmiElementValue =
6749 static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
6750 Map::ElementsKindBits::kShift) - 1;
6752 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
6753 kPointerFieldsEndOffset,
6754 kSize> BodyDescriptor;
6756 // Compares this map to another to see if they describe equivalent objects.
6757 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
6758 // it had exactly zero inobject properties.
6759 // The "shared" flags of both this map and |other| are ignored.
6760 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
6763 static void ConnectElementsTransition(Handle<Map> parent, Handle<Map> child);
6764 static void ConnectTransition(Handle<Map> parent, Handle<Map> child,
6765 Handle<Name> name, SimpleTransitionFlag flag);
6767 bool EquivalentToForTransition(Map* other);
6768 static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
6769 static Handle<Map> ShareDescriptor(Handle<Map> map,
6770 Handle<DescriptorArray> descriptors,
6771 Descriptor* descriptor);
6772 static Handle<Map> CopyInstallDescriptors(
6775 Handle<DescriptorArray> descriptors);
6776 static Handle<Map> CopyAddDescriptor(Handle<Map> map,
6777 Descriptor* descriptor,
6778 TransitionFlag flag);
6779 static Handle<Map> CopyReplaceDescriptors(
6781 Handle<DescriptorArray> descriptors,
6782 TransitionFlag flag,
6783 MaybeHandle<Name> maybe_name,
6784 SimpleTransitionFlag simple_flag = FULL_TRANSITION);
6785 static Handle<Map> CopyReplaceDescriptor(Handle<Map> map,
6786 Handle<DescriptorArray> descriptors,
6787 Descriptor* descriptor,
6789 TransitionFlag flag);
6791 static Handle<Map> CopyNormalized(Handle<Map> map,
6792 PropertyNormalizationMode mode);
6794 // Fires when the layout of an object with a leaf map changes.
6795 // This includes adding transitions to the leaf map or changing
6796 // the descriptor array.
6797 inline void NotifyLeafMapLayoutChange();
6799 static Handle<Map> TransitionElementsToSlow(Handle<Map> object,
6800 ElementsKind to_kind);
6802 // Zaps the contents of backing data structures. Note that the
6803 // heap verifier (i.e. VerifyMarkingVisitor) relies on zapping of objects
6804 // holding weak references when incremental marking is used, because it also
6805 // iterates over objects that are otherwise unreachable.
6806 // In general we only want to call these functions in release mode when
6807 // heap verification is turned on.
6808 void ZapPrototypeTransitions();
6809 void ZapTransitions();
6811 void DeprecateTransitionTree();
6812 void DeprecateTarget(Name* key, DescriptorArray* new_descriptors);
6814 Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
6816 void UpdateFieldType(int descriptor_number, Handle<Name> name,
6817 Handle<HeapType> new_type);
6819 void PrintGeneralization(FILE* file,
6824 bool constant_to_field,
6825 Representation old_representation,
6826 Representation new_representation,
6827 HeapType* old_field_type,
6828 HeapType* new_field_type);
6830 static inline void SetPrototypeTransitions(
6832 Handle<FixedArray> prototype_transitions);
6834 static Handle<Map> GetPrototypeTransition(Handle<Map> map,
6835 Handle<Object> prototype);
6836 static Handle<Map> PutPrototypeTransition(Handle<Map> map,
6837 Handle<Object> prototype,
6838 Handle<Map> target_map);
6840 static const int kFastPropertiesSoftLimit = 12;
6841 static const int kMaxFastProperties = 128;
6843 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
6847 // An abstract superclass, a marker class really, for simple structure classes.
6848 // It doesn't carry much functionality but allows struct classes to be
6849 // identified in the type system.
6850 class Struct: public HeapObject {
6852 inline void InitializeBody(int object_size);
6853 DECLARE_CAST(Struct)
6857 // A simple one-element struct, useful where smis need to be boxed.
6858 class Box : public Struct {
6860 // [value]: the boxed contents.
6861 DECL_ACCESSORS(value, Object)
6865 // Dispatched behavior.
6866 DECLARE_PRINTER(Box)
6867 DECLARE_VERIFIER(Box)
6869 static const int kValueOffset = HeapObject::kHeaderSize;
6870 static const int kSize = kValueOffset + kPointerSize;
6873 DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
6877 // Script describes a script which has been added to the VM.
6878 class Script: public Struct {
6887 // Script compilation types.
6888 enum CompilationType {
6889 COMPILATION_TYPE_HOST = 0,
6890 COMPILATION_TYPE_EVAL = 1
6893 // Script compilation state.
6894 enum CompilationState {
6895 COMPILATION_STATE_INITIAL = 0,
6896 COMPILATION_STATE_COMPILED = 1
6899 // [source]: the script source.
6900 DECL_ACCESSORS(source, Object)
6902 // [name]: the script name.
6903 DECL_ACCESSORS(name, Object)
6905 // [id]: the script id.
6906 DECL_ACCESSORS(id, Smi)
6908 // [line_offset]: script line offset in resource from where it was extracted.
6909 DECL_ACCESSORS(line_offset, Smi)
6911 // [column_offset]: script column offset in resource from where it was
6913 DECL_ACCESSORS(column_offset, Smi)
6915 // [context_data]: context data for the context this script was compiled in.
6916 DECL_ACCESSORS(context_data, Object)
6918 // [wrapper]: the wrapper cache.
6919 DECL_ACCESSORS(wrapper, Foreign)
6921 // [type]: the script type.
6922 DECL_ACCESSORS(type, Smi)
6924 // [line_ends]: FixedArray of line ends positions.
6925 DECL_ACCESSORS(line_ends, Object)
6927 // [eval_from_shared]: for eval scripts the shared funcion info for the
6928 // function from which eval was called.
6929 DECL_ACCESSORS(eval_from_shared, Object)
6931 // [eval_from_instructions_offset]: the instruction offset in the code for the
6932 // function from which eval was called where eval was called.
6933 DECL_ACCESSORS(eval_from_instructions_offset, Smi)
6935 // [flags]: Holds an exciting bitfield.
6936 DECL_ACCESSORS(flags, Smi)
6938 // [source_url]: sourceURL from magic comment
6939 DECL_ACCESSORS(source_url, Object)
6941 // [source_url]: sourceMappingURL magic comment
6942 DECL_ACCESSORS(source_mapping_url, Object)
6944 // [compilation_type]: how the the script was compiled. Encoded in the
6946 inline CompilationType compilation_type();
6947 inline void set_compilation_type(CompilationType type);
6949 // [compilation_state]: determines whether the script has already been
6950 // compiled. Encoded in the 'flags' field.
6951 inline CompilationState compilation_state();
6952 inline void set_compilation_state(CompilationState state);
6954 // [is_shared_cross_origin]: An opaque boolean set by the embedder via
6955 // ScriptOrigin, and used by the embedder to make decisions about the
6956 // script's level of privilege. V8 just passes this through. Encoded in
6957 // the 'flags' field.
6958 DECL_BOOLEAN_ACCESSORS(is_shared_cross_origin)
6960 DECLARE_CAST(Script)
6962 // If script source is an external string, check that the underlying
6963 // resource is accessible. Otherwise, always return true.
6964 inline bool HasValidSource();
6966 // Convert code position into column number.
6967 static int GetColumnNumber(Handle<Script> script, int code_pos);
6969 // Convert code position into (zero-based) line number.
6970 // The non-handlified version does not allocate, but may be much slower.
6971 static int GetLineNumber(Handle<Script> script, int code_pos);
6972 int GetLineNumber(int code_pos);
6974 static Handle<Object> GetNameOrSourceURL(Handle<Script> script);
6976 // Init line_ends array with code positions of line ends inside script source.
6977 static void InitLineEnds(Handle<Script> script);
6979 // Get the JS object wrapping the given script; create it if none exists.
6980 static Handle<JSObject> GetWrapper(Handle<Script> script);
6981 void ClearWrapperCache();
6983 // Dispatched behavior.
6984 DECLARE_PRINTER(Script)
6985 DECLARE_VERIFIER(Script)
6987 static const int kSourceOffset = HeapObject::kHeaderSize;
6988 static const int kNameOffset = kSourceOffset + kPointerSize;
6989 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
6990 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
6991 static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
6992 static const int kWrapperOffset = kContextOffset + kPointerSize;
6993 static const int kTypeOffset = kWrapperOffset + kPointerSize;
6994 static const int kLineEndsOffset = kTypeOffset + kPointerSize;
6995 static const int kIdOffset = kLineEndsOffset + kPointerSize;
6996 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
6997 static const int kEvalFrominstructionsOffsetOffset =
6998 kEvalFromSharedOffset + kPointerSize;
6999 static const int kFlagsOffset =
7000 kEvalFrominstructionsOffsetOffset + kPointerSize;
7001 static const int kSourceUrlOffset = kFlagsOffset + kPointerSize;
7002 static const int kSourceMappingUrlOffset = kSourceUrlOffset + kPointerSize;
7003 static const int kSize = kSourceMappingUrlOffset + kPointerSize;
7006 int GetLineNumberWithArray(int code_pos);
7008 // Bit positions in the flags field.
7009 static const int kCompilationTypeBit = 0;
7010 static const int kCompilationStateBit = 1;
7011 static const int kIsSharedCrossOriginBit = 2;
7013 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
7017 // List of builtin functions we want to identify to improve code
7020 // Each entry has a name of a global object property holding an object
7021 // optionally followed by ".prototype", a name of a builtin function
7022 // on the object (the one the id is set for), and a label.
7024 // Installation of ids for the selected builtin functions is handled
7025 // by the bootstrapper.
7026 #define FUNCTIONS_WITH_ID_LIST(V) \
7027 V(Array.prototype, indexOf, ArrayIndexOf) \
7028 V(Array.prototype, lastIndexOf, ArrayLastIndexOf) \
7029 V(Array.prototype, push, ArrayPush) \
7030 V(Array.prototype, pop, ArrayPop) \
7031 V(Array.prototype, shift, ArrayShift) \
7032 V(Function.prototype, apply, FunctionApply) \
7033 V(String.prototype, charCodeAt, StringCharCodeAt) \
7034 V(String.prototype, charAt, StringCharAt) \
7035 V(String, fromCharCode, StringFromCharCode) \
7036 V(Math, floor, MathFloor) \
7037 V(Math, round, MathRound) \
7038 V(Math, ceil, MathCeil) \
7039 V(Math, abs, MathAbs) \
7040 V(Math, log, MathLog) \
7041 V(Math, exp, MathExp) \
7042 V(Math, sqrt, MathSqrt) \
7043 V(Math, pow, MathPow) \
7044 V(Math, max, MathMax) \
7045 V(Math, min, MathMin) \
7046 V(Math, imul, MathImul) \
7047 V(Math, clz32, MathClz32) \
7048 V(Math, fround, MathFround)
7050 enum BuiltinFunctionId {
7052 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
7054 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
7055 #undef DECLARE_FUNCTION_ID
7056 // Fake id for a special case of Math.pow. Note, it continues the
7057 // list of math functions.
7062 // SharedFunctionInfo describes the JSFunction information that can be
7063 // shared by multiple instances of the function.
7064 class SharedFunctionInfo: public HeapObject {
7066 // [name]: Function name.
7067 DECL_ACCESSORS(name, Object)
7069 // [code]: Function code.
7070 DECL_ACCESSORS(code, Code)
7071 inline void ReplaceCode(Code* code);
7073 // [optimized_code_map]: Map from native context to optimized code
7074 // and a shared literals array or Smi(0) if none.
7075 DECL_ACCESSORS(optimized_code_map, Object)
7077 // Returns index i of the entry with the specified context and OSR entry.
7078 // At position i - 1 is the context, position i the code, and i + 1 the
7079 // literals array. Returns -1 when no matching entry is found.
7080 int SearchOptimizedCodeMap(Context* native_context, BailoutId osr_ast_id);
7082 // Installs optimized code from the code map on the given closure. The
7083 // index has to be consistent with a search result as defined above.
7084 FixedArray* GetLiteralsFromOptimizedCodeMap(int index);
7086 Code* GetCodeFromOptimizedCodeMap(int index);
7088 // Clear optimized code map.
7089 void ClearOptimizedCodeMap();
7091 // Removed a specific optimized code object from the optimized code map.
7092 void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
7094 void ClearTypeFeedbackInfo();
7096 // Trims the optimized code map after entries have been removed.
7097 void TrimOptimizedCodeMap(int shrink_by);
7099 // Add a new entry to the optimized code map.
7100 static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
7101 Handle<Context> native_context,
7103 Handle<FixedArray> literals,
7104 BailoutId osr_ast_id);
7106 // Layout description of the optimized code map.
7107 static const int kNextMapIndex = 0;
7108 static const int kEntriesStart = 1;
7109 static const int kContextOffset = 0;
7110 static const int kCachedCodeOffset = 1;
7111 static const int kLiteralsOffset = 2;
7112 static const int kOsrAstIdOffset = 3;
7113 static const int kEntryLength = 4;
7114 static const int kInitialLength = kEntriesStart + kEntryLength;
7116 // [scope_info]: Scope info.
7117 DECL_ACCESSORS(scope_info, ScopeInfo)
7119 // [construct stub]: Code stub for constructing instances of this function.
7120 DECL_ACCESSORS(construct_stub, Code)
7122 // Returns if this function has been compiled to native code yet.
7123 inline bool is_compiled();
7125 // [length]: The function length - usually the number of declared parameters.
7126 // Use up to 2^30 parameters.
7127 inline int length() const;
7128 inline void set_length(int value);
7130 // [formal parameter count]: The declared number of parameters.
7131 inline int formal_parameter_count() const;
7132 inline void set_formal_parameter_count(int value);
7134 // Set the formal parameter count so the function code will be
7135 // called without using argument adaptor frames.
7136 inline void DontAdaptArguments();
7138 // [expected_nof_properties]: Expected number of properties for the function.
7139 inline int expected_nof_properties() const;
7140 inline void set_expected_nof_properties(int value);
7142 // [feedback_vector] - accumulates ast node feedback from full-codegen and
7143 // (increasingly) from crankshafted code where sufficient feedback isn't
7144 // available. Currently the field is duplicated in
7145 // TypeFeedbackInfo::feedback_vector, but the allocation is done here.
7146 DECL_ACCESSORS(feedback_vector, FixedArray)
7148 // [instance class name]: class name for instances.
7149 DECL_ACCESSORS(instance_class_name, Object)
7151 // [function data]: This field holds some additional data for function.
7152 // Currently it either has FunctionTemplateInfo to make benefit the API
7153 // or Smi identifying a builtin function.
7154 // In the long run we don't want all functions to have this field but
7155 // we can fix that when we have a better model for storing hidden data
7157 DECL_ACCESSORS(function_data, Object)
7159 inline bool IsApiFunction();
7160 inline FunctionTemplateInfo* get_api_func_data();
7161 inline bool HasBuiltinFunctionId();
7162 inline BuiltinFunctionId builtin_function_id();
7164 // [script info]: Script from which the function originates.
7165 DECL_ACCESSORS(script, Object)
7167 // [num_literals]: Number of literals used by this function.
7168 inline int num_literals() const;
7169 inline void set_num_literals(int value);
7171 // [start_position_and_type]: Field used to store both the source code
7172 // position, whether or not the function is a function expression,
7173 // and whether or not the function is a toplevel function. The two
7174 // least significants bit indicates whether the function is an
7175 // expression and the rest contains the source code position.
7176 inline int start_position_and_type() const;
7177 inline void set_start_position_and_type(int value);
7179 // [debug info]: Debug information.
7180 DECL_ACCESSORS(debug_info, Object)
7182 // [inferred name]: Name inferred from variable or property
7183 // assignment of this function. Used to facilitate debugging and
7184 // profiling of JavaScript code written in OO style, where almost
7185 // all functions are anonymous but are assigned to object
7187 DECL_ACCESSORS(inferred_name, String)
7189 // The function's name if it is non-empty, otherwise the inferred name.
7190 String* DebugName();
7192 // Position of the 'function' token in the script source.
7193 inline int function_token_position() const;
7194 inline void set_function_token_position(int function_token_position);
7196 // Position of this function in the script source.
7197 inline int start_position() const;
7198 inline void set_start_position(int start_position);
7200 // End position of this function in the script source.
7201 inline int end_position() const;
7202 inline void set_end_position(int end_position);
7204 // Is this function a function expression in the source code.
7205 DECL_BOOLEAN_ACCESSORS(is_expression)
7207 // Is this function a top-level function (scripts, evals).
7208 DECL_BOOLEAN_ACCESSORS(is_toplevel)
7210 // Bit field containing various information collected by the compiler to
7211 // drive optimization.
7212 inline int compiler_hints() const;
7213 inline void set_compiler_hints(int value);
7215 inline int ast_node_count() const;
7216 inline void set_ast_node_count(int count);
7218 inline int profiler_ticks() const;
7219 inline void set_profiler_ticks(int ticks);
7221 // Inline cache age is used to infer whether the function survived a context
7222 // disposal or not. In the former case we reset the opt_count.
7223 inline int ic_age();
7224 inline void set_ic_age(int age);
7226 // Indicates if this function can be lazy compiled.
7227 // This is used to determine if we can safely flush code from a function
7228 // when doing GC if we expect that the function will no longer be used.
7229 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
7231 // Indicates if this function can be lazy compiled without a context.
7232 // This is used to determine if we can force compilation without reaching
7233 // the function through program execution but through other means (e.g. heap
7234 // iteration by the debugger).
7235 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
7237 // Indicates whether optimizations have been disabled for this
7238 // shared function info. If a function is repeatedly optimized or if
7239 // we cannot optimize the function we disable optimization to avoid
7240 // spending time attempting to optimize it again.
7241 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
7243 // Indicates the language mode.
7244 inline StrictMode strict_mode();
7245 inline void set_strict_mode(StrictMode strict_mode);
7247 // False if the function definitely does not allocate an arguments object.
7248 DECL_BOOLEAN_ACCESSORS(uses_arguments)
7250 // True if the function has any duplicated parameter names.
7251 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
7253 // Indicates whether the function is a native function.
7254 // These needs special treatment in .call and .apply since
7255 // null passed as the receiver should not be translated to the
7257 DECL_BOOLEAN_ACCESSORS(native)
7259 // Indicate that this builtin needs to be inlined in crankshaft.
7260 DECL_BOOLEAN_ACCESSORS(inline_builtin)
7262 // Indicates that the function was created by the Function function.
7263 // Though it's anonymous, toString should treat it as if it had the name
7264 // "anonymous". We don't set the name itself so that the system does not
7265 // see a binding for it.
7266 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
7268 // Indicates whether the function is a bound function created using
7269 // the bind function.
7270 DECL_BOOLEAN_ACCESSORS(bound)
7272 // Indicates that the function is anonymous (the name field can be set
7273 // through the API, which does not change this flag).
7274 DECL_BOOLEAN_ACCESSORS(is_anonymous)
7276 // Is this a function or top-level/eval code.
7277 DECL_BOOLEAN_ACCESSORS(is_function)
7279 // Indicates that code for this function cannot be cached.
7280 DECL_BOOLEAN_ACCESSORS(dont_cache)
7282 // Indicates that code for this function cannot be flushed.
7283 DECL_BOOLEAN_ACCESSORS(dont_flush)
7285 // Indicates that this function is a generator.
7286 DECL_BOOLEAN_ACCESSORS(is_generator)
7288 // Indicates that this function is an arrow function.
7289 DECL_BOOLEAN_ACCESSORS(is_arrow)
7291 // Indicates whether or not the code in the shared function support
7293 inline bool has_deoptimization_support();
7295 // Enable deoptimization support through recompiled code.
7296 void EnableDeoptimizationSupport(Code* recompiled);
7298 // Disable (further) attempted optimization of all functions sharing this
7299 // shared function info.
7300 void DisableOptimization(BailoutReason reason);
7302 inline BailoutReason DisableOptimizationReason();
7304 // Lookup the bailout ID and DCHECK that it exists in the non-optimized
7305 // code, returns whether it asserted (i.e., always true if assertions are
7307 bool VerifyBailoutId(BailoutId id);
7309 // [source code]: Source code for the function.
7310 bool HasSourceCode() const;
7311 Handle<Object> GetSourceCode();
7313 // Number of times the function was optimized.
7314 inline int opt_count();
7315 inline void set_opt_count(int opt_count);
7317 // Number of times the function was deoptimized.
7318 inline void set_deopt_count(int value);
7319 inline int deopt_count();
7320 inline void increment_deopt_count();
7322 // Number of time we tried to re-enable optimization after it
7323 // was disabled due to high number of deoptimizations.
7324 inline void set_opt_reenable_tries(int value);
7325 inline int opt_reenable_tries();
7327 inline void TryReenableOptimization();
7329 // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
7330 inline void set_counters(int value);
7331 inline int counters() const;
7333 // Stores opt_count and bailout_reason as bit-fields.
7334 inline void set_opt_count_and_bailout_reason(int value);
7335 inline int opt_count_and_bailout_reason() const;
7337 void set_bailout_reason(BailoutReason reason) {
7338 set_opt_count_and_bailout_reason(
7339 DisabledOptimizationReasonBits::update(opt_count_and_bailout_reason(),
7343 // Check whether or not this function is inlineable.
7344 bool IsInlineable();
7346 // Source size of this function.
7349 // Calculate the instance size.
7350 int CalculateInstanceSize();
7352 // Calculate the number of in-object properties.
7353 int CalculateInObjectProperties();
7355 // Dispatched behavior.
7356 DECLARE_PRINTER(SharedFunctionInfo)
7357 DECLARE_VERIFIER(SharedFunctionInfo)
7359 void ResetForNewContext(int new_ic_age);
7361 DECLARE_CAST(SharedFunctionInfo)
7364 static const int kDontAdaptArgumentsSentinel = -1;
7366 // Layout description.
7368 static const int kNameOffset = HeapObject::kHeaderSize;
7369 static const int kCodeOffset = kNameOffset + kPointerSize;
7370 static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
7371 static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
7372 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
7373 static const int kInstanceClassNameOffset =
7374 kConstructStubOffset + kPointerSize;
7375 static const int kFunctionDataOffset =
7376 kInstanceClassNameOffset + kPointerSize;
7377 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
7378 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
7379 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
7380 static const int kFeedbackVectorOffset =
7381 kInferredNameOffset + kPointerSize;
7382 #if V8_HOST_ARCH_32_BIT
7384 static const int kLengthOffset =
7385 kFeedbackVectorOffset + kPointerSize;
7386 static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
7387 static const int kExpectedNofPropertiesOffset =
7388 kFormalParameterCountOffset + kPointerSize;
7389 static const int kNumLiteralsOffset =
7390 kExpectedNofPropertiesOffset + kPointerSize;
7391 static const int kStartPositionAndTypeOffset =
7392 kNumLiteralsOffset + kPointerSize;
7393 static const int kEndPositionOffset =
7394 kStartPositionAndTypeOffset + kPointerSize;
7395 static const int kFunctionTokenPositionOffset =
7396 kEndPositionOffset + kPointerSize;
7397 static const int kCompilerHintsOffset =
7398 kFunctionTokenPositionOffset + kPointerSize;
7399 static const int kOptCountAndBailoutReasonOffset =
7400 kCompilerHintsOffset + kPointerSize;
7401 static const int kCountersOffset =
7402 kOptCountAndBailoutReasonOffset + kPointerSize;
7403 static const int kAstNodeCountOffset =
7404 kCountersOffset + kPointerSize;
7405 static const int kProfilerTicksOffset =
7406 kAstNodeCountOffset + kPointerSize;
7409 static const int kSize = kProfilerTicksOffset + kPointerSize;
7411 // The only reason to use smi fields instead of int fields
7412 // is to allow iteration without maps decoding during
7413 // garbage collections.
7414 // To avoid wasting space on 64-bit architectures we use
7415 // the following trick: we group integer fields into pairs
7416 // First integer in each pair is shifted left by 1.
7417 // By doing this we guarantee that LSB of each kPointerSize aligned
7418 // word is not set and thus this word cannot be treated as pointer
7419 // to HeapObject during old space traversal.
7420 static const int kLengthOffset =
7421 kFeedbackVectorOffset + kPointerSize;
7422 static const int kFormalParameterCountOffset =
7423 kLengthOffset + kIntSize;
7425 static const int kExpectedNofPropertiesOffset =
7426 kFormalParameterCountOffset + kIntSize;
7427 static const int kNumLiteralsOffset =
7428 kExpectedNofPropertiesOffset + kIntSize;
7430 static const int kEndPositionOffset =
7431 kNumLiteralsOffset + kIntSize;
7432 static const int kStartPositionAndTypeOffset =
7433 kEndPositionOffset + kIntSize;
7435 static const int kFunctionTokenPositionOffset =
7436 kStartPositionAndTypeOffset + kIntSize;
7437 static const int kCompilerHintsOffset =
7438 kFunctionTokenPositionOffset + kIntSize;
7440 static const int kOptCountAndBailoutReasonOffset =
7441 kCompilerHintsOffset + kIntSize;
7442 static const int kCountersOffset =
7443 kOptCountAndBailoutReasonOffset + kIntSize;
7445 static const int kAstNodeCountOffset =
7446 kCountersOffset + kIntSize;
7447 static const int kProfilerTicksOffset =
7448 kAstNodeCountOffset + kIntSize;
7451 static const int kSize = kProfilerTicksOffset + kIntSize;
7455 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
7457 typedef FixedBodyDescriptor<kNameOffset,
7458 kFeedbackVectorOffset + kPointerSize,
7459 kSize> BodyDescriptor;
7461 // Bit positions in start_position_and_type.
7462 // The source code start position is in the 30 most significant bits of
7463 // the start_position_and_type field.
7464 static const int kIsExpressionBit = 0;
7465 static const int kIsTopLevelBit = 1;
7466 static const int kStartPositionShift = 2;
7467 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
7469 // Bit positions in compiler_hints.
7470 enum CompilerHints {
7471 kAllowLazyCompilation,
7472 kAllowLazyCompilationWithoutContext,
7473 kOptimizationDisabled,
7474 kStrictModeFunction,
7476 kHasDuplicateParameters,
7481 kNameShouldPrintAsAnonymous,
7487 kCompilerHintsCount // Pseudo entry
7490 class DeoptCountBits: public BitField<int, 0, 4> {};
7491 class OptReenableTriesBits: public BitField<int, 4, 18> {};
7492 class ICAgeBits: public BitField<int, 22, 8> {};
7494 class OptCountBits: public BitField<int, 0, 22> {};
7495 class DisabledOptimizationReasonBits: public BitField<int, 22, 8> {};
7498 #if V8_HOST_ARCH_32_BIT
7499 // On 32 bit platforms, compiler hints is a smi.
7500 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
7501 static const int kCompilerHintsSize = kPointerSize;
7503 // On 64 bit platforms, compiler hints is not a smi, see comment above.
7504 static const int kCompilerHintsSmiTagSize = 0;
7505 static const int kCompilerHintsSize = kIntSize;
7508 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
7509 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
7512 // Constants for optimizing codegen for strict mode function and
7514 // Allows to use byte-width instructions.
7515 static const int kStrictModeBitWithinByte =
7516 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
7518 static const int kNativeBitWithinByte =
7519 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
7521 #if defined(V8_TARGET_LITTLE_ENDIAN)
7522 static const int kStrictModeByteOffset = kCompilerHintsOffset +
7523 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
7524 static const int kNativeByteOffset = kCompilerHintsOffset +
7525 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
7526 #elif defined(V8_TARGET_BIG_ENDIAN)
7527 static const int kStrictModeByteOffset = kCompilerHintsOffset +
7528 (kCompilerHintsSize - 1) -
7529 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
7530 static const int kNativeByteOffset = kCompilerHintsOffset +
7531 (kCompilerHintsSize - 1) -
7532 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
7534 #error Unknown byte ordering
7538 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
7542 // Printing support.
7543 struct SourceCodeOf {
7544 explicit SourceCodeOf(SharedFunctionInfo* v, int max = -1)
7545 : value(v), max_length(max) {}
7546 const SharedFunctionInfo* value;
7551 OStream& operator<<(OStream& os, const SourceCodeOf& v);
7554 class JSGeneratorObject: public JSObject {
7556 // [function]: The function corresponding to this generator object.
7557 DECL_ACCESSORS(function, JSFunction)
7559 // [context]: The context of the suspended computation.
7560 DECL_ACCESSORS(context, Context)
7562 // [receiver]: The receiver of the suspended computation.
7563 DECL_ACCESSORS(receiver, Object)
7565 // [continuation]: Offset into code of continuation.
7567 // A positive offset indicates a suspended generator. The special
7568 // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
7569 // cannot be resumed.
7570 inline int continuation() const;
7571 inline void set_continuation(int continuation);
7572 inline bool is_closed();
7573 inline bool is_executing();
7574 inline bool is_suspended();
7576 // [operand_stack]: Saved operand stack.
7577 DECL_ACCESSORS(operand_stack, FixedArray)
7579 // [stack_handler_index]: Index of first stack handler in operand_stack, or -1
7580 // if the captured activation had no stack handler.
7581 inline int stack_handler_index() const;
7582 inline void set_stack_handler_index(int stack_handler_index);
7584 DECLARE_CAST(JSGeneratorObject)
7586 // Dispatched behavior.
7587 DECLARE_PRINTER(JSGeneratorObject)
7588 DECLARE_VERIFIER(JSGeneratorObject)
7590 // Magic sentinel values for the continuation.
7591 static const int kGeneratorExecuting = -1;
7592 static const int kGeneratorClosed = 0;
7594 // Layout description.
7595 static const int kFunctionOffset = JSObject::kHeaderSize;
7596 static const int kContextOffset = kFunctionOffset + kPointerSize;
7597 static const int kReceiverOffset = kContextOffset + kPointerSize;
7598 static const int kContinuationOffset = kReceiverOffset + kPointerSize;
7599 static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
7600 static const int kStackHandlerIndexOffset =
7601 kOperandStackOffset + kPointerSize;
7602 static const int kSize = kStackHandlerIndexOffset + kPointerSize;
7604 // Resume mode, for use by runtime functions.
7605 enum ResumeMode { NEXT, THROW };
7607 // Yielding from a generator returns an object with the following inobject
7608 // properties. See Context::iterator_result_map() for the map.
7609 static const int kResultValuePropertyIndex = 0;
7610 static const int kResultDonePropertyIndex = 1;
7611 static const int kResultPropertyCount = 2;
7613 static const int kResultValuePropertyOffset = JSObject::kHeaderSize;
7614 static const int kResultDonePropertyOffset =
7615 kResultValuePropertyOffset + kPointerSize;
7616 static const int kResultSize = kResultDonePropertyOffset + kPointerSize;
7619 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
7623 // Representation for module instance objects.
7624 class JSModule: public JSObject {
7626 // [context]: the context holding the module's locals, or undefined if none.
7627 DECL_ACCESSORS(context, Object)
7629 // [scope_info]: Scope info.
7630 DECL_ACCESSORS(scope_info, ScopeInfo)
7632 DECLARE_CAST(JSModule)
7634 // Dispatched behavior.
7635 DECLARE_PRINTER(JSModule)
7636 DECLARE_VERIFIER(JSModule)
7638 // Layout description.
7639 static const int kContextOffset = JSObject::kHeaderSize;
7640 static const int kScopeInfoOffset = kContextOffset + kPointerSize;
7641 static const int kSize = kScopeInfoOffset + kPointerSize;
7644 DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
7648 // JSFunction describes JavaScript functions.
7649 class JSFunction: public JSObject {
7651 // [prototype_or_initial_map]:
7652 DECL_ACCESSORS(prototype_or_initial_map, Object)
7654 // [shared]: The information about the function that
7655 // can be shared by instances.
7656 DECL_ACCESSORS(shared, SharedFunctionInfo)
7658 // [context]: The context for this function.
7659 inline Context* context();
7660 inline void set_context(Object* context);
7661 inline JSObject* global_proxy();
7663 // [code]: The generated code object for this function. Executed
7664 // when the function is invoked, e.g. foo() or new foo(). See
7665 // [[Call]] and [[Construct]] description in ECMA-262, section
7667 inline Code* code();
7668 inline void set_code(Code* code);
7669 inline void set_code_no_write_barrier(Code* code);
7670 inline void ReplaceCode(Code* code);
7672 // Tells whether this function is builtin.
7673 inline bool IsBuiltin();
7675 // Tells whether this function is defined in a native script.
7676 inline bool IsFromNativeScript();
7678 // Tells whether this function is defined in an extension script.
7679 inline bool IsFromExtensionScript();
7681 // Tells whether or not the function needs arguments adaption.
7682 inline bool NeedsArgumentsAdaption();
7684 // Tells whether or not this function has been optimized.
7685 inline bool IsOptimized();
7687 // Tells whether or not this function can be optimized.
7688 inline bool IsOptimizable();
7690 // Mark this function for lazy recompilation. The function will be
7691 // recompiled the next time it is executed.
7692 void MarkForOptimization();
7693 void MarkForConcurrentOptimization();
7694 void MarkInOptimizationQueue();
7696 // Tells whether or not the function is already marked for lazy
7698 inline bool IsMarkedForOptimization();
7699 inline bool IsMarkedForConcurrentOptimization();
7701 // Tells whether or not the function is on the concurrent recompilation queue.
7702 inline bool IsInOptimizationQueue();
7704 // Inobject slack tracking is the way to reclaim unused inobject space.
7706 // The instance size is initially determined by adding some slack to
7707 // expected_nof_properties (to allow for a few extra properties added
7708 // after the constructor). There is no guarantee that the extra space
7709 // will not be wasted.
7711 // Here is the algorithm to reclaim the unused inobject space:
7712 // - Detect the first constructor call for this JSFunction.
7713 // When it happens enter the "in progress" state: initialize construction
7714 // counter in the initial_map and set the |done_inobject_slack_tracking|
7716 // - While the tracking is in progress create objects filled with
7717 // one_pointer_filler_map instead of undefined_value. This way they can be
7718 // resized quickly and safely.
7719 // - Once enough (kGenerousAllocationCount) objects have been created
7720 // compute the 'slack' (traverse the map transition tree starting from the
7721 // initial_map and find the lowest value of unused_property_fields).
7722 // - Traverse the transition tree again and decrease the instance size
7723 // of every map. Existing objects will resize automatically (they are
7724 // filled with one_pointer_filler_map). All further allocations will
7725 // use the adjusted instance size.
7726 // - SharedFunctionInfo's expected_nof_properties left unmodified since
7727 // allocations made using different closures could actually create different
7728 // kind of objects (see prototype inheritance pattern).
7730 // Important: inobject slack tracking is not attempted during the snapshot
7733 static const int kGenerousAllocationCount = Map::ConstructionCount::kMax;
7734 static const int kFinishSlackTracking = 1;
7735 static const int kNoSlackTracking = 0;
7737 // True if the initial_map is set and the object constructions countdown
7738 // counter is not zero.
7739 inline bool IsInobjectSlackTrackingInProgress();
7741 // Starts the tracking.
7742 // Initializes object constructions countdown counter in the initial map.
7743 // IsInobjectSlackTrackingInProgress is normally true after this call,
7744 // except when tracking have not been started (e.g. the map has no unused
7745 // properties or the snapshot is being built).
7746 void StartInobjectSlackTracking();
7748 // Completes the tracking.
7749 // IsInobjectSlackTrackingInProgress is false after this call.
7750 void CompleteInobjectSlackTracking();
7752 // [literals_or_bindings]: Fixed array holding either
7753 // the materialized literals or the bindings of a bound function.
7755 // If the function contains object, regexp or array literals, the
7756 // literals array prefix contains the object, regexp, and array
7757 // function to be used when creating these literals. This is
7758 // necessary so that we do not dynamically lookup the object, regexp
7759 // or array functions. Performing a dynamic lookup, we might end up
7760 // using the functions from a new context that we should not have
7763 // On bound functions, the array is a (copy-on-write) fixed-array containing
7764 // the function that was bound, bound this-value and any bound
7765 // arguments. Bound functions never contain literals.
7766 DECL_ACCESSORS(literals_or_bindings, FixedArray)
7768 inline FixedArray* literals();
7769 inline void set_literals(FixedArray* literals);
7771 inline FixedArray* function_bindings();
7772 inline void set_function_bindings(FixedArray* bindings);
7774 // The initial map for an object created by this constructor.
7775 inline Map* initial_map();
7776 static void SetInitialMap(Handle<JSFunction> function, Handle<Map> map,
7777 Handle<Object> prototype);
7778 inline bool has_initial_map();
7779 static void EnsureHasInitialMap(Handle<JSFunction> function);
7781 // Get and set the prototype property on a JSFunction. If the
7782 // function has an initial map the prototype is set on the initial
7783 // map. Otherwise, the prototype is put in the initial map field
7784 // until an initial map is needed.
7785 inline bool has_prototype();
7786 inline bool has_instance_prototype();
7787 inline Object* prototype();
7788 inline Object* instance_prototype();
7789 static void SetPrototype(Handle<JSFunction> function,
7790 Handle<Object> value);
7791 static void SetInstancePrototype(Handle<JSFunction> function,
7792 Handle<Object> value);
7794 // After prototype is removed, it will not be created when accessed, and
7795 // [[Construct]] from this function will not be allowed.
7796 bool RemovePrototype();
7797 inline bool should_have_prototype();
7799 // Accessor for this function's initial map's [[class]]
7800 // property. This is primarily used by ECMA native functions. This
7801 // method sets the class_name field of this function's initial map
7802 // to a given value. It creates an initial map if this function does
7803 // not have one. Note that this method does not copy the initial map
7804 // if it has one already, but simply replaces it with the new value.
7805 // Instances created afterwards will have a map whose [[class]] is
7806 // set to 'value', but there is no guarantees on instances created
7808 void SetInstanceClassName(String* name);
7810 // Returns if this function has been compiled to native code yet.
7811 inline bool is_compiled();
7813 // [next_function_link]: Links functions into various lists, e.g. the list
7814 // of optimized functions hanging off the native_context. The CodeFlusher
7815 // uses this link to chain together flushing candidates. Treated weakly
7816 // by the garbage collector.
7817 DECL_ACCESSORS(next_function_link, Object)
7819 // Prints the name of the function using PrintF.
7820 void PrintName(FILE* out = stdout);
7822 DECLARE_CAST(JSFunction)
7824 // Iterates the objects, including code objects indirectly referenced
7825 // through pointers to the first instruction in the code object.
7826 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
7828 // Dispatched behavior.
7829 DECLARE_PRINTER(JSFunction)
7830 DECLARE_VERIFIER(JSFunction)
7832 // Returns the number of allocated literals.
7833 inline int NumberOfLiterals();
7835 // Retrieve the native context from a function's literal array.
7836 static Context* NativeContextFromLiterals(FixedArray* literals);
7838 // Used for flags such as --hydrogen-filter.
7839 bool PassesFilter(const char* raw_filter);
7841 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
7842 // kSize) is weak and has special handling during garbage collection.
7843 static const int kCodeEntryOffset = JSObject::kHeaderSize;
7844 static const int kPrototypeOrInitialMapOffset =
7845 kCodeEntryOffset + kPointerSize;
7846 static const int kSharedFunctionInfoOffset =
7847 kPrototypeOrInitialMapOffset + kPointerSize;
7848 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
7849 static const int kLiteralsOffset = kContextOffset + kPointerSize;
7850 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
7851 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
7852 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
7854 // Layout of the literals array.
7855 static const int kLiteralsPrefixSize = 1;
7856 static const int kLiteralNativeContextIndex = 0;
7858 // Layout of the bound-function binding array.
7859 static const int kBoundFunctionIndex = 0;
7860 static const int kBoundThisIndex = 1;
7861 static const int kBoundArgumentsStartIndex = 2;
7864 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7868 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7869 // and the prototype is hidden. JSGlobalProxy always delegates
7870 // property accesses to its prototype if the prototype is not null.
7872 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7874 // Accessing a JSGlobalProxy requires security check.
7876 class JSGlobalProxy : public JSObject {
7878 // [native_context]: the owner native context of this global proxy object.
7879 // It is null value if this object is not used by any context.
7880 DECL_ACCESSORS(native_context, Object)
7882 // [hash]: The hash code property (undefined if not initialized yet).
7883 DECL_ACCESSORS(hash, Object)
7885 DECLARE_CAST(JSGlobalProxy)
7887 inline bool IsDetachedFrom(GlobalObject* global) const;
7889 // Dispatched behavior.
7890 DECLARE_PRINTER(JSGlobalProxy)
7891 DECLARE_VERIFIER(JSGlobalProxy)
7893 // Layout description.
7894 static const int kNativeContextOffset = JSObject::kHeaderSize;
7895 static const int kHashOffset = kNativeContextOffset + kPointerSize;
7896 static const int kSize = kHashOffset + kPointerSize;
7899 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7903 // Forward declaration.
7904 class JSBuiltinsObject;
7906 // Common super class for JavaScript global objects and the special
7907 // builtins global objects.
7908 class GlobalObject: public JSObject {
7910 // [builtins]: the object holding the runtime routines written in JS.
7911 DECL_ACCESSORS(builtins, JSBuiltinsObject)
7913 // [native context]: the natives corresponding to this global object.
7914 DECL_ACCESSORS(native_context, Context)
7916 // [global context]: the most recent (i.e. innermost) global context.
7917 DECL_ACCESSORS(global_context, Context)
7919 // [global proxy]: the global proxy object of the context
7920 DECL_ACCESSORS(global_proxy, JSObject)
7922 // Retrieve the property cell used to store a property.
7923 PropertyCell* GetPropertyCell(LookupResult* result);
7925 DECLARE_CAST(GlobalObject)
7927 // Layout description.
7928 static const int kBuiltinsOffset = JSObject::kHeaderSize;
7929 static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7930 static const int kGlobalContextOffset = kNativeContextOffset + kPointerSize;
7931 static const int kGlobalProxyOffset = kGlobalContextOffset + kPointerSize;
7932 static const int kHeaderSize = kGlobalProxyOffset + kPointerSize;
7935 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7939 // JavaScript global object.
7940 class JSGlobalObject: public GlobalObject {
7942 DECLARE_CAST(JSGlobalObject)
7944 // Ensure that the global object has a cell for the given property name.
7945 static Handle<PropertyCell> EnsurePropertyCell(Handle<JSGlobalObject> global,
7948 inline bool IsDetached();
7950 // Dispatched behavior.
7951 DECLARE_PRINTER(JSGlobalObject)
7952 DECLARE_VERIFIER(JSGlobalObject)
7954 // Layout description.
7955 static const int kSize = GlobalObject::kHeaderSize;
7958 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7962 // Builtins global object which holds the runtime routines written in
7964 class JSBuiltinsObject: public GlobalObject {
7966 // Accessors for the runtime routines written in JavaScript.
7967 inline Object* javascript_builtin(Builtins::JavaScript id);
7968 inline void set_javascript_builtin(Builtins::JavaScript id, Object* value);
7970 // Accessors for code of the runtime routines written in JavaScript.
7971 inline Code* javascript_builtin_code(Builtins::JavaScript id);
7972 inline void set_javascript_builtin_code(Builtins::JavaScript id, Code* value);
7974 DECLARE_CAST(JSBuiltinsObject)
7976 // Dispatched behavior.
7977 DECLARE_PRINTER(JSBuiltinsObject)
7978 DECLARE_VERIFIER(JSBuiltinsObject)
7980 // Layout description. The size of the builtins object includes
7981 // room for two pointers per runtime routine written in javascript
7982 // (function and code object).
7983 static const int kJSBuiltinsCount = Builtins::id_count;
7984 static const int kJSBuiltinsOffset = GlobalObject::kHeaderSize;
7985 static const int kJSBuiltinsCodeOffset =
7986 GlobalObject::kHeaderSize + (kJSBuiltinsCount * kPointerSize);
7987 static const int kSize =
7988 kJSBuiltinsCodeOffset + (kJSBuiltinsCount * kPointerSize);
7990 static int OffsetOfFunctionWithId(Builtins::JavaScript id) {
7991 return kJSBuiltinsOffset + id * kPointerSize;
7994 static int OffsetOfCodeWithId(Builtins::JavaScript id) {
7995 return kJSBuiltinsCodeOffset + id * kPointerSize;
7999 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
8003 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
8004 class JSValue: public JSObject {
8006 // [value]: the object being wrapped.
8007 DECL_ACCESSORS(value, Object)
8009 DECLARE_CAST(JSValue)
8011 // Dispatched behavior.
8012 DECLARE_PRINTER(JSValue)
8013 DECLARE_VERIFIER(JSValue)
8015 // Layout description.
8016 static const int kValueOffset = JSObject::kHeaderSize;
8017 static const int kSize = kValueOffset + kPointerSize;
8020 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
8026 // Representation for JS date objects.
8027 class JSDate: public JSObject {
8029 // If one component is NaN, all of them are, indicating a NaN time value.
8030 // [value]: the time value.
8031 DECL_ACCESSORS(value, Object)
8032 // [year]: caches year. Either undefined, smi, or NaN.
8033 DECL_ACCESSORS(year, Object)
8034 // [month]: caches month. Either undefined, smi, or NaN.
8035 DECL_ACCESSORS(month, Object)
8036 // [day]: caches day. Either undefined, smi, or NaN.
8037 DECL_ACCESSORS(day, Object)
8038 // [weekday]: caches day of week. Either undefined, smi, or NaN.
8039 DECL_ACCESSORS(weekday, Object)
8040 // [hour]: caches hours. Either undefined, smi, or NaN.
8041 DECL_ACCESSORS(hour, Object)
8042 // [min]: caches minutes. Either undefined, smi, or NaN.
8043 DECL_ACCESSORS(min, Object)
8044 // [sec]: caches seconds. Either undefined, smi, or NaN.
8045 DECL_ACCESSORS(sec, Object)
8046 // [cache stamp]: sample of the date cache stamp at the
8047 // moment when chached fields were cached.
8048 DECL_ACCESSORS(cache_stamp, Object)
8050 DECLARE_CAST(JSDate)
8052 // Returns the date field with the specified index.
8053 // See FieldIndex for the list of date fields.
8054 static Object* GetField(Object* date, Smi* index);
8056 void SetValue(Object* value, bool is_value_nan);
8059 // Dispatched behavior.
8060 DECLARE_PRINTER(JSDate)
8061 DECLARE_VERIFIER(JSDate)
8063 // The order is important. It must be kept in sync with date macros
8074 kFirstUncachedField,
8075 kMillisecond = kFirstUncachedField,
8079 kYearUTC = kFirstUTCField,
8092 // Layout description.
8093 static const int kValueOffset = JSObject::kHeaderSize;
8094 static const int kYearOffset = kValueOffset + kPointerSize;
8095 static const int kMonthOffset = kYearOffset + kPointerSize;
8096 static const int kDayOffset = kMonthOffset + kPointerSize;
8097 static const int kWeekdayOffset = kDayOffset + kPointerSize;
8098 static const int kHourOffset = kWeekdayOffset + kPointerSize;
8099 static const int kMinOffset = kHourOffset + kPointerSize;
8100 static const int kSecOffset = kMinOffset + kPointerSize;
8101 static const int kCacheStampOffset = kSecOffset + kPointerSize;
8102 static const int kSize = kCacheStampOffset + kPointerSize;
8105 inline Object* DoGetField(FieldIndex index);
8107 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
8109 // Computes and caches the cacheable fields of the date.
8110 inline void SetCachedFields(int64_t local_time_ms, DateCache* date_cache);
8113 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
8117 // Representation of message objects used for error reporting through
8118 // the API. The messages are formatted in JavaScript so this object is
8119 // a real JavaScript object. The information used for formatting the
8120 // error messages are not directly accessible from JavaScript to
8121 // prevent leaking information to user code called during error
8123 class JSMessageObject: public JSObject {
8125 // [type]: the type of error message.
8126 DECL_ACCESSORS(type, String)
8128 // [arguments]: the arguments for formatting the error message.
8129 DECL_ACCESSORS(arguments, JSArray)
8131 // [script]: the script from which the error message originated.
8132 DECL_ACCESSORS(script, Object)
8134 // [stack_frames]: an array of stack frames for this error object.
8135 DECL_ACCESSORS(stack_frames, Object)
8137 // [start_position]: the start position in the script for the error message.
8138 inline int start_position() const;
8139 inline void set_start_position(int value);
8141 // [end_position]: the end position in the script for the error message.
8142 inline int end_position() const;
8143 inline void set_end_position(int value);
8145 DECLARE_CAST(JSMessageObject)
8147 // Dispatched behavior.
8148 DECLARE_PRINTER(JSMessageObject)
8149 DECLARE_VERIFIER(JSMessageObject)
8151 // Layout description.
8152 static const int kTypeOffset = JSObject::kHeaderSize;
8153 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
8154 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
8155 static const int kStackFramesOffset = kScriptOffset + kPointerSize;
8156 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
8157 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
8158 static const int kSize = kEndPositionOffset + kPointerSize;
8160 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
8161 kStackFramesOffset + kPointerSize,
8162 kSize> BodyDescriptor;
8166 // Regular expressions
8167 // The regular expression holds a single reference to a FixedArray in
8168 // the kDataOffset field.
8169 // The FixedArray contains the following data:
8170 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
8171 // - reference to the original source string
8172 // - reference to the original flag string
8173 // If it is an atom regexp
8174 // - a reference to a literal string to search for
8175 // If it is an irregexp regexp:
8176 // - a reference to code for ASCII inputs (bytecode or compiled), or a smi
8177 // used for tracking the last usage (used for code flushing).
8178 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
8179 // used for tracking the last usage (used for code flushing)..
8180 // - max number of registers used by irregexp implementations.
8181 // - number of capture registers (output values) of the regexp.
8182 class JSRegExp: public JSObject {
8185 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
8186 // ATOM: A simple string to match against using an indexOf operation.
8187 // IRREGEXP: Compiled with Irregexp.
8188 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
8189 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
8190 enum Flag { NONE = 0, GLOBAL = 1, IGNORE_CASE = 2, MULTILINE = 4 };
8194 explicit Flags(uint32_t value) : value_(value) { }
8195 bool is_global() { return (value_ & GLOBAL) != 0; }
8196 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
8197 bool is_multiline() { return (value_ & MULTILINE) != 0; }
8198 uint32_t value() { return value_; }
8203 DECL_ACCESSORS(data, Object)
8205 inline Type TypeTag();
8206 inline int CaptureCount();
8207 inline Flags GetFlags();
8208 inline String* Pattern();
8209 inline Object* DataAt(int index);
8210 // Set implementation data after the object has been prepared.
8211 inline void SetDataAt(int index, Object* value);
8213 static int code_index(bool is_ascii) {
8215 return kIrregexpASCIICodeIndex;
8217 return kIrregexpUC16CodeIndex;
8221 static int saved_code_index(bool is_ascii) {
8223 return kIrregexpASCIICodeSavedIndex;
8225 return kIrregexpUC16CodeSavedIndex;
8229 DECLARE_CAST(JSRegExp)
8231 // Dispatched behavior.
8232 DECLARE_VERIFIER(JSRegExp)
8234 static const int kDataOffset = JSObject::kHeaderSize;
8235 static const int kSize = kDataOffset + kPointerSize;
8237 // Indices in the data array.
8238 static const int kTagIndex = 0;
8239 static const int kSourceIndex = kTagIndex + 1;
8240 static const int kFlagsIndex = kSourceIndex + 1;
8241 static const int kDataIndex = kFlagsIndex + 1;
8242 // The data fields are used in different ways depending on the
8243 // value of the tag.
8244 // Atom regexps (literal strings).
8245 static const int kAtomPatternIndex = kDataIndex;
8247 static const int kAtomDataSize = kAtomPatternIndex + 1;
8249 // Irregexp compiled code or bytecode for ASCII. If compilation
8250 // fails, this fields hold an exception object that should be
8251 // thrown if the regexp is used again.
8252 static const int kIrregexpASCIICodeIndex = kDataIndex;
8253 // Irregexp compiled code or bytecode for UC16. If compilation
8254 // fails, this fields hold an exception object that should be
8255 // thrown if the regexp is used again.
8256 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
8258 // Saved instance of Irregexp compiled code or bytecode for ASCII that
8259 // is a potential candidate for flushing.
8260 static const int kIrregexpASCIICodeSavedIndex = kDataIndex + 2;
8261 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
8262 // a potential candidate for flushing.
8263 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
8265 // Maximal number of registers used by either ASCII or UC16.
8266 // Only used to check that there is enough stack space
8267 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
8268 // Number of captures in the compiled regexp.
8269 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
8271 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
8273 // Offsets directly into the data fixed array.
8274 static const int kDataTagOffset =
8275 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
8276 static const int kDataAsciiCodeOffset =
8277 FixedArray::kHeaderSize + kIrregexpASCIICodeIndex * kPointerSize;
8278 static const int kDataUC16CodeOffset =
8279 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
8280 static const int kIrregexpCaptureCountOffset =
8281 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
8283 // In-object fields.
8284 static const int kSourceFieldIndex = 0;
8285 static const int kGlobalFieldIndex = 1;
8286 static const int kIgnoreCaseFieldIndex = 2;
8287 static const int kMultilineFieldIndex = 3;
8288 static const int kLastIndexFieldIndex = 4;
8289 static const int kInObjectFieldCount = 5;
8291 // The uninitialized value for a regexp code object.
8292 static const int kUninitializedValue = -1;
8294 // The compilation error value for the regexp code object. The real error
8295 // object is in the saved code field.
8296 static const int kCompilationErrorValue = -2;
8298 // When we store the sweep generation at which we moved the code from the
8299 // code index to the saved code index we mask it of to be in the [0:255]
8301 static const int kCodeAgeMask = 0xff;
8305 class CompilationCacheShape : public BaseShape<HashTableKey*> {
8307 static inline bool IsMatch(HashTableKey* key, Object* value) {
8308 return key->IsMatch(value);
8311 static inline uint32_t Hash(HashTableKey* key) {
8315 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
8316 return key->HashForObject(object);
8319 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
8321 static const int kPrefixSize = 0;
8322 static const int kEntrySize = 2;
8326 class CompilationCacheTable: public HashTable<CompilationCacheTable,
8327 CompilationCacheShape,
8330 // Find cached value for a string key, otherwise return null.
8331 Handle<Object> Lookup(Handle<String> src, Handle<Context> context);
8332 Handle<Object> LookupEval(Handle<String> src, Handle<Context> context,
8333 StrictMode strict_mode, int scope_position);
8334 Handle<Object> LookupRegExp(Handle<String> source, JSRegExp::Flags flags);
8335 static Handle<CompilationCacheTable> Put(
8336 Handle<CompilationCacheTable> cache, Handle<String> src,
8337 Handle<Context> context, Handle<Object> value);
8338 static Handle<CompilationCacheTable> PutEval(
8339 Handle<CompilationCacheTable> cache, Handle<String> src,
8340 Handle<Context> context, Handle<SharedFunctionInfo> value,
8341 int scope_position);
8342 static Handle<CompilationCacheTable> PutRegExp(
8343 Handle<CompilationCacheTable> cache, Handle<String> src,
8344 JSRegExp::Flags flags, Handle<FixedArray> value);
8345 void Remove(Object* value);
8347 DECLARE_CAST(CompilationCacheTable)
8350 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
8354 class CodeCache: public Struct {
8356 DECL_ACCESSORS(default_cache, FixedArray)
8357 DECL_ACCESSORS(normal_type_cache, Object)
8359 // Add the code object to the cache.
8361 Handle<CodeCache> cache, Handle<Name> name, Handle<Code> code);
8363 // Lookup code object in the cache. Returns code object if found and undefined
8365 Object* Lookup(Name* name, Code::Flags flags);
8367 // Get the internal index of a code object in the cache. Returns -1 if the
8368 // code object is not in that cache. This index can be used to later call
8369 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
8371 int GetIndex(Object* name, Code* code);
8373 // Remove an object from the cache with the provided internal index.
8374 void RemoveByIndex(Object* name, Code* code, int index);
8376 DECLARE_CAST(CodeCache)
8378 // Dispatched behavior.
8379 DECLARE_PRINTER(CodeCache)
8380 DECLARE_VERIFIER(CodeCache)
8382 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
8383 static const int kNormalTypeCacheOffset =
8384 kDefaultCacheOffset + kPointerSize;
8385 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
8388 static void UpdateDefaultCache(
8389 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
8390 static void UpdateNormalTypeCache(
8391 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
8392 Object* LookupDefaultCache(Name* name, Code::Flags flags);
8393 Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
8395 // Code cache layout of the default cache. Elements are alternating name and
8396 // code objects for non normal load/store/call IC's.
8397 static const int kCodeCacheEntrySize = 2;
8398 static const int kCodeCacheEntryNameOffset = 0;
8399 static const int kCodeCacheEntryCodeOffset = 1;
8401 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
8405 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
8407 static inline bool IsMatch(HashTableKey* key, Object* value) {
8408 return key->IsMatch(value);
8411 static inline uint32_t Hash(HashTableKey* key) {
8415 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
8416 return key->HashForObject(object);
8419 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
8421 static const int kPrefixSize = 0;
8422 static const int kEntrySize = 2;
8426 class CodeCacheHashTable: public HashTable<CodeCacheHashTable,
8427 CodeCacheHashTableShape,
8430 Object* Lookup(Name* name, Code::Flags flags);
8431 static Handle<CodeCacheHashTable> Put(
8432 Handle<CodeCacheHashTable> table,
8436 int GetIndex(Name* name, Code::Flags flags);
8437 void RemoveByIndex(int index);
8439 DECLARE_CAST(CodeCacheHashTable)
8441 // Initial size of the fixed array backing the hash table.
8442 static const int kInitialSize = 64;
8445 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
8449 class PolymorphicCodeCache: public Struct {
8451 DECL_ACCESSORS(cache, Object)
8453 static void Update(Handle<PolymorphicCodeCache> cache,
8454 MapHandleList* maps,
8459 // Returns an undefined value if the entry is not found.
8460 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
8462 DECLARE_CAST(PolymorphicCodeCache)
8464 // Dispatched behavior.
8465 DECLARE_PRINTER(PolymorphicCodeCache)
8466 DECLARE_VERIFIER(PolymorphicCodeCache)
8468 static const int kCacheOffset = HeapObject::kHeaderSize;
8469 static const int kSize = kCacheOffset + kPointerSize;
8472 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
8476 class PolymorphicCodeCacheHashTable
8477 : public HashTable<PolymorphicCodeCacheHashTable,
8478 CodeCacheHashTableShape,
8481 Object* Lookup(MapHandleList* maps, int code_kind);
8483 static Handle<PolymorphicCodeCacheHashTable> Put(
8484 Handle<PolymorphicCodeCacheHashTable> hash_table,
8485 MapHandleList* maps,
8489 DECLARE_CAST(PolymorphicCodeCacheHashTable)
8491 static const int kInitialSize = 64;
8493 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
8497 class TypeFeedbackInfo: public Struct {
8499 inline int ic_total_count();
8500 inline void set_ic_total_count(int count);
8502 inline int ic_with_type_info_count();
8503 inline void change_ic_with_type_info_count(int delta);
8505 inline int ic_generic_count();
8506 inline void change_ic_generic_count(int delta);
8508 inline void initialize_storage();
8510 inline void change_own_type_change_checksum();
8511 inline int own_type_change_checksum();
8513 inline void set_inlined_type_change_checksum(int checksum);
8514 inline bool matches_inlined_type_change_checksum(int checksum);
8517 DECLARE_CAST(TypeFeedbackInfo)
8519 // Dispatched behavior.
8520 DECLARE_PRINTER(TypeFeedbackInfo)
8521 DECLARE_VERIFIER(TypeFeedbackInfo)
8523 static const int kStorage1Offset = HeapObject::kHeaderSize;
8524 static const int kStorage2Offset = kStorage1Offset + kPointerSize;
8525 static const int kStorage3Offset = kStorage2Offset + kPointerSize;
8526 static const int kSize = kStorage3Offset + kPointerSize;
8528 // TODO(mvstanton): move these sentinel declarations to shared function info.
8529 // The object that indicates an uninitialized cache.
8530 static inline Handle<Object> UninitializedSentinel(Isolate* isolate);
8532 // The object that indicates a megamorphic state.
8533 static inline Handle<Object> MegamorphicSentinel(Isolate* isolate);
8535 // The object that indicates a monomorphic state of Array with
8537 static inline Handle<Object> MonomorphicArraySentinel(Isolate* isolate,
8538 ElementsKind elements_kind);
8540 // A raw version of the uninitialized sentinel that's safe to read during
8541 // garbage collection (e.g., for patching the cache).
8542 static inline Object* RawUninitializedSentinel(Heap* heap);
8545 static const int kTypeChangeChecksumBits = 7;
8547 class ICTotalCountField: public BitField<int, 0,
8548 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
8549 class OwnTypeChangeChecksum: public BitField<int,
8550 kSmiValueSize - kTypeChangeChecksumBits,
8551 kTypeChangeChecksumBits> {}; // NOLINT
8552 class ICsWithTypeInfoCountField: public BitField<int, 0,
8553 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
8554 class InlinedTypeChangeChecksum: public BitField<int,
8555 kSmiValueSize - kTypeChangeChecksumBits,
8556 kTypeChangeChecksumBits> {}; // NOLINT
8558 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
8562 enum AllocationSiteMode {
8563 DONT_TRACK_ALLOCATION_SITE,
8564 TRACK_ALLOCATION_SITE,
8565 LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
8569 class AllocationSite: public Struct {
8571 static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
8572 static const double kPretenureRatio;
8573 static const int kPretenureMinimumCreated = 100;
8575 // Values for pretenure decision field.
8576 enum PretenureDecision {
8582 kLastPretenureDecisionValue = kZombie
8585 const char* PretenureDecisionName(PretenureDecision decision);
8587 DECL_ACCESSORS(transition_info, Object)
8588 // nested_site threads a list of sites that represent nested literals
8589 // walked in a particular order. So [[1, 2], 1, 2] will have one
8590 // nested_site, but [[1, 2], 3, [4]] will have a list of two.
8591 DECL_ACCESSORS(nested_site, Object)
8592 DECL_ACCESSORS(pretenure_data, Smi)
8593 DECL_ACCESSORS(pretenure_create_count, Smi)
8594 DECL_ACCESSORS(dependent_code, DependentCode)
8595 DECL_ACCESSORS(weak_next, Object)
8597 inline void Initialize();
8599 // This method is expensive, it should only be called for reporting.
8600 bool IsNestedSite();
8602 // transition_info bitfields, for constructed array transition info.
8603 class ElementsKindBits: public BitField<ElementsKind, 0, 15> {};
8604 class UnusedBits: public BitField<int, 15, 14> {};
8605 class DoNotInlineBit: public BitField<bool, 29, 1> {};
8607 // Bitfields for pretenure_data
8608 class MementoFoundCountBits: public BitField<int, 0, 26> {};
8609 class PretenureDecisionBits: public BitField<PretenureDecision, 26, 3> {};
8610 class DeoptDependentCodeBit: public BitField<bool, 29, 1> {};
8611 STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
8613 // Increments the mementos found counter and returns true when the first
8614 // memento was found for a given allocation site.
8615 inline bool IncrementMementoFoundCount();
8617 inline void IncrementMementoCreateCount();
8619 PretenureFlag GetPretenureMode();
8621 void ResetPretenureDecision();
8623 PretenureDecision pretenure_decision() {
8624 int value = pretenure_data()->value();
8625 return PretenureDecisionBits::decode(value);
8628 void set_pretenure_decision(PretenureDecision decision) {
8629 int value = pretenure_data()->value();
8631 Smi::FromInt(PretenureDecisionBits::update(value, decision)),
8632 SKIP_WRITE_BARRIER);
8635 bool deopt_dependent_code() {
8636 int value = pretenure_data()->value();
8637 return DeoptDependentCodeBit::decode(value);
8640 void set_deopt_dependent_code(bool deopt) {
8641 int value = pretenure_data()->value();
8643 Smi::FromInt(DeoptDependentCodeBit::update(value, deopt)),
8644 SKIP_WRITE_BARRIER);
8647 int memento_found_count() {
8648 int value = pretenure_data()->value();
8649 return MementoFoundCountBits::decode(value);
8652 inline void set_memento_found_count(int count);
8654 int memento_create_count() {
8655 return pretenure_create_count()->value();
8658 void set_memento_create_count(int count) {
8659 set_pretenure_create_count(Smi::FromInt(count), SKIP_WRITE_BARRIER);
8662 // The pretenuring decision is made during gc, and the zombie state allows
8663 // us to recognize when an allocation site is just being kept alive because
8664 // a later traversal of new space may discover AllocationMementos that point
8665 // to this AllocationSite.
8667 return pretenure_decision() == kZombie;
8670 bool IsMaybeTenure() {
8671 return pretenure_decision() == kMaybeTenure;
8674 inline void MarkZombie();
8676 inline bool MakePretenureDecision(PretenureDecision current_decision,
8678 bool maximum_size_scavenge);
8680 inline bool DigestPretenuringFeedback(bool maximum_size_scavenge);
8682 ElementsKind GetElementsKind() {
8683 DCHECK(!SitePointsToLiteral());
8684 int value = Smi::cast(transition_info())->value();
8685 return ElementsKindBits::decode(value);
8688 void SetElementsKind(ElementsKind kind) {
8689 int value = Smi::cast(transition_info())->value();
8690 set_transition_info(Smi::FromInt(ElementsKindBits::update(value, kind)),
8691 SKIP_WRITE_BARRIER);
8694 bool CanInlineCall() {
8695 int value = Smi::cast(transition_info())->value();
8696 return DoNotInlineBit::decode(value) == 0;
8699 void SetDoNotInlineCall() {
8700 int value = Smi::cast(transition_info())->value();
8701 set_transition_info(Smi::FromInt(DoNotInlineBit::update(value, true)),
8702 SKIP_WRITE_BARRIER);
8705 bool SitePointsToLiteral() {
8706 // If transition_info is a smi, then it represents an ElementsKind
8707 // for a constructed array. Otherwise, it must be a boilerplate
8708 // for an object or array literal.
8709 return transition_info()->IsJSArray() || transition_info()->IsJSObject();
8712 static void DigestTransitionFeedback(Handle<AllocationSite> site,
8713 ElementsKind to_kind);
8720 static void AddDependentCompilationInfo(Handle<AllocationSite> site,
8722 CompilationInfo* info);
8724 DECLARE_PRINTER(AllocationSite)
8725 DECLARE_VERIFIER(AllocationSite)
8727 DECLARE_CAST(AllocationSite)
8728 static inline AllocationSiteMode GetMode(
8729 ElementsKind boilerplate_elements_kind);
8730 static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
8731 static inline bool CanTrack(InstanceType type);
8733 static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
8734 static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
8735 static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
8736 static const int kPretenureCreateCountOffset =
8737 kPretenureDataOffset + kPointerSize;
8738 static const int kDependentCodeOffset =
8739 kPretenureCreateCountOffset + kPointerSize;
8740 static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
8741 static const int kSize = kWeakNextOffset + kPointerSize;
8743 // During mark compact we need to take special care for the dependent code
8745 static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
8746 static const int kPointerFieldsEndOffset = kDependentCodeOffset;
8748 // For other visitors, use the fixed body descriptor below.
8749 typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
8750 kDependentCodeOffset + kPointerSize,
8751 kSize> BodyDescriptor;
8754 inline DependentCode::DependencyGroup ToDependencyGroup(Reason reason);
8755 bool PretenuringDecisionMade() {
8756 return pretenure_decision() != kUndecided;
8759 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
8763 class AllocationMemento: public Struct {
8765 static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
8766 static const int kSize = kAllocationSiteOffset + kPointerSize;
8768 DECL_ACCESSORS(allocation_site, Object)
8771 return allocation_site()->IsAllocationSite() &&
8772 !AllocationSite::cast(allocation_site())->IsZombie();
8774 AllocationSite* GetAllocationSite() {
8776 return AllocationSite::cast(allocation_site());
8779 DECLARE_PRINTER(AllocationMemento)
8780 DECLARE_VERIFIER(AllocationMemento)
8782 DECLARE_CAST(AllocationMemento)
8785 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
8789 // Representation of a slow alias as part of a sloppy arguments objects.
8790 // For fast aliases (if HasSloppyArgumentsElements()):
8791 // - the parameter map contains an index into the context
8792 // - all attributes of the element have default values
8793 // For slow aliases (if HasDictionaryArgumentsElements()):
8794 // - the parameter map contains no fast alias mapping (i.e. the hole)
8795 // - this struct (in the slow backing store) contains an index into the context
8796 // - all attributes are available as part if the property details
8797 class AliasedArgumentsEntry: public Struct {
8799 inline int aliased_context_slot() const;
8800 inline void set_aliased_context_slot(int count);
8802 DECLARE_CAST(AliasedArgumentsEntry)
8804 // Dispatched behavior.
8805 DECLARE_PRINTER(AliasedArgumentsEntry)
8806 DECLARE_VERIFIER(AliasedArgumentsEntry)
8808 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
8809 static const int kSize = kAliasedContextSlot + kPointerSize;
8812 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
8816 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
8817 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
8820 class StringHasher {
8822 explicit inline StringHasher(int length, uint32_t seed);
8824 template <typename schar>
8825 static inline uint32_t HashSequentialString(const schar* chars,
8829 // Reads all the data, even for long strings and computes the utf16 length.
8830 static uint32_t ComputeUtf8Hash(Vector<const char> chars,
8832 int* utf16_length_out);
8834 // Calculated hash value for a string consisting of 1 to
8835 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
8836 // value is represented decimal value.
8837 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
8839 // No string is allowed to have a hash of zero. That value is reserved
8840 // for internal properties. If the hash calculation yields zero then we
8842 static const int kZeroHash = 27;
8844 // Reusable parts of the hashing algorithm.
8845 INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
8846 INLINE(static uint32_t GetHashCore(uint32_t running_hash));
8849 // Returns the value to store in the hash field of a string with
8850 // the given length and contents.
8851 uint32_t GetHashField();
8852 // Returns true if the hash of this string can be computed without
8853 // looking at the contents.
8854 inline bool has_trivial_hash();
8855 // Adds a block of characters to the hash.
8856 template<typename Char>
8857 inline void AddCharacters(const Char* chars, int len);
8860 // Add a character to the hash.
8861 inline void AddCharacter(uint16_t c);
8862 // Update index. Returns true if string is still an index.
8863 inline bool UpdateIndex(uint16_t c);
8866 uint32_t raw_running_hash_;
8867 uint32_t array_index_;
8868 bool is_array_index_;
8869 bool is_first_char_;
8870 DISALLOW_COPY_AND_ASSIGN(StringHasher);
8874 class IteratingStringHasher : public StringHasher {
8876 static inline uint32_t Hash(String* string, uint32_t seed);
8877 inline void VisitOneByteString(const uint8_t* chars, int length);
8878 inline void VisitTwoByteString(const uint16_t* chars, int length);
8881 inline IteratingStringHasher(int len, uint32_t seed)
8882 : StringHasher(len, seed) {}
8883 DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher);
8887 // The characteristics of a string are stored in its map. Retrieving these
8888 // few bits of information is moderately expensive, involving two memory
8889 // loads where the second is dependent on the first. To improve efficiency
8890 // the shape of the string is given its own class so that it can be retrieved
8891 // once and used for several string operations. A StringShape is small enough
8892 // to be passed by value and is immutable, but be aware that flattening a
8893 // string can potentially alter its shape. Also be aware that a GC caused by
8894 // something else can alter the shape of a string due to ConsString
8895 // shortcutting. Keeping these restrictions in mind has proven to be error-
8896 // prone and so we no longer put StringShapes in variables unless there is a
8897 // concrete performance benefit at that particular point in the code.
8898 class StringShape BASE_EMBEDDED {
8900 inline explicit StringShape(const String* s);
8901 inline explicit StringShape(Map* s);
8902 inline explicit StringShape(InstanceType t);
8903 inline bool IsSequential();
8904 inline bool IsExternal();
8905 inline bool IsCons();
8906 inline bool IsSliced();
8907 inline bool IsIndirect();
8908 inline bool IsExternalAscii();
8909 inline bool IsExternalTwoByte();
8910 inline bool IsSequentialAscii();
8911 inline bool IsSequentialTwoByte();
8912 inline bool IsInternalized();
8913 inline StringRepresentationTag representation_tag();
8914 inline uint32_t encoding_tag();
8915 inline uint32_t full_representation_tag();
8916 inline uint32_t size_tag();
8918 inline uint32_t type() { return type_; }
8919 inline void invalidate() { valid_ = false; }
8920 inline bool valid() { return valid_; }
8922 inline void invalidate() { }
8928 inline void set_valid() { valid_ = true; }
8931 inline void set_valid() { }
8936 // The Name abstract class captures anything that can be used as a property
8937 // name, i.e., strings and symbols. All names store a hash value.
8938 class Name: public HeapObject {
8940 // Get and set the hash field of the name.
8941 inline uint32_t hash_field();
8942 inline void set_hash_field(uint32_t value);
8944 // Tells whether the hash code has been computed.
8945 inline bool HasHashCode();
8947 // Returns a hash value used for the property table
8948 inline uint32_t Hash();
8950 // Equality operations.
8951 inline bool Equals(Name* other);
8952 inline static bool Equals(Handle<Name> one, Handle<Name> two);
8955 inline bool AsArrayIndex(uint32_t* index);
8959 DECLARE_PRINTER(Name)
8961 // Layout description.
8962 static const int kHashFieldOffset = HeapObject::kHeaderSize;
8963 static const int kSize = kHashFieldOffset + kPointerSize;
8965 // Mask constant for checking if a name has a computed hash code
8966 // and if it is a string that is an array index. The least significant bit
8967 // indicates whether a hash code has been computed. If the hash code has
8968 // been computed the 2nd bit tells whether the string can be used as an
8970 static const int kHashNotComputedMask = 1;
8971 static const int kIsNotArrayIndexMask = 1 << 1;
8972 static const int kNofHashBitFields = 2;
8974 // Shift constant retrieving hash code from hash field.
8975 static const int kHashShift = kNofHashBitFields;
8977 // Only these bits are relevant in the hash, since the top two are shifted
8979 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8981 // Array index strings this short can keep their index in the hash field.
8982 static const int kMaxCachedArrayIndexLength = 7;
8984 // For strings which are array indexes the hash value has the string length
8985 // mixed into the hash, mainly to avoid a hash value of zero which would be
8986 // the case for the string '0'. 24 bits are used for the array index value.
8987 static const int kArrayIndexValueBits = 24;
8988 static const int kArrayIndexLengthBits =
8989 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8991 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8993 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8994 kArrayIndexValueBits> {}; // NOLINT
8995 class ArrayIndexLengthBits : public BitField<unsigned int,
8996 kNofHashBitFields + kArrayIndexValueBits,
8997 kArrayIndexLengthBits> {}; // NOLINT
8999 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
9000 // could use a mask to test if the length of string is less than or equal to
9001 // kMaxCachedArrayIndexLength.
9002 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
9004 static const unsigned int kContainsCachedArrayIndexMask =
9005 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
9006 << ArrayIndexLengthBits::kShift) |
9007 kIsNotArrayIndexMask;
9009 // Value of empty hash field indicating that the hash is not computed.
9010 static const int kEmptyHashField =
9011 kIsNotArrayIndexMask | kHashNotComputedMask;
9014 static inline bool IsHashFieldComputed(uint32_t field);
9017 DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
9022 class Symbol: public Name {
9024 // [name]: the print name of a symbol, or undefined if none.
9025 DECL_ACCESSORS(name, Object)
9027 DECL_ACCESSORS(flags, Smi)
9029 // [is_private]: whether this is a private symbol.
9030 DECL_BOOLEAN_ACCESSORS(is_private)
9032 DECLARE_CAST(Symbol)
9034 // Dispatched behavior.
9035 DECLARE_PRINTER(Symbol)
9036 DECLARE_VERIFIER(Symbol)
9038 // Layout description.
9039 static const int kNameOffset = Name::kSize;
9040 static const int kFlagsOffset = kNameOffset + kPointerSize;
9041 static const int kSize = kFlagsOffset + kPointerSize;
9043 typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
9046 static const int kPrivateBit = 0;
9048 DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
9054 // The String abstract class captures JavaScript string values:
9057 // 4.3.16 String Value
9058 // A string value is a member of the type String and is a finite
9059 // ordered sequence of zero or more 16-bit unsigned integer values.
9061 // All string values have a length field.
9062 class String: public Name {
9064 enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
9066 // Array index strings this short can keep their index in the hash field.
9067 static const int kMaxCachedArrayIndexLength = 7;
9069 // For strings which are array indexes the hash value has the string length
9070 // mixed into the hash, mainly to avoid a hash value of zero which would be
9071 // the case for the string '0'. 24 bits are used for the array index value.
9072 static const int kArrayIndexValueBits = 24;
9073 static const int kArrayIndexLengthBits =
9074 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
9076 STATIC_ASSERT((kArrayIndexLengthBits > 0));
9078 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
9079 kArrayIndexValueBits> {}; // NOLINT
9080 class ArrayIndexLengthBits : public BitField<unsigned int,
9081 kNofHashBitFields + kArrayIndexValueBits,
9082 kArrayIndexLengthBits> {}; // NOLINT
9084 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
9085 // could use a mask to test if the length of string is less than or equal to
9086 // kMaxCachedArrayIndexLength.
9087 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
9089 static const unsigned int kContainsCachedArrayIndexMask =
9090 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
9091 << ArrayIndexLengthBits::kShift) |
9092 kIsNotArrayIndexMask;
9094 // Representation of the flat content of a String.
9095 // A non-flat string doesn't have flat content.
9096 // A flat string has content that's encoded as a sequence of either
9097 // ASCII chars or two-byte UC16.
9098 // Returned by String::GetFlatContent().
9101 // Returns true if the string is flat and this structure contains content.
9102 bool IsFlat() { return state_ != NON_FLAT; }
9103 // Returns true if the structure contains ASCII content.
9104 bool IsAscii() { return state_ == ASCII; }
9105 // Returns true if the structure contains two-byte content.
9106 bool IsTwoByte() { return state_ == TWO_BYTE; }
9108 // Return the one byte content of the string. Only use if IsAscii() returns
9110 Vector<const uint8_t> ToOneByteVector() {
9111 DCHECK_EQ(ASCII, state_);
9112 return Vector<const uint8_t>(onebyte_start, length_);
9114 // Return the two-byte content of the string. Only use if IsTwoByte()
9116 Vector<const uc16> ToUC16Vector() {
9117 DCHECK_EQ(TWO_BYTE, state_);
9118 return Vector<const uc16>(twobyte_start, length_);
9122 DCHECK(i < length_);
9123 DCHECK(state_ != NON_FLAT);
9124 if (state_ == ASCII) return onebyte_start[i];
9125 return twobyte_start[i];
9129 enum State { NON_FLAT, ASCII, TWO_BYTE };
9131 // Constructors only used by String::GetFlatContent().
9132 explicit FlatContent(const uint8_t* start, int length)
9133 : onebyte_start(start), length_(length), state_(ASCII) { }
9134 explicit FlatContent(const uc16* start, int length)
9135 : twobyte_start(start), length_(length), state_(TWO_BYTE) { }
9136 FlatContent() : onebyte_start(NULL), length_(0), state_(NON_FLAT) { }
9139 const uint8_t* onebyte_start;
9140 const uc16* twobyte_start;
9145 friend class String;
9148 // Get and set the length of the string.
9149 inline int length() const;
9150 inline void set_length(int value);
9152 // Get and set the length of the string using acquire loads and release
9154 inline int synchronized_length() const;
9155 inline void synchronized_set_length(int value);
9157 // Returns whether this string has only ASCII chars, i.e. all of them can
9158 // be ASCII encoded. This might be the case even if the string is
9159 // two-byte. Such strings may appear when the embedder prefers
9160 // two-byte external representations even for ASCII data.
9161 inline bool IsOneByteRepresentation() const;
9162 inline bool IsTwoByteRepresentation() const;
9164 // Cons and slices have an encoding flag that may not represent the actual
9165 // encoding of the underlying string. This is taken into account here.
9166 // Requires: this->IsFlat()
9167 inline bool IsOneByteRepresentationUnderneath();
9168 inline bool IsTwoByteRepresentationUnderneath();
9170 // NOTE: this should be considered only a hint. False negatives are
9172 inline bool HasOnlyOneByteChars();
9174 // Get and set individual two byte chars in the string.
9175 inline void Set(int index, uint16_t value);
9176 // Get individual two byte char in the string. Repeated calls
9177 // to this method are not efficient unless the string is flat.
9178 INLINE(uint16_t Get(int index));
9180 // Flattens the string. Checks first inline to see if it is
9181 // necessary. Does nothing if the string is not a cons string.
9182 // Flattening allocates a sequential string with the same data as
9183 // the given string and mutates the cons string to a degenerate
9184 // form, where the first component is the new sequential string and
9185 // the second component is the empty string. If allocation fails,
9186 // this function returns a failure. If flattening succeeds, this
9187 // function returns the sequential string that is now the first
9188 // component of the cons string.
9190 // Degenerate cons strings are handled specially by the garbage
9191 // collector (see IsShortcutCandidate).
9193 static inline Handle<String> Flatten(Handle<String> string,
9194 PretenureFlag pretenure = NOT_TENURED);
9196 // Tries to return the content of a flat string as a structure holding either
9197 // a flat vector of char or of uc16.
9198 // If the string isn't flat, and therefore doesn't have flat content, the
9199 // returned structure will report so, and can't provide a vector of either
9201 FlatContent GetFlatContent();
9203 // Returns the parent of a sliced string or first part of a flat cons string.
9204 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
9205 inline String* GetUnderlying();
9207 // Mark the string as an undetectable object. It only applies to
9208 // ASCII and two byte string types.
9209 bool MarkAsUndetectable();
9211 // String equality operations.
9212 inline bool Equals(String* other);
9213 inline static bool Equals(Handle<String> one, Handle<String> two);
9214 bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
9215 bool IsOneByteEqualTo(Vector<const uint8_t> str);
9216 bool IsTwoByteEqualTo(Vector<const uc16> str);
9218 // Return a UTF8 representation of the string. The string is null
9219 // terminated but may optionally contain nulls. Length is returned
9220 // in length_output if length_output is not a null pointer The string
9221 // should be nearly flat, otherwise the performance of this method may
9222 // be very slow (quadratic in the length). Setting robustness_flag to
9223 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
9224 // handles unexpected data without causing assert failures and it does not
9225 // do any heap allocations. This is useful when printing stack traces.
9226 SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
9227 RobustnessFlag robustness_flag,
9230 int* length_output = 0);
9231 SmartArrayPointer<char> ToCString(
9232 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
9233 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
9234 int* length_output = 0);
9236 // Return a 16 bit Unicode representation of the string.
9237 // The string should be nearly flat, otherwise the performance of
9238 // of this method may be very bad. Setting robustness_flag to
9239 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
9240 // handles unexpected data without causing assert failures and it does not
9241 // do any heap allocations. This is useful when printing stack traces.
9242 SmartArrayPointer<uc16> ToWideCString(
9243 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
9245 bool ComputeArrayIndex(uint32_t* index);
9248 bool MakeExternal(v8::String::ExternalStringResource* resource);
9249 bool MakeExternal(v8::String::ExternalAsciiStringResource* resource);
9252 inline bool AsArrayIndex(uint32_t* index);
9254 DECLARE_CAST(String)
9256 void PrintOn(FILE* out);
9258 // For use during stack traces. Performs rudimentary sanity check.
9261 // Dispatched behavior.
9262 void StringShortPrint(StringStream* accumulator);
9263 void PrintUC16(OStream& os, int start = 0, int end = -1); // NOLINT
9265 char* ToAsciiArray();
9267 DECLARE_PRINTER(String)
9268 DECLARE_VERIFIER(String)
9270 inline bool IsFlat();
9272 // Layout description.
9273 static const int kLengthOffset = Name::kSize;
9274 static const int kSize = kLengthOffset + kPointerSize;
9276 // Maximum number of characters to consider when trying to convert a string
9277 // value into an array index.
9278 static const int kMaxArrayIndexSize = 10;
9279 STATIC_ASSERT(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
9282 static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
9283 static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
9284 static const int kMaxUtf16CodeUnit = 0xffff;
9285 static const uint32_t kMaxUtf16CodeUnitU = kMaxUtf16CodeUnit;
9287 // Value of hash field containing computed hash equal to zero.
9288 static const int kEmptyStringHash = kIsNotArrayIndexMask;
9290 // Maximal string length.
9291 static const int kMaxLength = (1 << 28) - 16;
9293 // Max length for computing hash. For strings longer than this limit the
9294 // string length is used as the hash value.
9295 static const int kMaxHashCalcLength = 16383;
9297 // Limit for truncation in short printing.
9298 static const int kMaxShortPrintLength = 1024;
9300 // Support for regular expressions.
9301 const uc16* GetTwoByteData(unsigned start);
9303 // Helper function for flattening strings.
9304 template <typename sinkchar>
9305 static void WriteToFlat(String* source,
9310 // The return value may point to the first aligned word containing the
9311 // first non-ascii character, rather than directly to the non-ascii character.
9312 // If the return value is >= the passed length, the entire string was ASCII.
9313 static inline int NonAsciiStart(const char* chars, int length) {
9314 const char* start = chars;
9315 const char* limit = chars + length;
9316 #ifdef V8_HOST_CAN_READ_UNALIGNED
9317 DCHECK(unibrow::Utf8::kMaxOneByteChar == 0x7F);
9318 const uintptr_t non_ascii_mask = kUintptrAllBitsSet / 0xFF * 0x80;
9319 while (chars + sizeof(uintptr_t) <= limit) {
9320 if (*reinterpret_cast<const uintptr_t*>(chars) & non_ascii_mask) {
9321 return static_cast<int>(chars - start);
9323 chars += sizeof(uintptr_t);
9326 while (chars < limit) {
9327 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
9328 return static_cast<int>(chars - start);
9332 return static_cast<int>(chars - start);
9335 static inline bool IsAscii(const char* chars, int length) {
9336 return NonAsciiStart(chars, length) >= length;
9339 static inline bool IsAscii(const uint8_t* chars, int length) {
9341 NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
9344 static inline int NonOneByteStart(const uc16* chars, int length) {
9345 const uc16* limit = chars + length;
9346 const uc16* start = chars;
9347 while (chars < limit) {
9348 if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
9351 return static_cast<int>(chars - start);
9354 static inline bool IsOneByte(const uc16* chars, int length) {
9355 return NonOneByteStart(chars, length) >= length;
9358 template<class Visitor>
9359 static inline ConsString* VisitFlat(Visitor* visitor,
9363 static Handle<FixedArray> CalculateLineEnds(Handle<String> string,
9364 bool include_ending_line);
9366 // Use the hash field to forward to the canonical internalized string
9367 // when deserializing an internalized string.
9368 inline void SetForwardedInternalizedString(String* string);
9369 inline String* GetForwardedInternalizedString();
9373 friend class StringTableInsertionKey;
9375 static Handle<String> SlowFlatten(Handle<ConsString> cons,
9376 PretenureFlag tenure);
9378 // Slow case of String::Equals. This implementation works on any strings
9379 // but it is most efficient on strings that are almost flat.
9380 bool SlowEquals(String* other);
9382 static bool SlowEquals(Handle<String> one, Handle<String> two);
9384 // Slow case of AsArrayIndex.
9385 bool SlowAsArrayIndex(uint32_t* index);
9387 // Compute and set the hash code.
9388 uint32_t ComputeAndSetHash();
9390 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
9394 // The SeqString abstract class captures sequential string values.
9395 class SeqString: public String {
9397 DECLARE_CAST(SeqString)
9399 // Layout description.
9400 static const int kHeaderSize = String::kSize;
9402 // Truncate the string in-place if possible and return the result.
9403 // In case of new_length == 0, the empty string is returned without
9404 // truncating the original string.
9405 MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
9408 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
9412 // The AsciiString class captures sequential ASCII string objects.
9413 // Each character in the AsciiString is an ASCII character.
9414 class SeqOneByteString: public SeqString {
9416 static const bool kHasAsciiEncoding = true;
9418 // Dispatched behavior.
9419 inline uint16_t SeqOneByteStringGet(int index);
9420 inline void SeqOneByteStringSet(int index, uint16_t value);
9422 // Get the address of the characters in this string.
9423 inline Address GetCharsAddress();
9425 inline uint8_t* GetChars();
9427 DECLARE_CAST(SeqOneByteString)
9429 // Garbage collection support. This method is called by the
9430 // garbage collector to compute the actual size of an AsciiString
9432 inline int SeqOneByteStringSize(InstanceType instance_type);
9434 // Computes the size for an AsciiString instance of a given length.
9435 static int SizeFor(int length) {
9436 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
9439 // Maximal memory usage for a single sequential ASCII string.
9440 static const int kMaxSize = 512 * MB - 1;
9441 STATIC_ASSERT((kMaxSize - kHeaderSize) >= String::kMaxLength);
9444 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
9448 // The TwoByteString class captures sequential unicode string objects.
9449 // Each character in the TwoByteString is a two-byte uint16_t.
9450 class SeqTwoByteString: public SeqString {
9452 static const bool kHasAsciiEncoding = false;
9454 // Dispatched behavior.
9455 inline uint16_t SeqTwoByteStringGet(int index);
9456 inline void SeqTwoByteStringSet(int index, uint16_t value);
9458 // Get the address of the characters in this string.
9459 inline Address GetCharsAddress();
9461 inline uc16* GetChars();
9464 const uint16_t* SeqTwoByteStringGetData(unsigned start);
9466 DECLARE_CAST(SeqTwoByteString)
9468 // Garbage collection support. This method is called by the
9469 // garbage collector to compute the actual size of a TwoByteString
9471 inline int SeqTwoByteStringSize(InstanceType instance_type);
9473 // Computes the size for a TwoByteString instance of a given length.
9474 static int SizeFor(int length) {
9475 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
9478 // Maximal memory usage for a single sequential two-byte string.
9479 static const int kMaxSize = 512 * MB - 1;
9480 STATIC_ASSERT(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
9481 String::kMaxLength);
9484 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
9488 // The ConsString class describes string values built by using the
9489 // addition operator on strings. A ConsString is a pair where the
9490 // first and second components are pointers to other string values.
9491 // One or both components of a ConsString can be pointers to other
9492 // ConsStrings, creating a binary tree of ConsStrings where the leaves
9493 // are non-ConsString string values. The string value represented by
9494 // a ConsString can be obtained by concatenating the leaf string
9495 // values in a left-to-right depth-first traversal of the tree.
9496 class ConsString: public String {
9498 // First string of the cons cell.
9499 inline String* first();
9500 // Doesn't check that the result is a string, even in debug mode. This is
9501 // useful during GC where the mark bits confuse the checks.
9502 inline Object* unchecked_first();
9503 inline void set_first(String* first,
9504 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9506 // Second string of the cons cell.
9507 inline String* second();
9508 // Doesn't check that the result is a string, even in debug mode. This is
9509 // useful during GC where the mark bits confuse the checks.
9510 inline Object* unchecked_second();
9511 inline void set_second(String* second,
9512 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9514 // Dispatched behavior.
9515 uint16_t ConsStringGet(int index);
9517 DECLARE_CAST(ConsString)
9519 // Layout description.
9520 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
9521 static const int kSecondOffset = kFirstOffset + kPointerSize;
9522 static const int kSize = kSecondOffset + kPointerSize;
9524 // Minimum length for a cons string.
9525 static const int kMinLength = 13;
9527 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
9530 DECLARE_VERIFIER(ConsString)
9533 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
9537 // The Sliced String class describes strings that are substrings of another
9538 // sequential string. The motivation is to save time and memory when creating
9539 // a substring. A Sliced String is described as a pointer to the parent,
9540 // the offset from the start of the parent string and the length. Using
9541 // a Sliced String therefore requires unpacking of the parent string and
9542 // adding the offset to the start address. A substring of a Sliced String
9543 // are not nested since the double indirection is simplified when creating
9544 // such a substring.
9545 // Currently missing features are:
9546 // - handling externalized parent strings
9547 // - external strings as parent
9548 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
9549 class SlicedString: public String {
9551 inline String* parent();
9552 inline void set_parent(String* parent,
9553 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9554 inline int offset() const;
9555 inline void set_offset(int offset);
9557 // Dispatched behavior.
9558 uint16_t SlicedStringGet(int index);
9560 DECLARE_CAST(SlicedString)
9562 // Layout description.
9563 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
9564 static const int kOffsetOffset = kParentOffset + kPointerSize;
9565 static const int kSize = kOffsetOffset + kPointerSize;
9567 // Minimum length for a sliced string.
9568 static const int kMinLength = 13;
9570 typedef FixedBodyDescriptor<kParentOffset,
9571 kOffsetOffset + kPointerSize, kSize>
9574 DECLARE_VERIFIER(SlicedString)
9577 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
9581 // The ExternalString class describes string values that are backed by
9582 // a string resource that lies outside the V8 heap. ExternalStrings
9583 // consist of the length field common to all strings, a pointer to the
9584 // external resource. It is important to ensure (externally) that the
9585 // resource is not deallocated while the ExternalString is live in the
9588 // The API expects that all ExternalStrings are created through the
9589 // API. Therefore, ExternalStrings should not be used internally.
9590 class ExternalString: public String {
9592 DECLARE_CAST(ExternalString)
9594 // Layout description.
9595 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
9596 static const int kShortSize = kResourceOffset + kPointerSize;
9597 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
9598 static const int kSize = kResourceDataOffset + kPointerSize;
9600 static const int kMaxShortLength =
9601 (kShortSize - SeqString::kHeaderSize) / kCharSize;
9603 // Return whether external string is short (data pointer is not cached).
9604 inline bool is_short();
9606 STATIC_ASSERT(kResourceOffset == Internals::kStringResourceOffset);
9609 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
9613 // The ExternalAsciiString class is an external string backed by an
9615 class ExternalAsciiString: public ExternalString {
9617 static const bool kHasAsciiEncoding = true;
9619 typedef v8::String::ExternalAsciiStringResource Resource;
9621 // The underlying resource.
9622 inline const Resource* resource();
9623 inline void set_resource(const Resource* buffer);
9625 // Update the pointer cache to the external character array.
9626 // The cached pointer is always valid, as the external character array does =
9627 // not move during lifetime. Deserialization is the only exception, after
9628 // which the pointer cache has to be refreshed.
9629 inline void update_data_cache();
9631 inline const uint8_t* GetChars();
9633 // Dispatched behavior.
9634 inline uint16_t ExternalAsciiStringGet(int index);
9636 DECLARE_CAST(ExternalAsciiString)
9638 // Garbage collection support.
9639 inline void ExternalAsciiStringIterateBody(ObjectVisitor* v);
9641 template<typename StaticVisitor>
9642 inline void ExternalAsciiStringIterateBody();
9645 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalAsciiString);
9649 // The ExternalTwoByteString class is an external string backed by a UTF-16
9651 class ExternalTwoByteString: public ExternalString {
9653 static const bool kHasAsciiEncoding = false;
9655 typedef v8::String::ExternalStringResource Resource;
9657 // The underlying string resource.
9658 inline const Resource* resource();
9659 inline void set_resource(const Resource* buffer);
9661 // Update the pointer cache to the external character array.
9662 // The cached pointer is always valid, as the external character array does =
9663 // not move during lifetime. Deserialization is the only exception, after
9664 // which the pointer cache has to be refreshed.
9665 inline void update_data_cache();
9667 inline const uint16_t* GetChars();
9669 // Dispatched behavior.
9670 inline uint16_t ExternalTwoByteStringGet(int index);
9673 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
9675 DECLARE_CAST(ExternalTwoByteString)
9677 // Garbage collection support.
9678 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
9680 template<typename StaticVisitor>
9681 inline void ExternalTwoByteStringIterateBody();
9684 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
9688 // Utility superclass for stack-allocated objects that must be updated
9689 // on gc. It provides two ways for the gc to update instances, either
9690 // iterating or updating after gc.
9691 class Relocatable BASE_EMBEDDED {
9693 explicit inline Relocatable(Isolate* isolate);
9694 inline virtual ~Relocatable();
9695 virtual void IterateInstance(ObjectVisitor* v) { }
9696 virtual void PostGarbageCollection() { }
9698 static void PostGarbageCollectionProcessing(Isolate* isolate);
9699 static int ArchiveSpacePerThread();
9700 static char* ArchiveState(Isolate* isolate, char* to);
9701 static char* RestoreState(Isolate* isolate, char* from);
9702 static void Iterate(Isolate* isolate, ObjectVisitor* v);
9703 static void Iterate(ObjectVisitor* v, Relocatable* top);
9704 static char* Iterate(ObjectVisitor* v, char* t);
9712 // A flat string reader provides random access to the contents of a
9713 // string independent of the character width of the string. The handle
9714 // must be valid as long as the reader is being used.
9715 class FlatStringReader : public Relocatable {
9717 FlatStringReader(Isolate* isolate, Handle<String> str);
9718 FlatStringReader(Isolate* isolate, Vector<const char> input);
9719 void PostGarbageCollection();
9720 inline uc32 Get(int index);
9721 int length() { return length_; }
9730 // A ConsStringOp that returns null.
9731 // Useful when the operation to apply on a ConsString
9732 // requires an expensive data structure.
9733 class ConsStringNullOp {
9735 inline ConsStringNullOp() {}
9736 static inline String* Operate(String*, unsigned*, int32_t*, unsigned*);
9738 DISALLOW_COPY_AND_ASSIGN(ConsStringNullOp);
9742 // This maintains an off-stack representation of the stack frames required
9743 // to traverse a ConsString, allowing an entirely iterative and restartable
9744 // traversal of the entire string
9745 class ConsStringIteratorOp {
9747 inline ConsStringIteratorOp() {}
9748 inline explicit ConsStringIteratorOp(ConsString* cons_string,
9750 Reset(cons_string, offset);
9752 inline void Reset(ConsString* cons_string, int offset = 0) {
9754 // Next will always return NULL.
9755 if (cons_string == NULL) return;
9756 Initialize(cons_string, offset);
9758 // Returns NULL when complete.
9759 inline String* Next(int* offset_out) {
9761 if (depth_ == 0) return NULL;
9762 return Continue(offset_out);
9766 static const int kStackSize = 32;
9767 // Use a mask instead of doing modulo operations for stack wrapping.
9768 static const int kDepthMask = kStackSize-1;
9769 STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
9770 static inline int OffsetForDepth(int depth);
9772 inline void PushLeft(ConsString* string);
9773 inline void PushRight(ConsString* string);
9774 inline void AdjustMaximumDepth();
9776 inline bool StackBlown() { return maximum_depth_ - depth_ == kStackSize; }
9777 void Initialize(ConsString* cons_string, int offset);
9778 String* Continue(int* offset_out);
9779 String* NextLeaf(bool* blew_stack);
9780 String* Search(int* offset_out);
9782 // Stack must always contain only frames for which right traversal
9783 // has not yet been performed.
9784 ConsString* frames_[kStackSize];
9789 DISALLOW_COPY_AND_ASSIGN(ConsStringIteratorOp);
9793 class StringCharacterStream {
9795 inline StringCharacterStream(String* string,
9796 ConsStringIteratorOp* op,
9798 inline uint16_t GetNext();
9799 inline bool HasMore();
9800 inline void Reset(String* string, int offset = 0);
9801 inline void VisitOneByteString(const uint8_t* chars, int length);
9802 inline void VisitTwoByteString(const uint16_t* chars, int length);
9807 const uint8_t* buffer8_;
9808 const uint16_t* buffer16_;
9810 const uint8_t* end_;
9811 ConsStringIteratorOp* op_;
9812 DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
9816 template <typename T>
9817 class VectorIterator {
9819 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
9820 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
9821 T GetNext() { return data_[index_++]; }
9822 bool has_more() { return index_ < data_.length(); }
9824 Vector<const T> data_;
9829 // The Oddball describes objects null, undefined, true, and false.
9830 class Oddball: public HeapObject {
9832 // [to_string]: Cached to_string computed at startup.
9833 DECL_ACCESSORS(to_string, String)
9835 // [to_number]: Cached to_number computed at startup.
9836 DECL_ACCESSORS(to_number, Object)
9838 inline byte kind() const;
9839 inline void set_kind(byte kind);
9841 DECLARE_CAST(Oddball)
9843 // Dispatched behavior.
9844 DECLARE_VERIFIER(Oddball)
9846 // Initialize the fields.
9847 static void Initialize(Isolate* isolate,
9848 Handle<Oddball> oddball,
9849 const char* to_string,
9850 Handle<Object> to_number,
9853 // Layout description.
9854 static const int kToStringOffset = HeapObject::kHeaderSize;
9855 static const int kToNumberOffset = kToStringOffset + kPointerSize;
9856 static const int kKindOffset = kToNumberOffset + kPointerSize;
9857 static const int kSize = kKindOffset + kPointerSize;
9859 static const byte kFalse = 0;
9860 static const byte kTrue = 1;
9861 static const byte kNotBooleanMask = ~1;
9862 static const byte kTheHole = 2;
9863 static const byte kNull = 3;
9864 static const byte kArgumentMarker = 4;
9865 static const byte kUndefined = 5;
9866 static const byte kUninitialized = 6;
9867 static const byte kOther = 7;
9868 static const byte kException = 8;
9870 typedef FixedBodyDescriptor<kToStringOffset,
9871 kToNumberOffset + kPointerSize,
9872 kSize> BodyDescriptor;
9874 STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset);
9875 STATIC_ASSERT(kNull == Internals::kNullOddballKind);
9876 STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind);
9879 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
9883 class Cell: public HeapObject {
9885 // [value]: value of the global property.
9886 DECL_ACCESSORS(value, Object)
9890 static inline Cell* FromValueAddress(Address value) {
9891 Object* result = FromAddress(value - kValueOffset);
9892 DCHECK(result->IsCell() || result->IsPropertyCell());
9893 return static_cast<Cell*>(result);
9896 inline Address ValueAddress() {
9897 return address() + kValueOffset;
9900 // Dispatched behavior.
9901 DECLARE_PRINTER(Cell)
9902 DECLARE_VERIFIER(Cell)
9904 // Layout description.
9905 static const int kValueOffset = HeapObject::kHeaderSize;
9906 static const int kSize = kValueOffset + kPointerSize;
9908 typedef FixedBodyDescriptor<kValueOffset,
9909 kValueOffset + kPointerSize,
9910 kSize> BodyDescriptor;
9913 DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9917 class PropertyCell: public Cell {
9919 // [type]: type of the global property.
9921 void set_type(HeapType* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9923 // [dependent_code]: dependent code that depends on the type of the global
9925 DECL_ACCESSORS(dependent_code, DependentCode)
9927 // Sets the value of the cell and updates the type field to be the union
9928 // of the cell's current type and the value's type. If the change causes
9929 // a change of the type of the cell's contents, code dependent on the cell
9930 // will be deoptimized.
9931 static void SetValueInferType(Handle<PropertyCell> cell,
9932 Handle<Object> value);
9934 // Computes the new type of the cell's contents for the given value, but
9935 // without actually modifying the 'type' field.
9936 static Handle<HeapType> UpdatedType(Handle<PropertyCell> cell,
9937 Handle<Object> value);
9939 static void AddDependentCompilationInfo(Handle<PropertyCell> cell,
9940 CompilationInfo* info);
9942 DECLARE_CAST(PropertyCell)
9944 inline Address TypeAddress() {
9945 return address() + kTypeOffset;
9948 // Dispatched behavior.
9949 DECLARE_PRINTER(PropertyCell)
9950 DECLARE_VERIFIER(PropertyCell)
9952 // Layout description.
9953 static const int kTypeOffset = kValueOffset + kPointerSize;
9954 static const int kDependentCodeOffset = kTypeOffset + kPointerSize;
9955 static const int kSize = kDependentCodeOffset + kPointerSize;
9957 static const int kPointerFieldsBeginOffset = kValueOffset;
9958 static const int kPointerFieldsEndOffset = kDependentCodeOffset;
9960 typedef FixedBodyDescriptor<kValueOffset,
9962 kSize> BodyDescriptor;
9965 DECL_ACCESSORS(type_raw, Object)
9966 DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9970 // The JSProxy describes EcmaScript Harmony proxies
9971 class JSProxy: public JSReceiver {
9973 // [handler]: The handler property.
9974 DECL_ACCESSORS(handler, Object)
9976 // [hash]: The hash code property (undefined if not initialized yet).
9977 DECL_ACCESSORS(hash, Object)
9979 DECLARE_CAST(JSProxy)
9981 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithHandler(
9982 Handle<JSProxy> proxy,
9983 Handle<Object> receiver,
9985 MUST_USE_RESULT static inline MaybeHandle<Object> GetElementWithHandler(
9986 Handle<JSProxy> proxy,
9987 Handle<Object> receiver,
9990 // If the handler defines an accessor property with a setter, invoke it.
9991 // If it defines an accessor property without a setter, or a data property
9992 // that is read-only, throw. In all these cases set '*done' to true,
9993 // otherwise set it to false.
9995 static MaybeHandle<Object> SetPropertyViaPrototypesWithHandler(
9996 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9997 Handle<Object> value, StrictMode strict_mode, bool* done);
9999 MUST_USE_RESULT static Maybe<PropertyAttributes>
10000 GetPropertyAttributesWithHandler(Handle<JSProxy> proxy,
10001 Handle<Object> receiver,
10002 Handle<Name> name);
10003 MUST_USE_RESULT static Maybe<PropertyAttributes>
10004 GetElementAttributeWithHandler(Handle<JSProxy> proxy,
10005 Handle<JSReceiver> receiver,
10007 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithHandler(
10008 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
10009 Handle<Object> value, StrictMode strict_mode);
10011 // Turn the proxy into an (empty) JSObject.
10012 static void Fix(Handle<JSProxy> proxy);
10014 // Initializes the body after the handler slot.
10015 inline void InitializeBody(int object_size, Object* value);
10017 // Invoke a trap by name. If the trap does not exist on this's handler,
10018 // but derived_trap is non-NULL, invoke that instead. May cause GC.
10019 MUST_USE_RESULT static MaybeHandle<Object> CallTrap(
10020 Handle<JSProxy> proxy,
10022 Handle<Object> derived_trap,
10024 Handle<Object> args[]);
10026 // Dispatched behavior.
10027 DECLARE_PRINTER(JSProxy)
10028 DECLARE_VERIFIER(JSProxy)
10030 // Layout description. We add padding so that a proxy has the same
10031 // size as a virgin JSObject. This is essential for becoming a JSObject
10033 static const int kHandlerOffset = HeapObject::kHeaderSize;
10034 static const int kHashOffset = kHandlerOffset + kPointerSize;
10035 static const int kPaddingOffset = kHashOffset + kPointerSize;
10036 static const int kSize = JSObject::kHeaderSize;
10037 static const int kHeaderSize = kPaddingOffset;
10038 static const int kPaddingSize = kSize - kPaddingOffset;
10040 STATIC_ASSERT(kPaddingSize >= 0);
10042 typedef FixedBodyDescriptor<kHandlerOffset,
10044 kSize> BodyDescriptor;
10047 friend class JSReceiver;
10049 MUST_USE_RESULT static inline MaybeHandle<Object> SetElementWithHandler(
10050 Handle<JSProxy> proxy,
10051 Handle<JSReceiver> receiver,
10053 Handle<Object> value,
10054 StrictMode strict_mode);
10056 MUST_USE_RESULT static Maybe<bool> HasPropertyWithHandler(
10057 Handle<JSProxy> proxy, Handle<Name> name);
10058 MUST_USE_RESULT static inline Maybe<bool> HasElementWithHandler(
10059 Handle<JSProxy> proxy, uint32_t index);
10061 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithHandler(
10062 Handle<JSProxy> proxy,
10065 MUST_USE_RESULT static MaybeHandle<Object> DeleteElementWithHandler(
10066 Handle<JSProxy> proxy,
10070 MUST_USE_RESULT Object* GetIdentityHash();
10072 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
10074 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
10078 class JSFunctionProxy: public JSProxy {
10080 // [call_trap]: The call trap.
10081 DECL_ACCESSORS(call_trap, Object)
10083 // [construct_trap]: The construct trap.
10084 DECL_ACCESSORS(construct_trap, Object)
10086 DECLARE_CAST(JSFunctionProxy)
10088 // Dispatched behavior.
10089 DECLARE_PRINTER(JSFunctionProxy)
10090 DECLARE_VERIFIER(JSFunctionProxy)
10092 // Layout description.
10093 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
10094 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
10095 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
10096 static const int kSize = JSFunction::kSize;
10097 static const int kPaddingSize = kSize - kPaddingOffset;
10099 STATIC_ASSERT(kPaddingSize >= 0);
10101 typedef FixedBodyDescriptor<kHandlerOffset,
10102 kConstructTrapOffset + kPointerSize,
10103 kSize> BodyDescriptor;
10106 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
10110 class JSCollection : public JSObject {
10112 // [table]: the backing hash table
10113 DECL_ACCESSORS(table, Object)
10115 static const int kTableOffset = JSObject::kHeaderSize;
10116 static const int kSize = kTableOffset + kPointerSize;
10119 DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollection);
10123 // The JSSet describes EcmaScript Harmony sets
10124 class JSSet : public JSCollection {
10126 DECLARE_CAST(JSSet)
10128 // Dispatched behavior.
10129 DECLARE_PRINTER(JSSet)
10130 DECLARE_VERIFIER(JSSet)
10133 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
10137 // The JSMap describes EcmaScript Harmony maps
10138 class JSMap : public JSCollection {
10140 DECLARE_CAST(JSMap)
10142 // Dispatched behavior.
10143 DECLARE_PRINTER(JSMap)
10144 DECLARE_VERIFIER(JSMap)
10147 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
10151 // OrderedHashTableIterator is an iterator that iterates over the keys and
10152 // values of an OrderedHashTable.
10154 // The iterator has a reference to the underlying OrderedHashTable data,
10155 // [table], as well as the current [index] the iterator is at.
10157 // When the OrderedHashTable is rehashed it adds a reference from the old table
10158 // to the new table as well as storing enough data about the changes so that the
10159 // iterator [index] can be adjusted accordingly.
10161 // When the [Next] result from the iterator is requested, the iterator checks if
10162 // there is a newer table that it needs to transition to.
10163 template<class Derived, class TableType>
10164 class OrderedHashTableIterator: public JSObject {
10166 // [table]: the backing hash table mapping keys to values.
10167 DECL_ACCESSORS(table, Object)
10169 // [index]: The index into the data table.
10170 DECL_ACCESSORS(index, Smi)
10172 // [kind]: The kind of iteration this is. One of the [Kind] enum values.
10173 DECL_ACCESSORS(kind, Smi)
10175 #ifdef OBJECT_PRINT
10176 void OrderedHashTableIteratorPrint(OStream& os); // NOLINT
10179 static const int kTableOffset = JSObject::kHeaderSize;
10180 static const int kIndexOffset = kTableOffset + kPointerSize;
10181 static const int kKindOffset = kIndexOffset + kPointerSize;
10182 static const int kSize = kKindOffset + kPointerSize;
10190 // Whether the iterator has more elements. This needs to be called before
10191 // calling |CurrentKey| and/or |CurrentValue|.
10194 // Move the index forward one.
10196 set_index(Smi::FromInt(Smi::cast(index())->value() + 1));
10199 // Populates the array with the next key and value and then moves the iterator
10201 // This returns the |kind| or 0 if the iterator is already at the end.
10202 Smi* Next(JSArray* value_array);
10204 // Returns the current key of the iterator. This should only be called when
10205 // |HasMore| returns true.
10206 inline Object* CurrentKey();
10209 // Transitions the iterator to the non obsolete backing store. This is a NOP
10210 // if the [table] is not obsolete.
10213 DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
10217 class JSSetIterator: public OrderedHashTableIterator<JSSetIterator,
10220 // Dispatched behavior.
10221 DECLARE_PRINTER(JSSetIterator)
10222 DECLARE_VERIFIER(JSSetIterator)
10224 DECLARE_CAST(JSSetIterator)
10226 // Called by |Next| to populate the array. This allows the subclasses to
10227 // populate the array differently.
10228 inline void PopulateValueArray(FixedArray* array);
10231 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSetIterator);
10235 class JSMapIterator: public OrderedHashTableIterator<JSMapIterator,
10238 // Dispatched behavior.
10239 DECLARE_PRINTER(JSMapIterator)
10240 DECLARE_VERIFIER(JSMapIterator)
10242 DECLARE_CAST(JSMapIterator)
10244 // Called by |Next| to populate the array. This allows the subclasses to
10245 // populate the array differently.
10246 inline void PopulateValueArray(FixedArray* array);
10249 // Returns the current value of the iterator. This should only be called when
10250 // |HasMore| returns true.
10251 inline Object* CurrentValue();
10253 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMapIterator);
10257 // Base class for both JSWeakMap and JSWeakSet
10258 class JSWeakCollection: public JSObject {
10260 // [table]: the backing hash table mapping keys to values.
10261 DECL_ACCESSORS(table, Object)
10263 // [next]: linked list of encountered weak maps during GC.
10264 DECL_ACCESSORS(next, Object)
10266 static const int kTableOffset = JSObject::kHeaderSize;
10267 static const int kNextOffset = kTableOffset + kPointerSize;
10268 static const int kSize = kNextOffset + kPointerSize;
10271 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
10275 // The JSWeakMap describes EcmaScript Harmony weak maps
10276 class JSWeakMap: public JSWeakCollection {
10278 DECLARE_CAST(JSWeakMap)
10280 // Dispatched behavior.
10281 DECLARE_PRINTER(JSWeakMap)
10282 DECLARE_VERIFIER(JSWeakMap)
10285 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
10289 // The JSWeakSet describes EcmaScript Harmony weak sets
10290 class JSWeakSet: public JSWeakCollection {
10292 DECLARE_CAST(JSWeakSet)
10294 // Dispatched behavior.
10295 DECLARE_PRINTER(JSWeakSet)
10296 DECLARE_VERIFIER(JSWeakSet)
10299 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
10303 class JSArrayBuffer: public JSObject {
10305 // [backing_store]: backing memory for this array
10306 DECL_ACCESSORS(backing_store, void)
10308 // [byte_length]: length in bytes
10309 DECL_ACCESSORS(byte_length, Object)
10312 DECL_ACCESSORS(flag, Smi)
10314 inline bool is_external();
10315 inline void set_is_external(bool value);
10317 inline bool should_be_freed();
10318 inline void set_should_be_freed(bool value);
10320 // [weak_next]: linked list of array buffers.
10321 DECL_ACCESSORS(weak_next, Object)
10323 // [weak_first_array]: weak linked list of views.
10324 DECL_ACCESSORS(weak_first_view, Object)
10326 DECLARE_CAST(JSArrayBuffer)
10328 // Neutering. Only neuters the buffer, not associated typed arrays.
10331 // Dispatched behavior.
10332 DECLARE_PRINTER(JSArrayBuffer)
10333 DECLARE_VERIFIER(JSArrayBuffer)
10335 static const int kBackingStoreOffset = JSObject::kHeaderSize;
10336 static const int kByteLengthOffset = kBackingStoreOffset + kPointerSize;
10337 static const int kFlagOffset = kByteLengthOffset + kPointerSize;
10338 static const int kWeakNextOffset = kFlagOffset + kPointerSize;
10339 static const int kWeakFirstViewOffset = kWeakNextOffset + kPointerSize;
10340 static const int kSize = kWeakFirstViewOffset + kPointerSize;
10342 static const int kSizeWithInternalFields =
10343 kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
10346 // Bit position in a flag
10347 static const int kIsExternalBit = 0;
10348 static const int kShouldBeFreed = 1;
10350 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
10354 class JSArrayBufferView: public JSObject {
10356 // [buffer]: ArrayBuffer that this typed array views.
10357 DECL_ACCESSORS(buffer, Object)
10359 // [byte_length]: offset of typed array in bytes.
10360 DECL_ACCESSORS(byte_offset, Object)
10362 // [byte_length]: length of typed array in bytes.
10363 DECL_ACCESSORS(byte_length, Object)
10365 // [weak_next]: linked list of typed arrays over the same array buffer.
10366 DECL_ACCESSORS(weak_next, Object)
10368 DECLARE_CAST(JSArrayBufferView)
10370 DECLARE_VERIFIER(JSArrayBufferView)
10372 static const int kBufferOffset = JSObject::kHeaderSize;
10373 static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
10374 static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
10375 static const int kWeakNextOffset = kByteLengthOffset + kPointerSize;
10376 static const int kViewSize = kWeakNextOffset + kPointerSize;
10382 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
10386 class JSTypedArray: public JSArrayBufferView {
10388 // [length]: length of typed array in elements.
10389 DECL_ACCESSORS(length, Object)
10391 // Neutering. Only neuters this typed array.
10394 DECLARE_CAST(JSTypedArray)
10396 ExternalArrayType type();
10397 size_t element_size();
10399 Handle<JSArrayBuffer> GetBuffer();
10401 // Dispatched behavior.
10402 DECLARE_PRINTER(JSTypedArray)
10403 DECLARE_VERIFIER(JSTypedArray)
10405 static const int kLengthOffset = kViewSize + kPointerSize;
10406 static const int kSize = kLengthOffset + kPointerSize;
10408 static const int kSizeWithInternalFields =
10409 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
10412 static Handle<JSArrayBuffer> MaterializeArrayBuffer(
10413 Handle<JSTypedArray> typed_array);
10415 DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
10419 class JSDataView: public JSArrayBufferView {
10421 // Only neuters this DataView
10424 DECLARE_CAST(JSDataView)
10426 // Dispatched behavior.
10427 DECLARE_PRINTER(JSDataView)
10428 DECLARE_VERIFIER(JSDataView)
10430 static const int kSize = kViewSize;
10432 static const int kSizeWithInternalFields =
10433 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
10436 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
10440 // Foreign describes objects pointing from JavaScript to C structures.
10441 // Since they cannot contain references to JS HeapObjects they can be
10442 // placed in old_data_space.
10443 class Foreign: public HeapObject {
10445 // [address]: field containing the address.
10446 inline Address foreign_address();
10447 inline void set_foreign_address(Address value);
10449 DECLARE_CAST(Foreign)
10451 // Dispatched behavior.
10452 inline void ForeignIterateBody(ObjectVisitor* v);
10454 template<typename StaticVisitor>
10455 inline void ForeignIterateBody();
10457 // Dispatched behavior.
10458 DECLARE_PRINTER(Foreign)
10459 DECLARE_VERIFIER(Foreign)
10461 // Layout description.
10463 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
10464 static const int kSize = kForeignAddressOffset + kPointerSize;
10466 STATIC_ASSERT(kForeignAddressOffset == Internals::kForeignAddressOffset);
10469 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
10473 // The JSArray describes JavaScript Arrays
10474 // Such an array can be in one of two modes:
10475 // - fast, backing storage is a FixedArray and length <= elements.length();
10476 // Please note: push and pop can be used to grow and shrink the array.
10477 // - slow, backing storage is a HashTable with numbers as keys.
10478 class JSArray: public JSObject {
10480 // [length]: The length property.
10481 DECL_ACCESSORS(length, Object)
10483 // Overload the length setter to skip write barrier when the length
10484 // is set to a smi. This matches the set function on FixedArray.
10485 inline void set_length(Smi* length);
10487 static void JSArrayUpdateLengthFromIndex(Handle<JSArray> array,
10489 Handle<Object> value);
10491 static bool IsReadOnlyLengthDescriptor(Handle<Map> jsarray_map);
10492 static bool WouldChangeReadOnlyLength(Handle<JSArray> array, uint32_t index);
10493 static MaybeHandle<Object> ReadOnlyLengthError(Handle<JSArray> array);
10495 // Initialize the array with the given capacity. The function may
10496 // fail due to out-of-memory situations, but only if the requested
10497 // capacity is non-zero.
10498 static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
10500 // Initializes the array to a certain length.
10501 inline bool AllowsSetElementsLength();
10503 MUST_USE_RESULT static MaybeHandle<Object> SetElementsLength(
10504 Handle<JSArray> array,
10505 Handle<Object> length);
10507 // Set the content of the array to the content of storage.
10508 static inline void SetContent(Handle<JSArray> array,
10509 Handle<FixedArrayBase> storage);
10511 DECLARE_CAST(JSArray)
10513 // Ensures that the fixed array backing the JSArray has at
10514 // least the stated size.
10515 static inline void EnsureSize(Handle<JSArray> array,
10516 int minimum_size_of_backing_fixed_array);
10518 // Expand the fixed array backing of a fast-case JSArray to at least
10519 // the requested size.
10520 static void Expand(Handle<JSArray> array,
10521 int minimum_size_of_backing_fixed_array);
10523 // Dispatched behavior.
10524 DECLARE_PRINTER(JSArray)
10525 DECLARE_VERIFIER(JSArray)
10527 // Number of element slots to pre-allocate for an empty array.
10528 static const int kPreallocatedArrayElements = 4;
10530 // Layout description.
10531 static const int kLengthOffset = JSObject::kHeaderSize;
10532 static const int kSize = kLengthOffset + kPointerSize;
10535 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
10539 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
10540 Handle<Map> initial_map);
10543 // JSRegExpResult is just a JSArray with a specific initial map.
10544 // This initial map adds in-object properties for "index" and "input"
10545 // properties, as assigned by RegExp.prototype.exec, which allows
10546 // faster creation of RegExp exec results.
10547 // This class just holds constants used when creating the result.
10548 // After creation the result must be treated as a JSArray in all regards.
10549 class JSRegExpResult: public JSArray {
10551 // Offsets of object fields.
10552 static const int kIndexOffset = JSArray::kSize;
10553 static const int kInputOffset = kIndexOffset + kPointerSize;
10554 static const int kSize = kInputOffset + kPointerSize;
10555 // Indices of in-object properties.
10556 static const int kIndexIndex = 0;
10557 static const int kInputIndex = 1;
10559 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
10563 class AccessorInfo: public Struct {
10565 DECL_ACCESSORS(name, Object)
10566 DECL_ACCESSORS(flag, Smi)
10567 DECL_ACCESSORS(expected_receiver_type, Object)
10569 inline bool all_can_read();
10570 inline void set_all_can_read(bool value);
10572 inline bool all_can_write();
10573 inline void set_all_can_write(bool value);
10575 inline PropertyAttributes property_attributes();
10576 inline void set_property_attributes(PropertyAttributes attributes);
10578 // Checks whether the given receiver is compatible with this accessor.
10579 static bool IsCompatibleReceiverType(Isolate* isolate,
10580 Handle<AccessorInfo> info,
10581 Handle<HeapType> type);
10582 inline bool IsCompatibleReceiver(Object* receiver);
10584 DECLARE_CAST(AccessorInfo)
10586 // Dispatched behavior.
10587 DECLARE_VERIFIER(AccessorInfo)
10589 // Append all descriptors to the array that are not already there.
10590 // Return number added.
10591 static int AppendUnique(Handle<Object> descriptors,
10592 Handle<FixedArray> array,
10593 int valid_descriptors);
10595 static const int kNameOffset = HeapObject::kHeaderSize;
10596 static const int kFlagOffset = kNameOffset + kPointerSize;
10597 static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
10598 static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
10601 inline bool HasExpectedReceiverType() {
10602 return expected_receiver_type()->IsFunctionTemplateInfo();
10604 // Bit positions in flag.
10605 static const int kAllCanReadBit = 0;
10606 static const int kAllCanWriteBit = 1;
10607 class AttributesField: public BitField<PropertyAttributes, 2, 3> {};
10609 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
10613 enum AccessorDescriptorType {
10614 kDescriptorBitmaskCompare,
10615 kDescriptorPointerCompare,
10616 kDescriptorPrimitiveValue,
10617 kDescriptorObjectDereference,
10618 kDescriptorPointerDereference,
10619 kDescriptorPointerShift,
10620 kDescriptorReturnObject
10624 struct BitmaskCompareDescriptor {
10626 uint32_t compare_value;
10627 uint8_t size; // Must be in {1,2,4}.
10631 struct PointerCompareDescriptor {
10632 void* compare_value;
10636 struct PrimitiveValueDescriptor {
10637 v8::DeclaredAccessorDescriptorDataType data_type;
10638 uint8_t bool_offset; // Must be in [0,7], used for kDescriptorBoolType.
10642 struct ObjectDerefenceDescriptor {
10643 uint8_t internal_field;
10647 struct PointerShiftDescriptor {
10648 int16_t byte_offset;
10652 struct DeclaredAccessorDescriptorData {
10653 AccessorDescriptorType type;
10655 struct BitmaskCompareDescriptor bitmask_compare_descriptor;
10656 struct PointerCompareDescriptor pointer_compare_descriptor;
10657 struct PrimitiveValueDescriptor primitive_value_descriptor;
10658 struct ObjectDerefenceDescriptor object_dereference_descriptor;
10659 struct PointerShiftDescriptor pointer_shift_descriptor;
10664 class DeclaredAccessorDescriptor;
10667 class DeclaredAccessorDescriptorIterator {
10669 explicit DeclaredAccessorDescriptorIterator(
10670 DeclaredAccessorDescriptor* descriptor);
10671 const DeclaredAccessorDescriptorData* Next();
10672 bool Complete() const { return length_ == offset_; }
10677 DISALLOW_IMPLICIT_CONSTRUCTORS(DeclaredAccessorDescriptorIterator);
10681 class DeclaredAccessorDescriptor: public Struct {
10683 DECL_ACCESSORS(serialized_data, ByteArray)
10685 DECLARE_CAST(DeclaredAccessorDescriptor)
10687 static Handle<DeclaredAccessorDescriptor> Create(
10689 const DeclaredAccessorDescriptorData& data,
10690 Handle<DeclaredAccessorDescriptor> previous);
10692 // Dispatched behavior.
10693 DECLARE_PRINTER(DeclaredAccessorDescriptor)
10694 DECLARE_VERIFIER(DeclaredAccessorDescriptor)
10696 static const int kSerializedDataOffset = HeapObject::kHeaderSize;
10697 static const int kSize = kSerializedDataOffset + kPointerSize;
10700 DISALLOW_IMPLICIT_CONSTRUCTORS(DeclaredAccessorDescriptor);
10704 class DeclaredAccessorInfo: public AccessorInfo {
10706 DECL_ACCESSORS(descriptor, DeclaredAccessorDescriptor)
10708 DECLARE_CAST(DeclaredAccessorInfo)
10710 // Dispatched behavior.
10711 DECLARE_PRINTER(DeclaredAccessorInfo)
10712 DECLARE_VERIFIER(DeclaredAccessorInfo)
10714 static const int kDescriptorOffset = AccessorInfo::kSize;
10715 static const int kSize = kDescriptorOffset + kPointerSize;
10718 DISALLOW_IMPLICIT_CONSTRUCTORS(DeclaredAccessorInfo);
10722 // An accessor must have a getter, but can have no setter.
10724 // When setting a property, V8 searches accessors in prototypes.
10725 // If an accessor was found and it does not have a setter,
10726 // the request is ignored.
10728 // If the accessor in the prototype has the READ_ONLY property attribute, then
10729 // a new value is added to the derived object when the property is set.
10730 // This shadows the accessor in the prototype.
10731 class ExecutableAccessorInfo: public AccessorInfo {
10733 DECL_ACCESSORS(getter, Object)
10734 DECL_ACCESSORS(setter, Object)
10735 DECL_ACCESSORS(data, Object)
10737 DECLARE_CAST(ExecutableAccessorInfo)
10739 // Dispatched behavior.
10740 DECLARE_PRINTER(ExecutableAccessorInfo)
10741 DECLARE_VERIFIER(ExecutableAccessorInfo)
10743 static const int kGetterOffset = AccessorInfo::kSize;
10744 static const int kSetterOffset = kGetterOffset + kPointerSize;
10745 static const int kDataOffset = kSetterOffset + kPointerSize;
10746 static const int kSize = kDataOffset + kPointerSize;
10748 inline void clear_setter();
10751 DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
10755 // Support for JavaScript accessors: A pair of a getter and a setter. Each
10756 // accessor can either be
10757 // * a pointer to a JavaScript function or proxy: a real accessor
10758 // * undefined: considered an accessor by the spec, too, strangely enough
10759 // * the hole: an accessor which has not been set
10760 // * a pointer to a map: a transition used to ensure map sharing
10761 class AccessorPair: public Struct {
10763 DECL_ACCESSORS(getter, Object)
10764 DECL_ACCESSORS(setter, Object)
10766 DECLARE_CAST(AccessorPair)
10768 static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
10770 Object* get(AccessorComponent component) {
10771 return component == ACCESSOR_GETTER ? getter() : setter();
10774 void set(AccessorComponent component, Object* value) {
10775 if (component == ACCESSOR_GETTER) {
10782 // Note: Returns undefined instead in case of a hole.
10783 Object* GetComponent(AccessorComponent component);
10785 // Set both components, skipping arguments which are a JavaScript null.
10786 void SetComponents(Object* getter, Object* setter) {
10787 if (!getter->IsNull()) set_getter(getter);
10788 if (!setter->IsNull()) set_setter(setter);
10791 bool ContainsAccessor() {
10792 return IsJSAccessor(getter()) || IsJSAccessor(setter());
10795 // Dispatched behavior.
10796 DECLARE_PRINTER(AccessorPair)
10797 DECLARE_VERIFIER(AccessorPair)
10799 static const int kGetterOffset = HeapObject::kHeaderSize;
10800 static const int kSetterOffset = kGetterOffset + kPointerSize;
10801 static const int kSize = kSetterOffset + kPointerSize;
10804 // Strangely enough, in addition to functions and harmony proxies, the spec
10805 // requires us to consider undefined as a kind of accessor, too:
10807 // Object.defineProperty(obj, "foo", {get: undefined});
10808 // assertTrue("foo" in obj);
10809 bool IsJSAccessor(Object* obj) {
10810 return obj->IsSpecFunction() || obj->IsUndefined();
10813 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
10817 class AccessCheckInfo: public Struct {
10819 DECL_ACCESSORS(named_callback, Object)
10820 DECL_ACCESSORS(indexed_callback, Object)
10821 DECL_ACCESSORS(data, Object)
10823 DECLARE_CAST(AccessCheckInfo)
10825 // Dispatched behavior.
10826 DECLARE_PRINTER(AccessCheckInfo)
10827 DECLARE_VERIFIER(AccessCheckInfo)
10829 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
10830 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
10831 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
10832 static const int kSize = kDataOffset + kPointerSize;
10835 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
10839 class InterceptorInfo: public Struct {
10841 DECL_ACCESSORS(getter, Object)
10842 DECL_ACCESSORS(setter, Object)
10843 DECL_ACCESSORS(query, Object)
10844 DECL_ACCESSORS(deleter, Object)
10845 DECL_ACCESSORS(enumerator, Object)
10846 DECL_ACCESSORS(data, Object)
10848 DECLARE_CAST(InterceptorInfo)
10850 // Dispatched behavior.
10851 DECLARE_PRINTER(InterceptorInfo)
10852 DECLARE_VERIFIER(InterceptorInfo)
10854 static const int kGetterOffset = HeapObject::kHeaderSize;
10855 static const int kSetterOffset = kGetterOffset + kPointerSize;
10856 static const int kQueryOffset = kSetterOffset + kPointerSize;
10857 static const int kDeleterOffset = kQueryOffset + kPointerSize;
10858 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
10859 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
10860 static const int kSize = kDataOffset + kPointerSize;
10863 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
10867 class CallHandlerInfo: public Struct {
10869 DECL_ACCESSORS(callback, Object)
10870 DECL_ACCESSORS(data, Object)
10872 DECLARE_CAST(CallHandlerInfo)
10874 // Dispatched behavior.
10875 DECLARE_PRINTER(CallHandlerInfo)
10876 DECLARE_VERIFIER(CallHandlerInfo)
10878 static const int kCallbackOffset = HeapObject::kHeaderSize;
10879 static const int kDataOffset = kCallbackOffset + kPointerSize;
10880 static const int kSize = kDataOffset + kPointerSize;
10883 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
10887 class TemplateInfo: public Struct {
10889 DECL_ACCESSORS(tag, Object)
10890 DECL_ACCESSORS(property_list, Object)
10891 DECL_ACCESSORS(property_accessors, Object)
10893 DECLARE_VERIFIER(TemplateInfo)
10895 static const int kTagOffset = HeapObject::kHeaderSize;
10896 static const int kPropertyListOffset = kTagOffset + kPointerSize;
10897 static const int kPropertyAccessorsOffset =
10898 kPropertyListOffset + kPointerSize;
10899 static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
10902 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
10906 class FunctionTemplateInfo: public TemplateInfo {
10908 DECL_ACCESSORS(serial_number, Object)
10909 DECL_ACCESSORS(call_code, Object)
10910 DECL_ACCESSORS(prototype_template, Object)
10911 DECL_ACCESSORS(parent_template, Object)
10912 DECL_ACCESSORS(named_property_handler, Object)
10913 DECL_ACCESSORS(indexed_property_handler, Object)
10914 DECL_ACCESSORS(instance_template, Object)
10915 DECL_ACCESSORS(class_name, Object)
10916 DECL_ACCESSORS(signature, Object)
10917 DECL_ACCESSORS(instance_call_handler, Object)
10918 DECL_ACCESSORS(access_check_info, Object)
10919 DECL_ACCESSORS(flag, Smi)
10921 inline int length() const;
10922 inline void set_length(int value);
10924 // Following properties use flag bits.
10925 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
10926 DECL_BOOLEAN_ACCESSORS(undetectable)
10927 // If the bit is set, object instances created by this function
10928 // requires access check.
10929 DECL_BOOLEAN_ACCESSORS(needs_access_check)
10930 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
10931 DECL_BOOLEAN_ACCESSORS(remove_prototype)
10932 DECL_BOOLEAN_ACCESSORS(do_not_cache)
10934 DECLARE_CAST(FunctionTemplateInfo)
10936 // Dispatched behavior.
10937 DECLARE_PRINTER(FunctionTemplateInfo)
10938 DECLARE_VERIFIER(FunctionTemplateInfo)
10940 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
10941 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
10942 static const int kPrototypeTemplateOffset =
10943 kCallCodeOffset + kPointerSize;
10944 static const int kParentTemplateOffset =
10945 kPrototypeTemplateOffset + kPointerSize;
10946 static const int kNamedPropertyHandlerOffset =
10947 kParentTemplateOffset + kPointerSize;
10948 static const int kIndexedPropertyHandlerOffset =
10949 kNamedPropertyHandlerOffset + kPointerSize;
10950 static const int kInstanceTemplateOffset =
10951 kIndexedPropertyHandlerOffset + kPointerSize;
10952 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
10953 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
10954 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
10955 static const int kAccessCheckInfoOffset =
10956 kInstanceCallHandlerOffset + kPointerSize;
10957 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
10958 static const int kLengthOffset = kFlagOffset + kPointerSize;
10959 static const int kSize = kLengthOffset + kPointerSize;
10961 // Returns true if |object| is an instance of this function template.
10962 bool IsTemplateFor(Object* object);
10963 bool IsTemplateFor(Map* map);
10966 // Bit position in the flag, from least significant bit position.
10967 static const int kHiddenPrototypeBit = 0;
10968 static const int kUndetectableBit = 1;
10969 static const int kNeedsAccessCheckBit = 2;
10970 static const int kReadOnlyPrototypeBit = 3;
10971 static const int kRemovePrototypeBit = 4;
10972 static const int kDoNotCacheBit = 5;
10974 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
10978 class ObjectTemplateInfo: public TemplateInfo {
10980 DECL_ACCESSORS(constructor, Object)
10981 DECL_ACCESSORS(internal_field_count, Object)
10983 DECLARE_CAST(ObjectTemplateInfo)
10985 // Dispatched behavior.
10986 DECLARE_PRINTER(ObjectTemplateInfo)
10987 DECLARE_VERIFIER(ObjectTemplateInfo)
10989 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10990 static const int kInternalFieldCountOffset =
10991 kConstructorOffset + kPointerSize;
10992 static const int kSize = kInternalFieldCountOffset + kPointerSize;
10996 class SignatureInfo: public Struct {
10998 DECL_ACCESSORS(receiver, Object)
10999 DECL_ACCESSORS(args, Object)
11001 DECLARE_CAST(SignatureInfo)
11003 // Dispatched behavior.
11004 DECLARE_PRINTER(SignatureInfo)
11005 DECLARE_VERIFIER(SignatureInfo)
11007 static const int kReceiverOffset = Struct::kHeaderSize;
11008 static const int kArgsOffset = kReceiverOffset + kPointerSize;
11009 static const int kSize = kArgsOffset + kPointerSize;
11012 DISALLOW_IMPLICIT_CONSTRUCTORS(SignatureInfo);
11016 class TypeSwitchInfo: public Struct {
11018 DECL_ACCESSORS(types, Object)
11020 DECLARE_CAST(TypeSwitchInfo)
11022 // Dispatched behavior.
11023 DECLARE_PRINTER(TypeSwitchInfo)
11024 DECLARE_VERIFIER(TypeSwitchInfo)
11026 static const int kTypesOffset = Struct::kHeaderSize;
11027 static const int kSize = kTypesOffset + kPointerSize;
11031 // The DebugInfo class holds additional information for a function being
11033 class DebugInfo: public Struct {
11035 // The shared function info for the source being debugged.
11036 DECL_ACCESSORS(shared, SharedFunctionInfo)
11037 // Code object for the original code.
11038 DECL_ACCESSORS(original_code, Code)
11039 // Code object for the patched code. This code object is the code object
11040 // currently active for the function.
11041 DECL_ACCESSORS(code, Code)
11042 // Fixed array holding status information for each active break point.
11043 DECL_ACCESSORS(break_points, FixedArray)
11045 // Check if there is a break point at a code position.
11046 bool HasBreakPoint(int code_position);
11047 // Get the break point info object for a code position.
11048 Object* GetBreakPointInfo(int code_position);
11049 // Clear a break point.
11050 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
11052 Handle<Object> break_point_object);
11053 // Set a break point.
11054 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
11055 int source_position, int statement_position,
11056 Handle<Object> break_point_object);
11057 // Get the break point objects for a code position.
11058 Object* GetBreakPointObjects(int code_position);
11059 // Find the break point info holding this break point object.
11060 static Object* FindBreakPointInfo(Handle<DebugInfo> debug_info,
11061 Handle<Object> break_point_object);
11062 // Get the number of break points for this function.
11063 int GetBreakPointCount();
11065 DECLARE_CAST(DebugInfo)
11067 // Dispatched behavior.
11068 DECLARE_PRINTER(DebugInfo)
11069 DECLARE_VERIFIER(DebugInfo)
11071 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
11072 static const int kOriginalCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
11073 static const int kPatchedCodeIndex = kOriginalCodeIndex + kPointerSize;
11074 static const int kActiveBreakPointsCountIndex =
11075 kPatchedCodeIndex + kPointerSize;
11076 static const int kBreakPointsStateIndex =
11077 kActiveBreakPointsCountIndex + kPointerSize;
11078 static const int kSize = kBreakPointsStateIndex + kPointerSize;
11080 static const int kEstimatedNofBreakPointsInFunction = 16;
11083 static const int kNoBreakPointInfo = -1;
11085 // Lookup the index in the break_points array for a code position.
11086 int GetBreakPointInfoIndex(int code_position);
11088 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
11092 // The BreakPointInfo class holds information for break points set in a
11093 // function. The DebugInfo object holds a BreakPointInfo object for each code
11094 // position with one or more break points.
11095 class BreakPointInfo: public Struct {
11097 // The position in the code for the break point.
11098 DECL_ACCESSORS(code_position, Smi)
11099 // The position in the source for the break position.
11100 DECL_ACCESSORS(source_position, Smi)
11101 // The position in the source for the last statement before this break
11103 DECL_ACCESSORS(statement_position, Smi)
11104 // List of related JavaScript break points.
11105 DECL_ACCESSORS(break_point_objects, Object)
11107 // Removes a break point.
11108 static void ClearBreakPoint(Handle<BreakPointInfo> info,
11109 Handle<Object> break_point_object);
11110 // Set a break point.
11111 static void SetBreakPoint(Handle<BreakPointInfo> info,
11112 Handle<Object> break_point_object);
11113 // Check if break point info has this break point object.
11114 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
11115 Handle<Object> break_point_object);
11116 // Get the number of break points for this code position.
11117 int GetBreakPointCount();
11119 DECLARE_CAST(BreakPointInfo)
11121 // Dispatched behavior.
11122 DECLARE_PRINTER(BreakPointInfo)
11123 DECLARE_VERIFIER(BreakPointInfo)
11125 static const int kCodePositionIndex = Struct::kHeaderSize;
11126 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
11127 static const int kStatementPositionIndex =
11128 kSourcePositionIndex + kPointerSize;
11129 static const int kBreakPointObjectsIndex =
11130 kStatementPositionIndex + kPointerSize;
11131 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
11134 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
11138 #undef DECL_BOOLEAN_ACCESSORS
11139 #undef DECL_ACCESSORS
11140 #undef DECLARE_CAST
11141 #undef DECLARE_VERIFIER
11143 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
11144 V(kStringTable, "string_table", "(Internalized strings)") \
11145 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
11146 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
11147 V(kSmiRootList, "smi_root_list", "(Smi roots)") \
11148 V(kInternalizedString, "internalized_string", "(Internal string)") \
11149 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
11150 V(kTop, "top", "(Isolate)") \
11151 V(kRelocatable, "relocatable", "(Relocatable)") \
11152 V(kDebug, "debug", "(Debugger)") \
11153 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
11154 V(kHandleScope, "handlescope", "(Handle scope)") \
11155 V(kBuiltins, "builtins", "(Builtins)") \
11156 V(kGlobalHandles, "globalhandles", "(Global handles)") \
11157 V(kEternalHandles, "eternalhandles", "(Eternal handles)") \
11158 V(kThreadManager, "threadmanager", "(Thread manager)") \
11159 V(kExtensions, "Extensions", "(Extensions)")
11161 class VisitorSynchronization : public AllStatic {
11163 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
11165 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
11168 #undef DECLARE_ENUM
11170 static const char* const kTags[kNumberOfSyncTags];
11171 static const char* const kTagNames[kNumberOfSyncTags];
11174 // Abstract base class for visiting, and optionally modifying, the
11175 // pointers contained in Objects. Used in GC and serialization/deserialization.
11176 class ObjectVisitor BASE_EMBEDDED {
11178 virtual ~ObjectVisitor() {}
11180 // Visits a contiguous arrays of pointers in the half-open range
11181 // [start, end). Any or all of the values may be modified on return.
11182 virtual void VisitPointers(Object** start, Object** end) = 0;
11184 // Handy shorthand for visiting a single pointer.
11185 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
11187 // Visit weak next_code_link in Code object.
11188 virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
11190 // To allow lazy clearing of inline caches the visitor has
11191 // a rich interface for iterating over Code objects..
11193 // Visits a code target in the instruction stream.
11194 virtual void VisitCodeTarget(RelocInfo* rinfo);
11196 // Visits a code entry in a JS function.
11197 virtual void VisitCodeEntry(Address entry_address);
11199 // Visits a global property cell reference in the instruction stream.
11200 virtual void VisitCell(RelocInfo* rinfo);
11202 // Visits a runtime entry in the instruction stream.
11203 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
11205 // Visits the resource of an ASCII or two-byte string.
11206 virtual void VisitExternalAsciiString(
11207 v8::String::ExternalAsciiStringResource** resource) {}
11208 virtual void VisitExternalTwoByteString(
11209 v8::String::ExternalStringResource** resource) {}
11211 // Visits a debug call target in the instruction stream.
11212 virtual void VisitDebugTarget(RelocInfo* rinfo);
11214 // Visits the byte sequence in a function's prologue that contains information
11215 // about the code's age.
11216 virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
11218 // Visit pointer embedded into a code object.
11219 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
11221 // Visits an external reference embedded into a code object.
11222 virtual void VisitExternalReference(RelocInfo* rinfo);
11224 // Visits an external reference. The value may be modified on return.
11225 virtual void VisitExternalReference(Address* p) {}
11227 // Visits a handle that has an embedder-assigned class ID.
11228 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
11230 // Intended for serialization/deserialization checking: insert, or
11231 // check for the presence of, a tag at this position in the stream.
11232 // Also used for marking up GC roots in heap snapshots.
11233 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
11237 class StructBodyDescriptor : public
11238 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
11240 static inline int SizeOf(Map* map, HeapObject* object) {
11241 return map->instance_size();
11246 // BooleanBit is a helper class for setting and getting a bit in an
11248 class BooleanBit : public AllStatic {
11250 static inline bool get(Smi* smi, int bit_position) {
11251 return get(smi->value(), bit_position);
11254 static inline bool get(int value, int bit_position) {
11255 return (value & (1 << bit_position)) != 0;
11258 static inline Smi* set(Smi* smi, int bit_position, bool v) {
11259 return Smi::FromInt(set(smi->value(), bit_position, v));
11262 static inline int set(int value, int bit_position, bool v) {
11264 value |= (1 << bit_position);
11266 value &= ~(1 << bit_position);
11272 } } // namespace v8::internal
11274 #endif // V8_OBJECTS_H_