1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
10 #include "src/allocation.h"
11 #include "src/assert-scope.h"
12 #include "src/bailout-reason.h"
13 #include "src/base/bits.h"
14 #include "src/base/smart-pointers.h"
15 #include "src/builtins.h"
16 #include "src/checks.h"
17 #include "src/elements-kind.h"
18 #include "src/field-index.h"
19 #include "src/flags.h"
21 #include "src/property-details.h"
22 #include "src/unicode-inl.h"
23 #include "src/unicode-decoder.h"
26 #if V8_TARGET_ARCH_ARM
27 #include "src/arm/constants-arm.h" // NOLINT
28 #elif V8_TARGET_ARCH_ARM64
29 #include "src/arm64/constants-arm64.h" // NOLINT
30 #elif V8_TARGET_ARCH_MIPS
31 #include "src/mips/constants-mips.h" // NOLINT
32 #elif V8_TARGET_ARCH_MIPS64
33 #include "src/mips64/constants-mips64.h" // NOLINT
34 #elif V8_TARGET_ARCH_PPC
35 #include "src/ppc/constants-ppc.h" // NOLINT
40 // Most object types in the V8 JavaScript are described in this file.
42 // Inheritance hierarchy:
44 // - Smi (immediate small integer)
45 // - HeapObject (superclass for everything allocated in the heap)
46 // - JSReceiver (suitable for property access)
50 // - JSArrayBufferView
63 // - JSGeneratorObject
82 // - CompilationCacheTable
83 // - CodeCacheHashTable
89 // - TypeFeedbackVector
92 // - ScriptContextTable
103 // - ExternalOneByteString
104 // - ExternalTwoByteString
105 // - InternalizedString
106 // - SeqInternalizedString
107 // - SeqOneByteInternalizedString
108 // - SeqTwoByteInternalizedString
109 // - ConsInternalizedString
110 // - ExternalInternalizedString
111 // - ExternalOneByteInternalizedString
112 // - ExternalTwoByteInternalizedString
129 // - SharedFunctionInfo
133 // - ExecutableAccessorInfo
139 // - FunctionTemplateInfo
140 // - ObjectTemplateInfo
149 // Formats of Object*:
150 // Smi: [31 bit signed int] 0
151 // HeapObject: [32 bit direct pointer] (4 byte aligned) | 01
156 enum KeyedAccessStoreMode {
158 STORE_TRANSITION_SMI_TO_OBJECT,
159 STORE_TRANSITION_SMI_TO_DOUBLE,
160 STORE_TRANSITION_DOUBLE_TO_OBJECT,
161 STORE_TRANSITION_HOLEY_SMI_TO_OBJECT,
162 STORE_TRANSITION_HOLEY_SMI_TO_DOUBLE,
163 STORE_TRANSITION_HOLEY_DOUBLE_TO_OBJECT,
164 STORE_AND_GROW_NO_TRANSITION,
165 STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT,
166 STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE,
167 STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT,
168 STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_OBJECT,
169 STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_DOUBLE,
170 STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT,
171 STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS,
172 STORE_NO_TRANSITION_HANDLE_COW
176 enum TypeofMode { INSIDE_TYPEOF, NOT_INSIDE_TYPEOF };
185 enum ExternalArrayType {
186 kExternalInt8Array = 1,
189 kExternalUint16Array,
191 kExternalUint32Array,
192 kExternalFloat32Array,
193 kExternalFloat64Array,
194 kExternalUint8ClampedArray,
198 static const int kGrowICDelta = STORE_AND_GROW_NO_TRANSITION -
200 STATIC_ASSERT(STANDARD_STORE == 0);
201 STATIC_ASSERT(kGrowICDelta ==
202 STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT -
203 STORE_TRANSITION_SMI_TO_OBJECT);
204 STATIC_ASSERT(kGrowICDelta ==
205 STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE -
206 STORE_TRANSITION_SMI_TO_DOUBLE);
207 STATIC_ASSERT(kGrowICDelta ==
208 STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT -
209 STORE_TRANSITION_DOUBLE_TO_OBJECT);
212 static inline KeyedAccessStoreMode GetGrowStoreMode(
213 KeyedAccessStoreMode store_mode) {
214 if (store_mode < STORE_AND_GROW_NO_TRANSITION) {
215 store_mode = static_cast<KeyedAccessStoreMode>(
216 static_cast<int>(store_mode) + kGrowICDelta);
222 static inline bool IsTransitionStoreMode(KeyedAccessStoreMode store_mode) {
223 return store_mode > STANDARD_STORE &&
224 store_mode <= STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT &&
225 store_mode != STORE_AND_GROW_NO_TRANSITION;
229 static inline KeyedAccessStoreMode GetNonTransitioningStoreMode(
230 KeyedAccessStoreMode store_mode) {
231 if (store_mode >= STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS) {
234 if (store_mode >= STORE_AND_GROW_NO_TRANSITION) {
235 return STORE_AND_GROW_NO_TRANSITION;
237 return STANDARD_STORE;
241 static inline bool IsGrowStoreMode(KeyedAccessStoreMode store_mode) {
242 return store_mode >= STORE_AND_GROW_NO_TRANSITION &&
243 store_mode <= STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT;
247 enum IcCheckType { ELEMENT, PROPERTY };
250 // SKIP_WRITE_BARRIER skips the write barrier.
251 // UPDATE_WEAK_WRITE_BARRIER skips the marking part of the write barrier and
252 // only performs the generational part.
253 // UPDATE_WRITE_BARRIER is doing the full barrier, marking and generational.
254 enum WriteBarrierMode {
256 UPDATE_WEAK_WRITE_BARRIER,
261 // Indicates whether a value can be loaded as a constant.
262 enum StoreMode { ALLOW_IN_DESCRIPTOR, FORCE_FIELD };
265 // PropertyNormalizationMode is used to specify whether to keep
266 // inobject properties when normalizing properties of a JSObject.
267 enum PropertyNormalizationMode {
268 CLEAR_INOBJECT_PROPERTIES,
269 KEEP_INOBJECT_PROPERTIES
273 // Indicates how aggressively the prototype should be optimized. FAST_PROTOTYPE
274 // will give the fastest result by tailoring the map to the prototype, but that
275 // will cause polymorphism with other objects. REGULAR_PROTOTYPE is to be used
276 // (at least for now) when dynamically modifying the prototype chain of an
277 // object using __proto__ or Object.setPrototypeOf.
278 enum PrototypeOptimizationMode { REGULAR_PROTOTYPE, FAST_PROTOTYPE };
281 // Indicates whether transitions can be added to a source map or not.
282 enum TransitionFlag {
288 // Indicates whether the transition is simple: the target map of the transition
289 // either extends the current map with a new property, or it modifies the
290 // property that was added last to the current map.
291 enum SimpleTransitionFlag {
292 SIMPLE_PROPERTY_TRANSITION,
298 // Indicates whether we are only interested in the descriptors of a particular
299 // map, or in all descriptors in the descriptor array.
300 enum DescriptorFlag {
305 // The GC maintains a bit of information, the MarkingParity, which toggles
306 // from odd to even and back every time marking is completed. Incremental
307 // marking can visit an object twice during a marking phase, so algorithms that
308 // that piggy-back on marking can use the parity to ensure that they only
309 // perform an operation on an object once per marking phase: they record the
310 // MarkingParity when they visit an object, and only re-visit the object when it
311 // is marked again and the MarkingParity changes.
318 // ICs store extra state in a Code object. The default extra state is
320 typedef int ExtraICState;
321 static const ExtraICState kNoExtraICState = 0;
323 // Instance size sentinel for objects of variable size.
324 const int kVariableSizeSentinel = 0;
326 // We may store the unsigned bit field as signed Smi value and do not
328 const int kStubMajorKeyBits = 7;
329 const int kStubMinorKeyBits = kSmiValueSize - kStubMajorKeyBits - 1;
331 // All Maps have a field instance_type containing a InstanceType.
332 // It describes the type of the instances.
334 // As an example, a JavaScript object is a heap object and its map
335 // instance_type is JS_OBJECT_TYPE.
337 // The names of the string instance types are intended to systematically
338 // mirror their encoding in the instance_type field of the map. The default
339 // encoding is considered TWO_BYTE. It is not mentioned in the name. ONE_BYTE
340 // encoding is mentioned explicitly in the name. Likewise, the default
341 // representation is considered sequential. It is not mentioned in the
342 // name. The other representations (e.g. CONS, EXTERNAL) are explicitly
343 // mentioned. Finally, the string is either a STRING_TYPE (if it is a normal
344 // string) or a INTERNALIZED_STRING_TYPE (if it is a internalized string).
346 // NOTE: The following things are some that depend on the string types having
347 // instance_types that are less than those of all other types:
348 // HeapObject::Size, HeapObject::IterateBody, the typeof operator, and
351 // NOTE: Everything following JS_VALUE_TYPE is considered a
352 // JSObject for GC purposes. The first four entries here have typeof
353 // 'object', whereas JS_FUNCTION_TYPE has typeof 'function'.
354 #define INSTANCE_TYPE_LIST(V) \
356 V(ONE_BYTE_STRING_TYPE) \
357 V(CONS_STRING_TYPE) \
358 V(CONS_ONE_BYTE_STRING_TYPE) \
359 V(SLICED_STRING_TYPE) \
360 V(SLICED_ONE_BYTE_STRING_TYPE) \
361 V(EXTERNAL_STRING_TYPE) \
362 V(EXTERNAL_ONE_BYTE_STRING_TYPE) \
363 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
364 V(SHORT_EXTERNAL_STRING_TYPE) \
365 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE) \
366 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
368 V(INTERNALIZED_STRING_TYPE) \
369 V(ONE_BYTE_INTERNALIZED_STRING_TYPE) \
370 V(EXTERNAL_INTERNALIZED_STRING_TYPE) \
371 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
372 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
373 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE) \
374 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
375 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
390 V(PROPERTY_CELL_TYPE) \
392 V(HEAP_NUMBER_TYPE) \
393 V(MUTABLE_HEAP_NUMBER_TYPE) \
396 V(BYTECODE_ARRAY_TYPE) \
399 V(FIXED_INT8_ARRAY_TYPE) \
400 V(FIXED_UINT8_ARRAY_TYPE) \
401 V(FIXED_INT16_ARRAY_TYPE) \
402 V(FIXED_UINT16_ARRAY_TYPE) \
403 V(FIXED_INT32_ARRAY_TYPE) \
404 V(FIXED_UINT32_ARRAY_TYPE) \
405 V(FIXED_FLOAT32_ARRAY_TYPE) \
406 V(FIXED_FLOAT64_ARRAY_TYPE) \
407 V(FIXED_UINT8_CLAMPED_ARRAY_TYPE) \
411 V(DECLARED_ACCESSOR_DESCRIPTOR_TYPE) \
412 V(DECLARED_ACCESSOR_INFO_TYPE) \
413 V(EXECUTABLE_ACCESSOR_INFO_TYPE) \
414 V(ACCESSOR_PAIR_TYPE) \
415 V(ACCESS_CHECK_INFO_TYPE) \
416 V(INTERCEPTOR_INFO_TYPE) \
417 V(CALL_HANDLER_INFO_TYPE) \
418 V(FUNCTION_TEMPLATE_INFO_TYPE) \
419 V(OBJECT_TEMPLATE_INFO_TYPE) \
420 V(SIGNATURE_INFO_TYPE) \
421 V(TYPE_SWITCH_INFO_TYPE) \
422 V(ALLOCATION_MEMENTO_TYPE) \
423 V(ALLOCATION_SITE_TYPE) \
426 V(POLYMORPHIC_CODE_CACHE_TYPE) \
427 V(TYPE_FEEDBACK_INFO_TYPE) \
428 V(ALIASED_ARGUMENTS_ENTRY_TYPE) \
430 V(PROTOTYPE_INFO_TYPE) \
432 V(FIXED_ARRAY_TYPE) \
433 V(FIXED_DOUBLE_ARRAY_TYPE) \
434 V(SHARED_FUNCTION_INFO_TYPE) \
437 V(JS_MESSAGE_OBJECT_TYPE) \
442 V(JS_CONTEXT_EXTENSION_OBJECT_TYPE) \
443 V(JS_GENERATOR_OBJECT_TYPE) \
445 V(JS_GLOBAL_OBJECT_TYPE) \
446 V(JS_BUILTINS_OBJECT_TYPE) \
447 V(JS_GLOBAL_PROXY_TYPE) \
449 V(JS_ARRAY_BUFFER_TYPE) \
450 V(JS_TYPED_ARRAY_TYPE) \
451 V(JS_DATA_VIEW_TYPE) \
455 V(JS_SET_ITERATOR_TYPE) \
456 V(JS_MAP_ITERATOR_TYPE) \
457 V(JS_WEAK_MAP_TYPE) \
458 V(JS_WEAK_SET_TYPE) \
461 V(JS_FUNCTION_TYPE) \
462 V(JS_FUNCTION_PROXY_TYPE) \
464 V(BREAK_POINT_INFO_TYPE)
467 // Since string types are not consecutive, this macro is used to
468 // iterate over them.
469 #define STRING_TYPE_LIST(V) \
470 V(STRING_TYPE, kVariableSizeSentinel, string, String) \
471 V(ONE_BYTE_STRING_TYPE, kVariableSizeSentinel, one_byte_string, \
473 V(CONS_STRING_TYPE, ConsString::kSize, cons_string, ConsString) \
474 V(CONS_ONE_BYTE_STRING_TYPE, ConsString::kSize, cons_one_byte_string, \
476 V(SLICED_STRING_TYPE, SlicedString::kSize, sliced_string, SlicedString) \
477 V(SLICED_ONE_BYTE_STRING_TYPE, SlicedString::kSize, sliced_one_byte_string, \
478 SlicedOneByteString) \
479 V(EXTERNAL_STRING_TYPE, ExternalTwoByteString::kSize, external_string, \
481 V(EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kSize, \
482 external_one_byte_string, ExternalOneByteString) \
483 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, ExternalTwoByteString::kSize, \
484 external_string_with_one_byte_data, ExternalStringWithOneByteData) \
485 V(SHORT_EXTERNAL_STRING_TYPE, ExternalTwoByteString::kShortSize, \
486 short_external_string, ShortExternalString) \
487 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kShortSize, \
488 short_external_one_byte_string, ShortExternalOneByteString) \
489 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, \
490 ExternalTwoByteString::kShortSize, \
491 short_external_string_with_one_byte_data, \
492 ShortExternalStringWithOneByteData) \
494 V(INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, internalized_string, \
495 InternalizedString) \
496 V(ONE_BYTE_INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, \
497 one_byte_internalized_string, OneByteInternalizedString) \
498 V(EXTERNAL_INTERNALIZED_STRING_TYPE, ExternalTwoByteString::kSize, \
499 external_internalized_string, ExternalInternalizedString) \
500 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, ExternalOneByteString::kSize, \
501 external_one_byte_internalized_string, ExternalOneByteInternalizedString) \
502 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
503 ExternalTwoByteString::kSize, \
504 external_internalized_string_with_one_byte_data, \
505 ExternalInternalizedStringWithOneByteData) \
506 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE, \
507 ExternalTwoByteString::kShortSize, short_external_internalized_string, \
508 ShortExternalInternalizedString) \
509 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, \
510 ExternalOneByteString::kShortSize, \
511 short_external_one_byte_internalized_string, \
512 ShortExternalOneByteInternalizedString) \
513 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
514 ExternalTwoByteString::kShortSize, \
515 short_external_internalized_string_with_one_byte_data, \
516 ShortExternalInternalizedStringWithOneByteData)
518 // A struct is a simple object a set of object-valued fields. Including an
519 // object type in this causes the compiler to generate most of the boilerplate
520 // code for the class including allocation and garbage collection routines,
521 // casts and predicates. All you need to define is the class, methods and
522 // object verification routines. Easy, no?
524 // Note that for subtle reasons related to the ordering or numerical values of
525 // type tags, elements in this list have to be added to the INSTANCE_TYPE_LIST
527 #define STRUCT_LIST(V) \
529 V(EXECUTABLE_ACCESSOR_INFO, ExecutableAccessorInfo, \
530 executable_accessor_info) \
531 V(ACCESSOR_PAIR, AccessorPair, accessor_pair) \
532 V(ACCESS_CHECK_INFO, AccessCheckInfo, access_check_info) \
533 V(INTERCEPTOR_INFO, InterceptorInfo, interceptor_info) \
534 V(CALL_HANDLER_INFO, CallHandlerInfo, call_handler_info) \
535 V(FUNCTION_TEMPLATE_INFO, FunctionTemplateInfo, function_template_info) \
536 V(OBJECT_TEMPLATE_INFO, ObjectTemplateInfo, object_template_info) \
537 V(TYPE_SWITCH_INFO, TypeSwitchInfo, type_switch_info) \
538 V(SCRIPT, Script, script) \
539 V(ALLOCATION_SITE, AllocationSite, allocation_site) \
540 V(ALLOCATION_MEMENTO, AllocationMemento, allocation_memento) \
541 V(CODE_CACHE, CodeCache, code_cache) \
542 V(POLYMORPHIC_CODE_CACHE, PolymorphicCodeCache, polymorphic_code_cache) \
543 V(TYPE_FEEDBACK_INFO, TypeFeedbackInfo, type_feedback_info) \
544 V(ALIASED_ARGUMENTS_ENTRY, AliasedArgumentsEntry, aliased_arguments_entry) \
545 V(DEBUG_INFO, DebugInfo, debug_info) \
546 V(BREAK_POINT_INFO, BreakPointInfo, break_point_info) \
547 V(PROTOTYPE_INFO, PrototypeInfo, prototype_info)
549 // We use the full 8 bits of the instance_type field to encode heap object
550 // instance types. The high-order bit (bit 7) is set if the object is not a
551 // string, and cleared if it is a string.
552 const uint32_t kIsNotStringMask = 0x80;
553 const uint32_t kStringTag = 0x0;
554 const uint32_t kNotStringTag = 0x80;
556 // Bit 6 indicates that the object is an internalized string (if set) or not.
557 // Bit 7 has to be clear as well.
558 const uint32_t kIsNotInternalizedMask = 0x40;
559 const uint32_t kNotInternalizedTag = 0x40;
560 const uint32_t kInternalizedTag = 0x0;
562 // If bit 7 is clear then bit 2 indicates whether the string consists of
563 // two-byte characters or one-byte characters.
564 const uint32_t kStringEncodingMask = 0x4;
565 const uint32_t kTwoByteStringTag = 0x0;
566 const uint32_t kOneByteStringTag = 0x4;
568 // If bit 7 is clear, the low-order 2 bits indicate the representation
570 const uint32_t kStringRepresentationMask = 0x03;
571 enum StringRepresentationTag {
573 kConsStringTag = 0x1,
574 kExternalStringTag = 0x2,
575 kSlicedStringTag = 0x3
577 const uint32_t kIsIndirectStringMask = 0x1;
578 const uint32_t kIsIndirectStringTag = 0x1;
579 STATIC_ASSERT((kSeqStringTag & kIsIndirectStringMask) == 0); // NOLINT
580 STATIC_ASSERT((kExternalStringTag & kIsIndirectStringMask) == 0); // NOLINT
581 STATIC_ASSERT((kConsStringTag &
582 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
583 STATIC_ASSERT((kSlicedStringTag &
584 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
586 // Use this mask to distinguish between cons and slice only after making
587 // sure that the string is one of the two (an indirect string).
588 const uint32_t kSlicedNotConsMask = kSlicedStringTag & ~kConsStringTag;
589 STATIC_ASSERT(IS_POWER_OF_TWO(kSlicedNotConsMask));
591 // If bit 7 is clear, then bit 3 indicates whether this two-byte
592 // string actually contains one byte data.
593 const uint32_t kOneByteDataHintMask = 0x08;
594 const uint32_t kOneByteDataHintTag = 0x08;
596 // If bit 7 is clear and string representation indicates an external string,
597 // then bit 4 indicates whether the data pointer is cached.
598 const uint32_t kShortExternalStringMask = 0x10;
599 const uint32_t kShortExternalStringTag = 0x10;
602 // A ConsString with an empty string as the right side is a candidate
603 // for being shortcut by the garbage collector. We don't allocate any
604 // non-flat internalized strings, so we do not shortcut them thereby
605 // avoiding turning internalized strings into strings. The bit-masks
606 // below contain the internalized bit as additional safety.
607 // See heap.cc, mark-compact.cc and objects-visiting.cc.
608 const uint32_t kShortcutTypeMask =
610 kIsNotInternalizedMask |
611 kStringRepresentationMask;
612 const uint32_t kShortcutTypeTag = kConsStringTag | kNotInternalizedTag;
614 static inline bool IsShortcutCandidate(int type) {
615 return ((type & kShortcutTypeMask) == kShortcutTypeTag);
621 INTERNALIZED_STRING_TYPE =
622 kTwoByteStringTag | kSeqStringTag | kInternalizedTag,
623 ONE_BYTE_INTERNALIZED_STRING_TYPE =
624 kOneByteStringTag | kSeqStringTag | kInternalizedTag,
625 EXTERNAL_INTERNALIZED_STRING_TYPE =
626 kTwoByteStringTag | kExternalStringTag | kInternalizedTag,
627 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
628 kOneByteStringTag | kExternalStringTag | kInternalizedTag,
629 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
630 EXTERNAL_INTERNALIZED_STRING_TYPE | kOneByteDataHintTag |
632 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE = EXTERNAL_INTERNALIZED_STRING_TYPE |
633 kShortExternalStringTag |
635 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
636 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kShortExternalStringTag |
638 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
639 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
640 kShortExternalStringTag | kInternalizedTag,
641 STRING_TYPE = INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
642 ONE_BYTE_STRING_TYPE =
643 ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
644 CONS_STRING_TYPE = kTwoByteStringTag | kConsStringTag | kNotInternalizedTag,
645 CONS_ONE_BYTE_STRING_TYPE =
646 kOneByteStringTag | kConsStringTag | kNotInternalizedTag,
648 kTwoByteStringTag | kSlicedStringTag | kNotInternalizedTag,
649 SLICED_ONE_BYTE_STRING_TYPE =
650 kOneByteStringTag | kSlicedStringTag | kNotInternalizedTag,
651 EXTERNAL_STRING_TYPE =
652 EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
653 EXTERNAL_ONE_BYTE_STRING_TYPE =
654 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
655 EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
656 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
658 SHORT_EXTERNAL_STRING_TYPE =
659 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
660 SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE =
661 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
662 SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
663 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
667 SYMBOL_TYPE = kNotStringTag, // FIRST_NONSTRING_TYPE, LAST_NAME_TYPE
669 // Objects allocated in their own spaces (never in new space).
674 // "Data", objects that cannot contain non-map-word pointers to heap
677 MUTABLE_HEAP_NUMBER_TYPE,
678 FLOAT32X4_TYPE, // FIRST_SIMD_VALUE_TYPE
684 BOOL8X16_TYPE, // LAST_SIMD_VALUE_TYPE
689 FIXED_INT8_ARRAY_TYPE, // FIRST_FIXED_TYPED_ARRAY_TYPE
690 FIXED_UINT8_ARRAY_TYPE,
691 FIXED_INT16_ARRAY_TYPE,
692 FIXED_UINT16_ARRAY_TYPE,
693 FIXED_INT32_ARRAY_TYPE,
694 FIXED_UINT32_ARRAY_TYPE,
695 FIXED_FLOAT32_ARRAY_TYPE,
696 FIXED_FLOAT64_ARRAY_TYPE,
697 FIXED_UINT8_CLAMPED_ARRAY_TYPE, // LAST_FIXED_TYPED_ARRAY_TYPE
698 FIXED_DOUBLE_ARRAY_TYPE,
699 FILLER_TYPE, // LAST_DATA_TYPE
702 DECLARED_ACCESSOR_DESCRIPTOR_TYPE,
703 DECLARED_ACCESSOR_INFO_TYPE,
704 EXECUTABLE_ACCESSOR_INFO_TYPE,
706 ACCESS_CHECK_INFO_TYPE,
707 INTERCEPTOR_INFO_TYPE,
708 CALL_HANDLER_INFO_TYPE,
709 FUNCTION_TEMPLATE_INFO_TYPE,
710 OBJECT_TEMPLATE_INFO_TYPE,
712 TYPE_SWITCH_INFO_TYPE,
713 ALLOCATION_SITE_TYPE,
714 ALLOCATION_MEMENTO_TYPE,
717 POLYMORPHIC_CODE_CACHE_TYPE,
718 TYPE_FEEDBACK_INFO_TYPE,
719 ALIASED_ARGUMENTS_ENTRY_TYPE,
722 BREAK_POINT_INFO_TYPE,
724 SHARED_FUNCTION_INFO_TYPE,
730 // All the following types are subtypes of JSReceiver, which corresponds to
731 // objects in the JS sense. The first and the last type in this range are
732 // the two forms of function. This organization enables using the same
733 // compares for checking the JS_RECEIVER/SPEC_OBJECT range and the
734 // NONCALLABLE_JS_OBJECT range.
735 JS_FUNCTION_PROXY_TYPE, // FIRST_JS_RECEIVER_TYPE, FIRST_JS_PROXY_TYPE
736 JS_PROXY_TYPE, // LAST_JS_PROXY_TYPE
737 JS_VALUE_TYPE, // FIRST_JS_OBJECT_TYPE
738 JS_MESSAGE_OBJECT_TYPE,
741 JS_CONTEXT_EXTENSION_OBJECT_TYPE,
742 JS_GENERATOR_OBJECT_TYPE,
744 JS_GLOBAL_OBJECT_TYPE,
745 JS_BUILTINS_OBJECT_TYPE,
746 JS_GLOBAL_PROXY_TYPE,
748 JS_ARRAY_BUFFER_TYPE,
753 JS_SET_ITERATOR_TYPE,
754 JS_MAP_ITERATOR_TYPE,
758 JS_FUNCTION_TYPE, // LAST_JS_OBJECT_TYPE, LAST_JS_RECEIVER_TYPE
762 LAST_TYPE = JS_FUNCTION_TYPE,
763 FIRST_NAME_TYPE = FIRST_TYPE,
764 LAST_NAME_TYPE = SYMBOL_TYPE,
765 FIRST_UNIQUE_NAME_TYPE = INTERNALIZED_STRING_TYPE,
766 LAST_UNIQUE_NAME_TYPE = SYMBOL_TYPE,
767 FIRST_NONSTRING_TYPE = SYMBOL_TYPE,
768 // Boundaries for testing for a SIMD types.
769 FIRST_SIMD_VALUE_TYPE = FLOAT32X4_TYPE,
770 LAST_SIMD_VALUE_TYPE = BOOL8X16_TYPE,
771 // Boundaries for testing for a fixed typed array.
772 FIRST_FIXED_TYPED_ARRAY_TYPE = FIXED_INT8_ARRAY_TYPE,
773 LAST_FIXED_TYPED_ARRAY_TYPE = FIXED_UINT8_CLAMPED_ARRAY_TYPE,
774 // Boundary for promotion to old space.
775 LAST_DATA_TYPE = FILLER_TYPE,
776 // Boundary for objects represented as JSReceiver (i.e. JSObject or JSProxy).
777 // Note that there is no range for JSObject or JSProxy, since their subtypes
778 // are not continuous in this enum! The enum ranges instead reflect the
779 // external class names, where proxies are treated as either ordinary objects,
781 FIRST_JS_RECEIVER_TYPE = JS_FUNCTION_PROXY_TYPE,
782 LAST_JS_RECEIVER_TYPE = LAST_TYPE,
783 // Boundaries for testing the types represented as JSObject
784 FIRST_JS_OBJECT_TYPE = JS_VALUE_TYPE,
785 LAST_JS_OBJECT_TYPE = LAST_TYPE,
786 // Boundaries for testing the types represented as JSProxy
787 FIRST_JS_PROXY_TYPE = JS_FUNCTION_PROXY_TYPE,
788 LAST_JS_PROXY_TYPE = JS_PROXY_TYPE,
789 // Boundaries for testing whether the type is a JavaScript object.
790 FIRST_SPEC_OBJECT_TYPE = FIRST_JS_RECEIVER_TYPE,
791 LAST_SPEC_OBJECT_TYPE = LAST_JS_RECEIVER_TYPE,
792 // Boundaries for testing the types for which typeof is "object".
793 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_PROXY_TYPE,
794 LAST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_REGEXP_TYPE,
795 // Note that the types for which typeof is "function" are not continuous.
796 // Define this so that we can put assertions on discrete checks.
797 NUM_OF_CALLABLE_SPEC_OBJECT_TYPES = 2
800 STATIC_ASSERT(JS_OBJECT_TYPE == Internals::kJSObjectType);
801 STATIC_ASSERT(FIRST_NONSTRING_TYPE == Internals::kFirstNonstringType);
802 STATIC_ASSERT(ODDBALL_TYPE == Internals::kOddballType);
803 STATIC_ASSERT(FOREIGN_TYPE == Internals::kForeignType);
806 #define FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(V) \
807 V(FAST_ELEMENTS_SUB_TYPE) \
808 V(DICTIONARY_ELEMENTS_SUB_TYPE) \
809 V(FAST_PROPERTIES_SUB_TYPE) \
810 V(DICTIONARY_PROPERTIES_SUB_TYPE) \
811 V(MAP_CODE_CACHE_SUB_TYPE) \
812 V(SCOPE_INFO_SUB_TYPE) \
813 V(STRING_TABLE_SUB_TYPE) \
814 V(DESCRIPTOR_ARRAY_SUB_TYPE) \
815 V(TRANSITION_ARRAY_SUB_TYPE)
817 enum FixedArraySubInstanceType {
818 #define DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE(name) name,
819 FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE)
820 #undef DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE
821 LAST_FIXED_ARRAY_SUB_TYPE = TRANSITION_ARRAY_SUB_TYPE
834 #define DECL_BOOLEAN_ACCESSORS(name) \
835 inline bool name() const; \
836 inline void set_##name(bool value); \
839 #define DECL_ACCESSORS(name, type) \
840 inline type* name() const; \
841 inline void set_##name(type* value, \
842 WriteBarrierMode mode = UPDATE_WRITE_BARRIER); \
845 #define DECLARE_CAST(type) \
846 INLINE(static type* cast(Object* object)); \
847 INLINE(static const type* cast(const Object* object));
851 class AllocationSite;
852 class AllocationSiteCreationContext;
853 class AllocationSiteUsageContext;
856 class ElementsAccessor;
857 class FixedArrayBase;
858 class FunctionLiteral;
860 class JSBuiltinsObject;
861 class LayoutDescriptor;
862 class LookupIterator;
863 class ObjectHashTable;
866 class SafepointEntry;
867 class SharedFunctionInfo;
869 class TypeFeedbackInfo;
870 class TypeFeedbackVector;
873 // We cannot just say "class HeapType;" if it is created from a template... =8-?
874 template<class> class TypeImpl;
875 struct HeapTypeConfig;
876 typedef TypeImpl<HeapTypeConfig> HeapType;
879 // A template-ized version of the IsXXX functions.
880 template <class C> inline bool Is(Object* obj);
883 #define DECLARE_VERIFIER(Name) void Name##Verify();
885 #define DECLARE_VERIFIER(Name)
889 #define DECLARE_PRINTER(Name) void Name##Print(std::ostream& os); // NOLINT
891 #define DECLARE_PRINTER(Name)
895 #define OBJECT_TYPE_LIST(V) \
900 #define HEAP_OBJECT_TYPE_LIST(V) \
902 V(MutableHeapNumber) \
918 V(ExternalTwoByteString) \
919 V(ExternalOneByteString) \
920 V(SeqTwoByteString) \
921 V(SeqOneByteString) \
922 V(InternalizedString) \
925 V(FixedTypedArrayBase) \
928 V(FixedUint16Array) \
930 V(FixedUint32Array) \
932 V(FixedFloat32Array) \
933 V(FixedFloat64Array) \
934 V(FixedUint8ClampedArray) \
940 V(JSContextExtensionObject) \
941 V(JSGeneratorObject) \
943 V(LayoutDescriptor) \
947 V(TypeFeedbackVector) \
948 V(DeoptimizationInputData) \
949 V(DeoptimizationOutputData) \
953 V(FixedDoubleArray) \
957 V(ScriptContextTable) \
963 V(SharedFunctionInfo) \
972 V(JSArrayBufferView) \
981 V(JSWeakCollection) \
988 V(NormalizedMapCache) \
989 V(CompilationCacheTable) \
990 V(CodeCacheHashTable) \
991 V(PolymorphicCodeCacheHashTable) \
996 V(JSBuiltinsObject) \
998 V(UndetectableObject) \
999 V(AccessCheckNeeded) \
1003 V(ObjectHashTable) \
1005 V(WeakValueHashTable) \
1008 // Object is the abstract superclass for all classes in the
1009 // object hierarchy.
1010 // Object does not use any virtual functions to avoid the
1011 // allocation of the C++ vtable.
1012 // Since both Smi and HeapObject are subclasses of Object no
1013 // data members can be present in Object.
1017 bool IsObject() const { return true; }
1019 #define IS_TYPE_FUNCTION_DECL(type_) INLINE(bool Is##type_() const);
1020 OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1021 HEAP_OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1022 #undef IS_TYPE_FUNCTION_DECL
1024 // A non-keyed store is of the form a.x = foo or a["x"] = foo whereas
1025 // a keyed store is of the form a[expression] = foo.
1026 enum StoreFromKeyed {
1027 MAY_BE_STORE_FROM_KEYED,
1028 CERTAINLY_NOT_STORE_FROM_KEYED
1031 INLINE(bool IsFixedArrayBase() const);
1032 INLINE(bool IsExternal() const);
1033 INLINE(bool IsAccessorInfo() const);
1035 INLINE(bool IsStruct() const);
1036 #define DECLARE_STRUCT_PREDICATE(NAME, Name, name) \
1037 INLINE(bool Is##Name() const);
1038 STRUCT_LIST(DECLARE_STRUCT_PREDICATE)
1039 #undef DECLARE_STRUCT_PREDICATE
1041 INLINE(bool IsSpecObject()) const;
1042 INLINE(bool IsSpecFunction()) const;
1043 INLINE(bool IsTemplateInfo()) const;
1044 INLINE(bool IsNameDictionary() const);
1045 INLINE(bool IsGlobalDictionary() const);
1046 INLINE(bool IsSeededNumberDictionary() const);
1047 INLINE(bool IsUnseededNumberDictionary() const);
1048 INLINE(bool IsOrderedHashSet() const);
1049 INLINE(bool IsOrderedHashMap() const);
1050 bool IsCallable() const;
1051 static bool IsPromise(Handle<Object> object);
1054 INLINE(bool IsUndefined() const);
1055 INLINE(bool IsNull() const);
1056 INLINE(bool IsTheHole() const);
1057 INLINE(bool IsException() const);
1058 INLINE(bool IsUninitialized() const);
1059 INLINE(bool IsTrue() const);
1060 INLINE(bool IsFalse() const);
1061 INLINE(bool IsArgumentsMarker() const);
1063 // Filler objects (fillers and free space objects).
1064 INLINE(bool IsFiller() const);
1066 // Extract the number.
1067 inline double Number();
1068 INLINE(bool IsNaN() const);
1069 INLINE(bool IsMinusZero() const);
1070 bool ToInt32(int32_t* value);
1071 bool ToUint32(uint32_t* value);
1073 inline Representation OptimalRepresentation() {
1074 if (!FLAG_track_fields) return Representation::Tagged();
1076 return Representation::Smi();
1077 } else if (FLAG_track_double_fields && IsHeapNumber()) {
1078 return Representation::Double();
1079 } else if (FLAG_track_computed_fields && IsUninitialized()) {
1080 return Representation::None();
1081 } else if (FLAG_track_heap_object_fields) {
1082 DCHECK(IsHeapObject());
1083 return Representation::HeapObject();
1085 return Representation::Tagged();
1089 inline ElementsKind OptimalElementsKind() {
1090 if (IsSmi()) return FAST_SMI_ELEMENTS;
1091 if (IsNumber()) return FAST_DOUBLE_ELEMENTS;
1092 return FAST_ELEMENTS;
1095 inline bool FitsRepresentation(Representation representation) {
1096 if (FLAG_track_fields && representation.IsNone()) {
1098 } else if (FLAG_track_fields && representation.IsSmi()) {
1100 } else if (FLAG_track_double_fields && representation.IsDouble()) {
1101 return IsMutableHeapNumber() || IsNumber();
1102 } else if (FLAG_track_heap_object_fields && representation.IsHeapObject()) {
1103 return IsHeapObject();
1108 // Checks whether two valid primitive encodings of a property name resolve to
1109 // the same logical property. E.g., the smi 1, the string "1" and the double
1110 // 1 all refer to the same property, so this helper will return true.
1111 inline bool KeyEquals(Object* other);
1113 Handle<HeapType> OptimalType(Isolate* isolate, Representation representation);
1115 inline static Handle<Object> NewStorageFor(Isolate* isolate,
1116 Handle<Object> object,
1117 Representation representation);
1119 inline static Handle<Object> WrapForRead(Isolate* isolate,
1120 Handle<Object> object,
1121 Representation representation);
1123 // Returns true if the object is of the correct type to be used as a
1124 // implementation of a JSObject's elements.
1125 inline bool HasValidElements();
1127 inline bool HasSpecificClassOf(String* name);
1129 bool BooleanValue(); // ECMA-262 9.2.
1131 // Convert to a JSObject if needed.
1132 // native_context is used when creating wrapper object.
1133 static inline MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1134 Handle<Object> object);
1135 static MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1136 Handle<Object> object,
1137 Handle<Context> context);
1139 MUST_USE_RESULT static MaybeHandle<Object> GetProperty(
1140 LookupIterator* it, LanguageMode language_mode = SLOPPY);
1142 // Implementation of [[Put]], ECMA-262 5th edition, section 8.12.5.
1143 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1144 Handle<Object> object, Handle<Name> name, Handle<Object> value,
1145 LanguageMode language_mode,
1146 StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
1148 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1149 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1150 StoreFromKeyed store_mode);
1152 MUST_USE_RESULT static MaybeHandle<Object> SetSuperProperty(
1153 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1154 StoreFromKeyed store_mode);
1156 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1157 LookupIterator* it, LanguageMode language_mode);
1158 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1159 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1160 LanguageMode language_mode);
1161 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1162 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1163 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1164 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1165 Handle<Object> value, LanguageMode language_mode);
1166 MUST_USE_RESULT static MaybeHandle<Object> RedefineNonconfigurableProperty(
1167 Isolate* isolate, Handle<Object> name, Handle<Object> value,
1168 LanguageMode language_mode);
1169 MUST_USE_RESULT static MaybeHandle<Object> SetDataProperty(
1170 LookupIterator* it, Handle<Object> value);
1171 MUST_USE_RESULT static MaybeHandle<Object> AddDataProperty(
1172 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1173 LanguageMode language_mode, StoreFromKeyed store_mode);
1174 MUST_USE_RESULT static inline MaybeHandle<Object> GetPropertyOrElement(
1175 Handle<Object> object, Handle<Name> name,
1176 LanguageMode language_mode = SLOPPY);
1177 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1178 Isolate* isolate, Handle<Object> object, const char* key,
1179 LanguageMode language_mode = SLOPPY);
1180 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1181 Handle<Object> object, Handle<Name> name,
1182 LanguageMode language_mode = SLOPPY);
1184 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithAccessor(
1185 LookupIterator* it, LanguageMode language_mode);
1186 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithAccessor(
1187 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1189 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithDefinedGetter(
1190 Handle<Object> receiver,
1191 Handle<JSReceiver> getter);
1192 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithDefinedSetter(
1193 Handle<Object> receiver,
1194 Handle<JSReceiver> setter,
1195 Handle<Object> value);
1197 MUST_USE_RESULT static inline MaybeHandle<Object> GetElement(
1198 Isolate* isolate, Handle<Object> object, uint32_t index,
1199 LanguageMode language_mode = SLOPPY);
1201 MUST_USE_RESULT static inline MaybeHandle<Object> SetElement(
1202 Isolate* isolate, Handle<Object> object, uint32_t index,
1203 Handle<Object> value, LanguageMode language_mode);
1205 static inline Handle<Object> GetPrototypeSkipHiddenPrototypes(
1206 Isolate* isolate, Handle<Object> receiver);
1208 // Returns the permanent hash code associated with this object. May return
1209 // undefined if not yet created.
1212 // Returns undefined for JSObjects, but returns the hash code for simple
1213 // objects. This avoids a double lookup in the cases where we know we will
1214 // add the hash to the JSObject if it does not already exist.
1215 Object* GetSimpleHash();
1217 // Returns the permanent hash code associated with this object depending on
1218 // the actual object type. May create and store a hash code if needed and none
1220 static Handle<Smi> GetOrCreateHash(Isolate* isolate, Handle<Object> object);
1222 // Checks whether this object has the same value as the given one. This
1223 // function is implemented according to ES5, section 9.12 and can be used
1224 // to implement the Harmony "egal" function.
1225 bool SameValue(Object* other);
1227 // Checks whether this object has the same value as the given one.
1228 // +0 and -0 are treated equal. Everything else is the same as SameValue.
1229 // This function is implemented according to ES6, section 7.2.4 and is used
1230 // by ES6 Map and Set.
1231 bool SameValueZero(Object* other);
1233 // Tries to convert an object to an array length. Returns true and sets the
1234 // output parameter if it succeeds.
1235 inline bool ToArrayLength(uint32_t* index);
1237 // Tries to convert an object to an array index. Returns true and sets the
1238 // output parameter if it succeeds. Equivalent to ToArrayLength, but does not
1239 // allow kMaxUInt32.
1240 inline bool ToArrayIndex(uint32_t* index);
1242 // Returns true if this is a JSValue containing a string and the index is
1243 // < the length of the string. Used to implement [] on strings.
1244 inline bool IsStringObjectWithCharacterAt(uint32_t index);
1246 DECLARE_VERIFIER(Object)
1248 // Verify a pointer is a valid object pointer.
1249 static void VerifyPointer(Object* p);
1252 inline void VerifyApiCallResultType();
1254 // Prints this object without details.
1255 void ShortPrint(FILE* out = stdout);
1257 // Prints this object without details to a message accumulator.
1258 void ShortPrint(StringStream* accumulator);
1260 void ShortPrint(std::ostream& os); // NOLINT
1262 DECLARE_CAST(Object)
1264 // Layout description.
1265 static const int kHeaderSize = 0; // Object does not take up any space.
1268 // For our gdb macros, we should perhaps change these in the future.
1271 // Prints this object with details.
1272 void Print(std::ostream& os); // NOLINT
1274 void Print() { ShortPrint(); }
1275 void Print(std::ostream& os) { ShortPrint(os); } // NOLINT
1279 friend class LookupIterator;
1280 friend class PrototypeIterator;
1282 // Return the map of the root of object's prototype chain.
1283 Map* GetRootMap(Isolate* isolate);
1285 // Helper for SetProperty and SetSuperProperty.
1286 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyInternal(
1287 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1288 StoreFromKeyed store_mode, bool* found);
1290 DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
1295 explicit Brief(const Object* const v) : value(v) {}
1296 const Object* value;
1300 std::ostream& operator<<(std::ostream& os, const Brief& v);
1303 // Smi represents integer Numbers that can be stored in 31 bits.
1304 // Smis are immediate which means they are NOT allocated in the heap.
1305 // The this pointer has the following format: [31 bit signed int] 0
1306 // For long smis it has the following format:
1307 // [32 bit signed int] [31 bits zero padding] 0
1308 // Smi stands for small integer.
1309 class Smi: public Object {
1311 // Returns the integer value.
1312 inline int value() const;
1314 // Convert a value to a Smi object.
1315 static inline Smi* FromInt(int value);
1317 static inline Smi* FromIntptr(intptr_t value);
1319 // Returns whether value can be represented in a Smi.
1320 static inline bool IsValid(intptr_t value);
1324 // Dispatched behavior.
1325 void SmiPrint(std::ostream& os) const; // NOLINT
1326 DECLARE_VERIFIER(Smi)
1328 static const int kMinValue =
1329 (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1330 static const int kMaxValue = -(kMinValue + 1);
1333 DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1337 // Heap objects typically have a map pointer in their first word. However,
1338 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1339 // encoded in the first word. The class MapWord is an abstraction of the
1340 // value in a heap object's first word.
1341 class MapWord BASE_EMBEDDED {
1343 // Normal state: the map word contains a map pointer.
1345 // Create a map word from a map pointer.
1346 static inline MapWord FromMap(const Map* map);
1348 // View this map word as a map pointer.
1349 inline Map* ToMap();
1352 // Scavenge collection: the map word of live objects in the from space
1353 // contains a forwarding address (a heap object pointer in the to space).
1355 // True if this map word is a forwarding address for a scavenge
1356 // collection. Only valid during a scavenge collection (specifically,
1357 // when all map words are heap object pointers, i.e. not during a full GC).
1358 inline bool IsForwardingAddress();
1360 // Create a map word from a forwarding address.
1361 static inline MapWord FromForwardingAddress(HeapObject* object);
1363 // View this map word as a forwarding address.
1364 inline HeapObject* ToForwardingAddress();
1366 static inline MapWord FromRawValue(uintptr_t value) {
1367 return MapWord(value);
1370 inline uintptr_t ToRawValue() {
1375 // HeapObject calls the private constructor and directly reads the value.
1376 friend class HeapObject;
1378 explicit MapWord(uintptr_t value) : value_(value) {}
1384 // The content of an heap object (except for the map pointer). kTaggedValues
1385 // objects can contain both heap pointers and Smis, kMixedValues can contain
1386 // heap pointers, Smis, and raw values (e.g. doubles or strings), and kRawValues
1387 // objects can contain raw values and Smis.
1388 enum class HeapObjectContents { kTaggedValues, kMixedValues, kRawValues };
1391 // HeapObject is the superclass for all classes describing heap allocated
1393 class HeapObject: public Object {
1395 // [map]: Contains a map which contains the object's reflective
1397 inline Map* map() const;
1398 inline void set_map(Map* value);
1399 // The no-write-barrier version. This is OK if the object is white and in
1400 // new space, or if the value is an immortal immutable object, like the maps
1401 // of primitive (non-JS) objects like strings, heap numbers etc.
1402 inline void set_map_no_write_barrier(Map* value);
1404 // Get the map using acquire load.
1405 inline Map* synchronized_map();
1406 inline MapWord synchronized_map_word() const;
1408 // Set the map using release store
1409 inline void synchronized_set_map(Map* value);
1410 inline void synchronized_set_map_no_write_barrier(Map* value);
1411 inline void synchronized_set_map_word(MapWord map_word);
1413 // During garbage collection, the map word of a heap object does not
1414 // necessarily contain a map pointer.
1415 inline MapWord map_word() const;
1416 inline void set_map_word(MapWord map_word);
1418 // The Heap the object was allocated in. Used also to access Isolate.
1419 inline Heap* GetHeap() const;
1421 // Convenience method to get current isolate.
1422 inline Isolate* GetIsolate() const;
1424 // Converts an address to a HeapObject pointer.
1425 static inline HeapObject* FromAddress(Address address);
1427 // Returns the address of this HeapObject.
1428 inline Address address();
1430 // Iterates over pointers contained in the object (including the Map)
1431 void Iterate(ObjectVisitor* v);
1433 // Iterates over all pointers contained in the object except the
1434 // first map pointer. The object type is given in the first
1435 // parameter. This function does not access the map pointer in the
1436 // object, and so is safe to call while the map pointer is modified.
1437 void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1439 // Returns the heap object's size in bytes
1442 // Indicates what type of values this heap object may contain.
1443 inline HeapObjectContents ContentType();
1445 // Given a heap object's map pointer, returns the heap size in bytes
1446 // Useful when the map pointer field is used for other purposes.
1448 inline int SizeFromMap(Map* map);
1450 // Returns the field at offset in obj, as a read/write Object* reference.
1451 // Does no checking, and is safe to use during GC, while maps are invalid.
1452 // Does not invoke write barrier, so should only be assigned to
1453 // during marking GC.
1454 static inline Object** RawField(HeapObject* obj, int offset);
1456 // Adds the |code| object related to |name| to the code cache of this map. If
1457 // this map is a dictionary map that is shared, the map copied and installed
1459 static void UpdateMapCodeCache(Handle<HeapObject> object,
1463 DECLARE_CAST(HeapObject)
1465 // Return the write barrier mode for this. Callers of this function
1466 // must be able to present a reference to an DisallowHeapAllocation
1467 // object as a sign that they are not going to use this function
1468 // from code that allocates and thus invalidates the returned write
1470 inline WriteBarrierMode GetWriteBarrierMode(
1471 const DisallowHeapAllocation& promise);
1473 // Dispatched behavior.
1474 void HeapObjectShortPrint(std::ostream& os); // NOLINT
1476 void PrintHeader(std::ostream& os, const char* id); // NOLINT
1478 DECLARE_PRINTER(HeapObject)
1479 DECLARE_VERIFIER(HeapObject)
1481 inline void VerifyObjectField(int offset);
1482 inline void VerifySmiField(int offset);
1484 // Verify a pointer is a valid HeapObject pointer that points to object
1485 // areas in the heap.
1486 static void VerifyHeapPointer(Object* p);
1489 inline AllocationAlignment RequiredAlignment();
1491 // Layout description.
1492 // First field in a heap object is map.
1493 static const int kMapOffset = Object::kHeaderSize;
1494 static const int kHeaderSize = kMapOffset + kPointerSize;
1496 STATIC_ASSERT(kMapOffset == Internals::kHeapObjectMapOffset);
1499 // helpers for calling an ObjectVisitor to iterate over pointers in the
1500 // half-open range [start, end) specified as integer offsets
1501 inline void IteratePointers(ObjectVisitor* v, int start, int end);
1502 // as above, for the single element at "offset"
1503 inline void IteratePointer(ObjectVisitor* v, int offset);
1504 // as above, for the next code link of a code object.
1505 inline void IterateNextCodeLink(ObjectVisitor* v, int offset);
1508 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1512 // This class describes a body of an object of a fixed size
1513 // in which all pointer fields are located in the [start_offset, end_offset)
1515 template<int start_offset, int end_offset, int size>
1516 class FixedBodyDescriptor {
1518 static const int kStartOffset = start_offset;
1519 static const int kEndOffset = end_offset;
1520 static const int kSize = size;
1522 static inline void IterateBody(HeapObject* obj, ObjectVisitor* v);
1524 template<typename StaticVisitor>
1525 static inline void IterateBody(HeapObject* obj) {
1526 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1527 HeapObject::RawField(obj, end_offset));
1532 // This class describes a body of an object of a variable size
1533 // in which all pointer fields are located in the [start_offset, object_size)
1535 template<int start_offset>
1536 class FlexibleBodyDescriptor {
1538 static const int kStartOffset = start_offset;
1540 static inline void IterateBody(HeapObject* obj,
1544 template<typename StaticVisitor>
1545 static inline void IterateBody(HeapObject* obj, int object_size) {
1546 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1547 HeapObject::RawField(obj, object_size));
1552 // The HeapNumber class describes heap allocated numbers that cannot be
1553 // represented in a Smi (small integer)
1554 class HeapNumber: public HeapObject {
1556 // [value]: number value.
1557 inline double value() const;
1558 inline void set_value(double value);
1560 DECLARE_CAST(HeapNumber)
1562 // Dispatched behavior.
1563 bool HeapNumberBooleanValue();
1565 void HeapNumberPrint(std::ostream& os); // NOLINT
1566 DECLARE_VERIFIER(HeapNumber)
1568 inline int get_exponent();
1569 inline int get_sign();
1571 // Layout description.
1572 static const int kValueOffset = HeapObject::kHeaderSize;
1573 // IEEE doubles are two 32 bit words. The first is just mantissa, the second
1574 // is a mixture of sign, exponent and mantissa. The offsets of two 32 bit
1575 // words within double numbers are endian dependent and they are set
1577 #if defined(V8_TARGET_LITTLE_ENDIAN)
1578 static const int kMantissaOffset = kValueOffset;
1579 static const int kExponentOffset = kValueOffset + 4;
1580 #elif defined(V8_TARGET_BIG_ENDIAN)
1581 static const int kMantissaOffset = kValueOffset + 4;
1582 static const int kExponentOffset = kValueOffset;
1584 #error Unknown byte ordering
1587 static const int kSize = kValueOffset + kDoubleSize;
1588 static const uint32_t kSignMask = 0x80000000u;
1589 static const uint32_t kExponentMask = 0x7ff00000u;
1590 static const uint32_t kMantissaMask = 0xfffffu;
1591 static const int kMantissaBits = 52;
1592 static const int kExponentBits = 11;
1593 static const int kExponentBias = 1023;
1594 static const int kExponentShift = 20;
1595 static const int kInfinityOrNanExponent =
1596 (kExponentMask >> kExponentShift) - kExponentBias;
1597 static const int kMantissaBitsInTopWord = 20;
1598 static const int kNonMantissaBitsInTopWord = 12;
1601 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
1605 // The SimdValue128 class describes heap allocated 128 bit SIMD values.
1606 class Simd128Value : public HeapObject {
1608 DECLARE_CAST(Simd128Value)
1610 // Checks that another instance is bit-wise equal.
1611 bool BitwiseEquals(const Simd128Value* other) const;
1612 // Computes a hash from the 128 bit value, viewed as 4 32-bit integers.
1613 uint32_t Hash() const;
1614 // Copies the 16 bytes of SIMD data to the destination address.
1615 void CopyBits(void* destination) const;
1617 // Layout description.
1618 static const int kValueOffset = HeapObject::kHeaderSize;
1619 static const int kSize = kValueOffset + kSimd128Size;
1622 DISALLOW_IMPLICIT_CONSTRUCTORS(Simd128Value);
1626 #define SIMD128_TYPES(V) \
1627 V(Float32x4, float32x4, 4, float) \
1628 V(Int32x4, int32x4, 4, int32_t) \
1629 V(Bool32x4, bool32x4, 4, bool) \
1630 V(Int16x8, int16x8, 8, int16_t) \
1631 V(Bool16x8, bool16x8, 8, bool) \
1632 V(Int8x16, int8x16, 16, int8_t) \
1633 V(Bool8x16, bool8x16, 16, bool)
1635 #define SIMD128_VALUE_CLASS(name, type, lane_count, lane_type) \
1636 class name : public Simd128Value { \
1638 inline lane_type get_lane(int lane) const; \
1639 inline void set_lane(int lane, lane_type value); \
1641 DECLARE_CAST(name) \
1643 DECLARE_PRINTER(name) \
1644 DECLARE_VERIFIER(name) \
1647 DISALLOW_IMPLICIT_CONSTRUCTORS(name); \
1650 SIMD128_TYPES(SIMD128_VALUE_CLASS)
1653 enum EnsureElementsMode {
1654 DONT_ALLOW_DOUBLE_ELEMENTS,
1655 ALLOW_COPIED_DOUBLE_ELEMENTS,
1656 ALLOW_CONVERTED_DOUBLE_ELEMENTS
1660 // Indicator for one component of an AccessorPair.
1661 enum AccessorComponent {
1667 // JSReceiver includes types on which properties can be defined, i.e.,
1668 // JSObject and JSProxy.
1669 class JSReceiver: public HeapObject {
1671 DECLARE_CAST(JSReceiver)
1673 // Implementation of [[HasProperty]], ECMA-262 5th edition, section 8.12.6.
1674 MUST_USE_RESULT static inline Maybe<bool> HasProperty(
1675 Handle<JSReceiver> object, Handle<Name> name);
1676 MUST_USE_RESULT static inline Maybe<bool> HasOwnProperty(Handle<JSReceiver>,
1678 MUST_USE_RESULT static inline Maybe<bool> HasElement(
1679 Handle<JSReceiver> object, uint32_t index);
1680 MUST_USE_RESULT static inline Maybe<bool> HasOwnElement(
1681 Handle<JSReceiver> object, uint32_t index);
1683 // Implementation of [[Delete]], ECMA-262 5th edition, section 8.12.7.
1684 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyOrElement(
1685 Handle<JSReceiver> object, Handle<Name> name,
1686 LanguageMode language_mode = SLOPPY);
1687 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1688 Handle<JSReceiver> object, Handle<Name> name,
1689 LanguageMode language_mode = SLOPPY);
1690 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1691 LookupIterator* it, LanguageMode language_mode);
1692 MUST_USE_RESULT static MaybeHandle<Object> DeleteElement(
1693 Handle<JSReceiver> object, uint32_t index,
1694 LanguageMode language_mode = SLOPPY);
1696 // Tests for the fast common case for property enumeration.
1697 bool IsSimpleEnum();
1699 // Returns the class name ([[Class]] property in the specification).
1700 String* class_name();
1702 // Returns the constructor name (the name (possibly, inferred name) of the
1703 // function that was used to instantiate the object).
1704 String* constructor_name();
1706 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetPropertyAttributes(
1707 Handle<JSReceiver> object, Handle<Name> name);
1708 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1709 GetOwnPropertyAttributes(Handle<JSReceiver> object, Handle<Name> name);
1711 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetElementAttributes(
1712 Handle<JSReceiver> object, uint32_t index);
1713 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1714 GetOwnElementAttributes(Handle<JSReceiver> object, uint32_t index);
1716 MUST_USE_RESULT static Maybe<PropertyAttributes> GetPropertyAttributes(
1717 LookupIterator* it);
1720 static Handle<Object> GetDataProperty(Handle<JSReceiver> object,
1722 static Handle<Object> GetDataProperty(LookupIterator* it);
1725 // Retrieves a permanent object identity hash code. The undefined value might
1726 // be returned in case no hash was created yet.
1727 inline Object* GetIdentityHash();
1729 // Retrieves a permanent object identity hash code. May create and store a
1730 // hash code if needed and none exists.
1731 inline static Handle<Smi> GetOrCreateIdentityHash(
1732 Handle<JSReceiver> object);
1734 enum KeyCollectionType { OWN_ONLY, INCLUDE_PROTOS };
1736 // Computes the enumerable keys for a JSObject. Used for implementing
1737 // "for (n in object) { }".
1738 MUST_USE_RESULT static MaybeHandle<FixedArray> GetKeys(
1739 Handle<JSReceiver> object,
1740 KeyCollectionType type);
1743 DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
1747 // The JSObject describes real heap allocated JavaScript objects with
1749 // Note that the map of JSObject changes during execution to enable inline
1751 class JSObject: public JSReceiver {
1753 // [properties]: Backing storage for properties.
1754 // properties is a FixedArray in the fast case and a Dictionary in the
1756 DECL_ACCESSORS(properties, FixedArray) // Get and set fast properties.
1757 inline void initialize_properties();
1758 inline bool HasFastProperties();
1759 // Gets slow properties for non-global objects.
1760 inline NameDictionary* property_dictionary();
1761 // Gets global object properties.
1762 inline GlobalDictionary* global_dictionary();
1764 // [elements]: The elements (properties with names that are integers).
1766 // Elements can be in two general modes: fast and slow. Each mode
1767 // corrensponds to a set of object representations of elements that
1768 // have something in common.
1770 // In the fast mode elements is a FixedArray and so each element can
1771 // be quickly accessed. This fact is used in the generated code. The
1772 // elements array can have one of three maps in this mode:
1773 // fixed_array_map, sloppy_arguments_elements_map or
1774 // fixed_cow_array_map (for copy-on-write arrays). In the latter case
1775 // the elements array may be shared by a few objects and so before
1776 // writing to any element the array must be copied. Use
1777 // EnsureWritableFastElements in this case.
1779 // In the slow mode the elements is either a NumberDictionary, a
1780 // FixedArray parameter map for a (sloppy) arguments object.
1781 DECL_ACCESSORS(elements, FixedArrayBase)
1782 inline void initialize_elements();
1783 static void ResetElements(Handle<JSObject> object);
1784 static inline void SetMapAndElements(Handle<JSObject> object,
1786 Handle<FixedArrayBase> elements);
1787 inline ElementsKind GetElementsKind();
1788 ElementsAccessor* GetElementsAccessor();
1789 // Returns true if an object has elements of FAST_SMI_ELEMENTS ElementsKind.
1790 inline bool HasFastSmiElements();
1791 // Returns true if an object has elements of FAST_ELEMENTS ElementsKind.
1792 inline bool HasFastObjectElements();
1793 // Returns true if an object has elements of FAST_ELEMENTS or
1794 // FAST_SMI_ONLY_ELEMENTS.
1795 inline bool HasFastSmiOrObjectElements();
1796 // Returns true if an object has any of the fast elements kinds.
1797 inline bool HasFastElements();
1798 // Returns true if an object has elements of FAST_DOUBLE_ELEMENTS
1800 inline bool HasFastDoubleElements();
1801 // Returns true if an object has elements of FAST_HOLEY_*_ELEMENTS
1803 inline bool HasFastHoleyElements();
1804 inline bool HasSloppyArgumentsElements();
1805 inline bool HasDictionaryElements();
1807 inline bool HasFixedTypedArrayElements();
1809 inline bool HasFixedUint8ClampedElements();
1810 inline bool HasFixedArrayElements();
1811 inline bool HasFixedInt8Elements();
1812 inline bool HasFixedUint8Elements();
1813 inline bool HasFixedInt16Elements();
1814 inline bool HasFixedUint16Elements();
1815 inline bool HasFixedInt32Elements();
1816 inline bool HasFixedUint32Elements();
1817 inline bool HasFixedFloat32Elements();
1818 inline bool HasFixedFloat64Elements();
1820 inline bool HasFastArgumentsElements();
1821 inline bool HasSlowArgumentsElements();
1822 inline SeededNumberDictionary* element_dictionary(); // Gets slow elements.
1824 // Requires: HasFastElements().
1825 static Handle<FixedArray> EnsureWritableFastElements(
1826 Handle<JSObject> object);
1828 // Collects elements starting at index 0.
1829 // Undefined values are placed after non-undefined values.
1830 // Returns the number of non-undefined values.
1831 static Handle<Object> PrepareElementsForSort(Handle<JSObject> object,
1833 // As PrepareElementsForSort, but only on objects where elements is
1834 // a dictionary, and it will stay a dictionary. Collates undefined and
1835 // unexisting elements below limit from position zero of the elements.
1836 static Handle<Object> PrepareSlowElementsForSort(Handle<JSObject> object,
1839 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithInterceptor(
1840 LookupIterator* it, Handle<Object> value);
1842 // SetLocalPropertyIgnoreAttributes converts callbacks to fields. We need to
1843 // grant an exemption to ExecutableAccessor callbacks in some cases.
1844 enum ExecutableAccessorInfoHandling { DEFAULT_HANDLING, DONT_FORCE_FIELD };
1846 MUST_USE_RESULT static MaybeHandle<Object> DefineOwnPropertyIgnoreAttributes(
1847 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1848 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1850 MUST_USE_RESULT static MaybeHandle<Object> SetOwnPropertyIgnoreAttributes(
1851 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1852 PropertyAttributes attributes,
1853 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1855 MUST_USE_RESULT static MaybeHandle<Object> SetOwnElementIgnoreAttributes(
1856 Handle<JSObject> object, uint32_t index, Handle<Object> value,
1857 PropertyAttributes attributes,
1858 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1860 // Equivalent to one of the above depending on whether |name| can be converted
1861 // to an array index.
1862 MUST_USE_RESULT static MaybeHandle<Object>
1863 DefinePropertyOrElementIgnoreAttributes(
1864 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1865 PropertyAttributes attributes = NONE,
1866 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1868 // Adds or reconfigures a property to attributes NONE. It will fail when it
1870 MUST_USE_RESULT static Maybe<bool> CreateDataProperty(LookupIterator* it,
1871 Handle<Object> value);
1873 static void AddProperty(Handle<JSObject> object, Handle<Name> name,
1874 Handle<Object> value, PropertyAttributes attributes);
1876 MUST_USE_RESULT static MaybeHandle<Object> AddDataElement(
1877 Handle<JSObject> receiver, uint32_t index, Handle<Object> value,
1878 PropertyAttributes attributes);
1880 // Extend the receiver with a single fast property appeared first in the
1881 // passed map. This also extends the property backing store if necessary.
1882 static void AllocateStorageForMap(Handle<JSObject> object, Handle<Map> map);
1884 // Migrates the given object to a map whose field representations are the
1885 // lowest upper bound of all known representations for that field.
1886 static void MigrateInstance(Handle<JSObject> instance);
1888 // Migrates the given object only if the target map is already available,
1889 // or returns false if such a map is not yet available.
1890 static bool TryMigrateInstance(Handle<JSObject> instance);
1892 // Sets the property value in a normalized object given (key, value, details).
1893 // Handles the special representation of JS global objects.
1894 static void SetNormalizedProperty(Handle<JSObject> object, Handle<Name> name,
1895 Handle<Object> value,
1896 PropertyDetails details);
1897 static void SetDictionaryElement(Handle<JSObject> object, uint32_t index,
1898 Handle<Object> value,
1899 PropertyAttributes attributes);
1900 static void SetDictionaryArgumentsElement(Handle<JSObject> object,
1902 Handle<Object> value,
1903 PropertyAttributes attributes);
1905 static void OptimizeAsPrototype(Handle<JSObject> object,
1906 PrototypeOptimizationMode mode);
1907 static void ReoptimizeIfPrototype(Handle<JSObject> object);
1908 static void LazyRegisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1909 static bool RegisterPrototypeUserIfNotRegistered(Handle<JSObject> prototype,
1910 Handle<HeapObject> user,
1912 static bool UnregisterPrototypeUser(Handle<JSObject> prototype,
1913 Handle<HeapObject> user);
1914 static void InvalidatePrototypeChains(Map* map);
1916 // Retrieve interceptors.
1917 InterceptorInfo* GetNamedInterceptor();
1918 InterceptorInfo* GetIndexedInterceptor();
1920 // Used from JSReceiver.
1921 MUST_USE_RESULT static Maybe<PropertyAttributes>
1922 GetPropertyAttributesWithInterceptor(LookupIterator* it);
1923 MUST_USE_RESULT static Maybe<PropertyAttributes>
1924 GetPropertyAttributesWithFailedAccessCheck(LookupIterator* it);
1926 // Retrieves an AccessorPair property from the given object. Might return
1927 // undefined if the property doesn't exist or is of a different kind.
1928 MUST_USE_RESULT static MaybeHandle<Object> GetAccessor(
1929 Handle<JSObject> object,
1931 AccessorComponent component);
1933 // Defines an AccessorPair property on the given object.
1934 // TODO(mstarzinger): Rename to SetAccessor().
1935 static MaybeHandle<Object> DefineAccessor(Handle<JSObject> object,
1937 Handle<Object> getter,
1938 Handle<Object> setter,
1939 PropertyAttributes attributes);
1941 // Defines an AccessorInfo property on the given object.
1942 MUST_USE_RESULT static MaybeHandle<Object> SetAccessor(
1943 Handle<JSObject> object,
1944 Handle<AccessorInfo> info);
1946 // The result must be checked first for exceptions. If there's no exception,
1947 // the output parameter |done| indicates whether the interceptor has a result
1949 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithInterceptor(
1950 LookupIterator* it, bool* done);
1952 // Accessors for hidden properties object.
1954 // Hidden properties are not own properties of the object itself.
1955 // Instead they are stored in an auxiliary structure kept as an own
1956 // property with a special name Heap::hidden_string(). But if the
1957 // receiver is a JSGlobalProxy then the auxiliary object is a property
1958 // of its prototype, and if it's a detached proxy, then you can't have
1959 // hidden properties.
1961 // Sets a hidden property on this object. Returns this object if successful,
1962 // undefined if called on a detached proxy.
1963 static Handle<Object> SetHiddenProperty(Handle<JSObject> object,
1965 Handle<Object> value);
1966 // Gets the value of a hidden property with the given key. Returns the hole
1967 // if the property doesn't exist (or if called on a detached proxy),
1968 // otherwise returns the value set for the key.
1969 Object* GetHiddenProperty(Handle<Name> key);
1970 // Deletes a hidden property. Deleting a non-existing property is
1971 // considered successful.
1972 static void DeleteHiddenProperty(Handle<JSObject> object,
1974 // Returns true if the object has a property with the hidden string as name.
1975 static bool HasHiddenProperties(Handle<JSObject> object);
1977 static void SetIdentityHash(Handle<JSObject> object, Handle<Smi> hash);
1979 static void ValidateElements(Handle<JSObject> object);
1981 // Makes sure that this object can contain HeapObject as elements.
1982 static inline void EnsureCanContainHeapObjectElements(Handle<JSObject> obj);
1984 // Makes sure that this object can contain the specified elements.
1985 static inline void EnsureCanContainElements(
1986 Handle<JSObject> object,
1989 EnsureElementsMode mode);
1990 static inline void EnsureCanContainElements(
1991 Handle<JSObject> object,
1992 Handle<FixedArrayBase> elements,
1994 EnsureElementsMode mode);
1995 static void EnsureCanContainElements(
1996 Handle<JSObject> object,
1997 Arguments* arguments,
2000 EnsureElementsMode mode);
2002 // Would we convert a fast elements array to dictionary mode given
2003 // an access at key?
2004 bool WouldConvertToSlowElements(uint32_t index);
2006 // Computes the new capacity when expanding the elements of a JSObject.
2007 static uint32_t NewElementsCapacity(uint32_t old_capacity) {
2008 // (old_capacity + 50%) + 16
2009 return old_capacity + (old_capacity >> 1) + 16;
2012 // These methods do not perform access checks!
2013 static void UpdateAllocationSite(Handle<JSObject> object,
2014 ElementsKind to_kind);
2016 // Lookup interceptors are used for handling properties controlled by host
2018 inline bool HasNamedInterceptor();
2019 inline bool HasIndexedInterceptor();
2021 // Computes the enumerable keys from interceptors. Used for debug mirrors and
2022 // by JSReceiver::GetKeys.
2023 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForNamedInterceptor(
2024 Handle<JSObject> object,
2025 Handle<JSReceiver> receiver);
2026 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForIndexedInterceptor(
2027 Handle<JSObject> object,
2028 Handle<JSReceiver> receiver);
2030 // Support functions for v8 api (needed for correct interceptor behavior).
2031 MUST_USE_RESULT static Maybe<bool> HasRealNamedProperty(
2032 Handle<JSObject> object, Handle<Name> name);
2033 MUST_USE_RESULT static Maybe<bool> HasRealElementProperty(
2034 Handle<JSObject> object, uint32_t index);
2035 MUST_USE_RESULT static Maybe<bool> HasRealNamedCallbackProperty(
2036 Handle<JSObject> object, Handle<Name> name);
2038 // Get the header size for a JSObject. Used to compute the index of
2039 // internal fields as well as the number of internal fields.
2040 inline int GetHeaderSize();
2042 inline int GetInternalFieldCount();
2043 inline int GetInternalFieldOffset(int index);
2044 inline Object* GetInternalField(int index);
2045 inline void SetInternalField(int index, Object* value);
2046 inline void SetInternalField(int index, Smi* value);
2048 // Returns the number of properties on this object filtering out properties
2049 // with the specified attributes (ignoring interceptors).
2050 int NumberOfOwnProperties(PropertyAttributes filter = NONE);
2051 // Fill in details for properties into storage starting at the specified
2052 // index. Returns the number of properties added.
2053 int GetOwnPropertyNames(FixedArray* storage, int index,
2054 PropertyAttributes filter = NONE);
2056 // Returns the number of properties on this object filtering out properties
2057 // with the specified attributes (ignoring interceptors).
2058 int NumberOfOwnElements(PropertyAttributes filter);
2059 // Returns the number of enumerable elements (ignoring interceptors).
2060 int NumberOfEnumElements();
2061 // Returns the number of elements on this object filtering out elements
2062 // with the specified attributes (ignoring interceptors).
2063 int GetOwnElementKeys(FixedArray* storage, PropertyAttributes filter);
2064 // Count and fill in the enumerable elements into storage.
2065 // (storage->length() == NumberOfEnumElements()).
2066 // If storage is NULL, will count the elements without adding
2067 // them to any storage.
2068 // Returns the number of enumerable elements.
2069 int GetEnumElementKeys(FixedArray* storage);
2071 static Handle<FixedArray> GetEnumPropertyKeys(Handle<JSObject> object,
2074 // Returns a new map with all transitions dropped from the object's current
2075 // map and the ElementsKind set.
2076 static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
2077 ElementsKind to_kind);
2078 static void TransitionElementsKind(Handle<JSObject> object,
2079 ElementsKind to_kind);
2081 // Always use this to migrate an object to a new map.
2082 // |expected_additional_properties| is only used for fast-to-slow transitions
2083 // and ignored otherwise.
2084 static void MigrateToMap(Handle<JSObject> object, Handle<Map> new_map,
2085 int expected_additional_properties = 0);
2087 // Convert the object to use the canonical dictionary
2088 // representation. If the object is expected to have additional properties
2089 // added this number can be indicated to have the backing store allocated to
2090 // an initial capacity for holding these properties.
2091 static void NormalizeProperties(Handle<JSObject> object,
2092 PropertyNormalizationMode mode,
2093 int expected_additional_properties,
2094 const char* reason);
2096 // Convert and update the elements backing store to be a
2097 // SeededNumberDictionary dictionary. Returns the backing after conversion.
2098 static Handle<SeededNumberDictionary> NormalizeElements(
2099 Handle<JSObject> object);
2101 void RequireSlowElements(SeededNumberDictionary* dictionary);
2103 // Transform slow named properties to fast variants.
2104 static void MigrateSlowToFast(Handle<JSObject> object,
2105 int unused_property_fields, const char* reason);
2107 inline bool IsUnboxedDoubleField(FieldIndex index);
2109 // Access fast-case object properties at index.
2110 static Handle<Object> FastPropertyAt(Handle<JSObject> object,
2111 Representation representation,
2113 inline Object* RawFastPropertyAt(FieldIndex index);
2114 inline double RawFastDoublePropertyAt(FieldIndex index);
2116 inline void FastPropertyAtPut(FieldIndex index, Object* value);
2117 inline void RawFastPropertyAtPut(FieldIndex index, Object* value);
2118 inline void RawFastDoublePropertyAtPut(FieldIndex index, double value);
2119 inline void WriteToField(int descriptor, Object* value);
2121 // Access to in object properties.
2122 inline int GetInObjectPropertyOffset(int index);
2123 inline Object* InObjectPropertyAt(int index);
2124 inline Object* InObjectPropertyAtPut(int index,
2126 WriteBarrierMode mode
2127 = UPDATE_WRITE_BARRIER);
2129 // Set the object's prototype (only JSReceiver and null are allowed values).
2130 MUST_USE_RESULT static MaybeHandle<Object> SetPrototype(
2131 Handle<JSObject> object, Handle<Object> value, bool from_javascript);
2133 // Initializes the body after properties slot, properties slot is
2134 // initialized by set_properties. Fill the pre-allocated fields with
2135 // pre_allocated_value and the rest with filler_value.
2136 // Note: this call does not update write barrier, the caller is responsible
2137 // to ensure that |filler_value| can be collected without WB here.
2138 inline void InitializeBody(Map* map,
2139 Object* pre_allocated_value,
2140 Object* filler_value);
2142 // Check whether this object references another object
2143 bool ReferencesObject(Object* obj);
2145 // Disalow further properties to be added to the oject.
2146 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensions(
2147 Handle<JSObject> object);
2149 bool IsExtensible();
2152 MUST_USE_RESULT static MaybeHandle<Object> Seal(Handle<JSObject> object);
2154 // ES5 Object.freeze
2155 MUST_USE_RESULT static MaybeHandle<Object> Freeze(Handle<JSObject> object);
2157 // Called the first time an object is observed with ES7 Object.observe.
2158 static void SetObserved(Handle<JSObject> object);
2161 enum DeepCopyHints { kNoHints = 0, kObjectIsShallow = 1 };
2163 MUST_USE_RESULT static MaybeHandle<JSObject> DeepCopy(
2164 Handle<JSObject> object,
2165 AllocationSiteUsageContext* site_context,
2166 DeepCopyHints hints = kNoHints);
2167 MUST_USE_RESULT static MaybeHandle<JSObject> DeepWalk(
2168 Handle<JSObject> object,
2169 AllocationSiteCreationContext* site_context);
2171 DECLARE_CAST(JSObject)
2173 // Dispatched behavior.
2174 void JSObjectShortPrint(StringStream* accumulator);
2175 DECLARE_PRINTER(JSObject)
2176 DECLARE_VERIFIER(JSObject)
2178 void PrintProperties(std::ostream& os); // NOLINT
2179 void PrintElements(std::ostream& os); // NOLINT
2181 #if defined(DEBUG) || defined(OBJECT_PRINT)
2182 void PrintTransitions(std::ostream& os); // NOLINT
2185 static void PrintElementsTransition(
2186 FILE* file, Handle<JSObject> object,
2187 ElementsKind from_kind, Handle<FixedArrayBase> from_elements,
2188 ElementsKind to_kind, Handle<FixedArrayBase> to_elements);
2190 void PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map);
2193 // Structure for collecting spill information about JSObjects.
2194 class SpillInformation {
2198 int number_of_objects_;
2199 int number_of_objects_with_fast_properties_;
2200 int number_of_objects_with_fast_elements_;
2201 int number_of_fast_used_fields_;
2202 int number_of_fast_unused_fields_;
2203 int number_of_slow_used_properties_;
2204 int number_of_slow_unused_properties_;
2205 int number_of_fast_used_elements_;
2206 int number_of_fast_unused_elements_;
2207 int number_of_slow_used_elements_;
2208 int number_of_slow_unused_elements_;
2211 void IncrementSpillStatistics(SpillInformation* info);
2215 // If a GC was caused while constructing this object, the elements pointer
2216 // may point to a one pointer filler map. The object won't be rooted, but
2217 // our heap verification code could stumble across it.
2218 bool ElementsAreSafeToExamine();
2221 Object* SlowReverseLookup(Object* value);
2223 // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2224 // Also maximal value of JSArray's length property.
2225 static const uint32_t kMaxElementCount = 0xffffffffu;
2227 // Constants for heuristics controlling conversion of fast elements
2228 // to slow elements.
2230 // Maximal gap that can be introduced by adding an element beyond
2231 // the current elements length.
2232 static const uint32_t kMaxGap = 1024;
2234 // Maximal length of fast elements array that won't be checked for
2235 // being dense enough on expansion.
2236 static const int kMaxUncheckedFastElementsLength = 5000;
2238 // Same as above but for old arrays. This limit is more strict. We
2239 // don't want to be wasteful with long lived objects.
2240 static const int kMaxUncheckedOldFastElementsLength = 500;
2242 // Note that Page::kMaxRegularHeapObjectSize puts a limit on
2243 // permissible values (see the DCHECK in heap.cc).
2244 static const int kInitialMaxFastElementArray = 100000;
2246 // This constant applies only to the initial map of "global.Object" and
2247 // not to arbitrary other JSObject maps.
2248 static const int kInitialGlobalObjectUnusedPropertiesCount = 4;
2250 static const int kMaxInstanceSize = 255 * kPointerSize;
2251 // When extending the backing storage for property values, we increase
2252 // its size by more than the 1 entry necessary, so sequentially adding fields
2253 // to the same object requires fewer allocations and copies.
2254 static const int kFieldsAdded = 3;
2256 // Layout description.
2257 static const int kPropertiesOffset = HeapObject::kHeaderSize;
2258 static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2259 static const int kHeaderSize = kElementsOffset + kPointerSize;
2261 STATIC_ASSERT(kHeaderSize == Internals::kJSObjectHeaderSize);
2263 class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2265 static inline int SizeOf(Map* map, HeapObject* object);
2268 Context* GetCreationContext();
2270 // Enqueue change record for Object.observe. May cause GC.
2271 MUST_USE_RESULT static MaybeHandle<Object> EnqueueChangeRecord(
2272 Handle<JSObject> object, const char* type, Handle<Name> name,
2273 Handle<Object> old_value);
2275 // Gets the number of currently used elements.
2276 int GetFastElementsUsage();
2278 // Deletes an existing named property in a normalized object.
2279 static void DeleteNormalizedProperty(Handle<JSObject> object,
2280 Handle<Name> name, int entry);
2282 static bool AllCanRead(LookupIterator* it);
2283 static bool AllCanWrite(LookupIterator* it);
2286 friend class JSReceiver;
2287 friend class Object;
2289 static void MigrateFastToFast(Handle<JSObject> object, Handle<Map> new_map);
2290 static void MigrateFastToSlow(Handle<JSObject> object,
2291 Handle<Map> new_map,
2292 int expected_additional_properties);
2294 // Used from Object::GetProperty().
2295 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithFailedAccessCheck(
2296 LookupIterator* it);
2298 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithFailedAccessCheck(
2299 LookupIterator* it, Handle<Object> value);
2301 // Add a property to a slow-case object.
2302 static void AddSlowProperty(Handle<JSObject> object,
2304 Handle<Object> value,
2305 PropertyAttributes attributes);
2307 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithInterceptor(
2308 LookupIterator* it);
2310 bool ReferencesObjectFromElements(FixedArray* elements,
2314 // Return the hash table backing store or the inline stored identity hash,
2315 // whatever is found.
2316 MUST_USE_RESULT Object* GetHiddenPropertiesHashTable();
2318 // Return the hash table backing store for hidden properties. If there is no
2319 // backing store, allocate one.
2320 static Handle<ObjectHashTable> GetOrCreateHiddenPropertiesHashtable(
2321 Handle<JSObject> object);
2323 // Set the hidden property backing store to either a hash table or
2324 // the inline-stored identity hash.
2325 static Handle<Object> SetHiddenPropertiesHashTable(
2326 Handle<JSObject> object,
2327 Handle<Object> value);
2329 MUST_USE_RESULT Object* GetIdentityHash();
2331 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSObject> object);
2333 static Handle<SeededNumberDictionary> GetNormalizedElementDictionary(
2334 Handle<JSObject> object, Handle<FixedArrayBase> elements);
2336 // Helper for fast versions of preventExtensions, seal, and freeze.
2337 // attrs is one of NONE, SEALED, or FROZEN (depending on the operation).
2338 template <PropertyAttributes attrs>
2339 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensionsWithTransition(
2340 Handle<JSObject> object);
2342 DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
2346 // Common superclass for FixedArrays that allow implementations to share
2347 // common accessors and some code paths.
2348 class FixedArrayBase: public HeapObject {
2350 // [length]: length of the array.
2351 inline int length() const;
2352 inline void set_length(int value);
2354 // Get and set the length using acquire loads and release stores.
2355 inline int synchronized_length() const;
2356 inline void synchronized_set_length(int value);
2358 DECLARE_CAST(FixedArrayBase)
2360 // Layout description.
2361 // Length is smi tagged when it is stored.
2362 static const int kLengthOffset = HeapObject::kHeaderSize;
2363 static const int kHeaderSize = kLengthOffset + kPointerSize;
2367 class FixedDoubleArray;
2368 class IncrementalMarking;
2371 // FixedArray describes fixed-sized arrays with element type Object*.
2372 class FixedArray: public FixedArrayBase {
2374 // Setter and getter for elements.
2375 inline Object* get(int index) const;
2376 void SetValue(uint32_t index, Object* value);
2377 static inline Handle<Object> get(Handle<FixedArray> array, int index);
2378 // Setter that uses write barrier.
2379 inline void set(int index, Object* value);
2380 inline bool is_the_hole(int index);
2382 // Setter that doesn't need write barrier.
2383 inline void set(int index, Smi* value);
2384 // Setter with explicit barrier mode.
2385 inline void set(int index, Object* value, WriteBarrierMode mode);
2387 // Setters for frequently used oddballs located in old space.
2388 inline void set_undefined(int index);
2389 inline void set_null(int index);
2390 inline void set_the_hole(int index);
2392 inline Object** GetFirstElementAddress();
2393 inline bool ContainsOnlySmisOrHoles();
2395 // Gives access to raw memory which stores the array's data.
2396 inline Object** data_start();
2398 inline void FillWithHoles(int from, int to);
2400 // Shrink length and insert filler objects.
2401 void Shrink(int length);
2403 enum KeyFilter { ALL_KEYS, NON_SYMBOL_KEYS };
2405 // Add the elements of a JSArray to this FixedArray.
2406 MUST_USE_RESULT static MaybeHandle<FixedArray> AddKeysFromArrayLike(
2407 Handle<FixedArray> content, Handle<JSObject> array,
2408 KeyFilter filter = ALL_KEYS);
2410 // Computes the union of keys and return the result.
2411 // Used for implementing "for (n in object) { }"
2412 MUST_USE_RESULT static MaybeHandle<FixedArray> UnionOfKeys(
2413 Handle<FixedArray> first,
2414 Handle<FixedArray> second);
2416 // Copy a sub array from the receiver to dest.
2417 void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
2419 // Garbage collection support.
2420 static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
2422 // Code Generation support.
2423 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2425 // Garbage collection support.
2426 Object** RawFieldOfElementAt(int index) {
2427 return HeapObject::RawField(this, OffsetOfElementAt(index));
2430 DECLARE_CAST(FixedArray)
2432 // Maximal allowed size, in bytes, of a single FixedArray.
2433 // Prevents overflowing size computations, as well as extreme memory
2435 static const int kMaxSize = 128 * MB * kPointerSize;
2436 // Maximally allowed length of a FixedArray.
2437 static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
2439 // Dispatched behavior.
2440 DECLARE_PRINTER(FixedArray)
2441 DECLARE_VERIFIER(FixedArray)
2443 // Checks if two FixedArrays have identical contents.
2444 bool IsEqualTo(FixedArray* other);
2447 // Swap two elements in a pair of arrays. If this array and the
2448 // numbers array are the same object, the elements are only swapped
2450 void SwapPairs(FixedArray* numbers, int i, int j);
2452 // Sort prefix of this array and the numbers array as pairs wrt. the
2453 // numbers. If the numbers array and the this array are the same
2454 // object, the prefix of this array is sorted.
2455 void SortPairs(FixedArray* numbers, uint32_t len);
2457 class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
2459 static inline int SizeOf(Map* map, HeapObject* object) {
2461 reinterpret_cast<FixedArray*>(object)->synchronized_length());
2466 // Set operation on FixedArray without using write barriers. Can
2467 // only be used for storing old space objects or smis.
2468 static inline void NoWriteBarrierSet(FixedArray* array,
2472 // Set operation on FixedArray without incremental write barrier. Can
2473 // only be used if the object is guaranteed to be white (whiteness witness
2475 static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
2480 STATIC_ASSERT(kHeaderSize == Internals::kFixedArrayHeaderSize);
2482 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
2486 // FixedDoubleArray describes fixed-sized arrays with element type double.
2487 class FixedDoubleArray: public FixedArrayBase {
2489 // Setter and getter for elements.
2490 inline double get_scalar(int index);
2491 inline uint64_t get_representation(int index);
2492 static inline Handle<Object> get(Handle<FixedDoubleArray> array, int index);
2493 // This accessor has to get a Number as |value|.
2494 void SetValue(uint32_t index, Object* value);
2495 inline void set(int index, double value);
2496 inline void set_the_hole(int index);
2498 // Checking for the hole.
2499 inline bool is_the_hole(int index);
2501 // Garbage collection support.
2502 inline static int SizeFor(int length) {
2503 return kHeaderSize + length * kDoubleSize;
2506 // Gives access to raw memory which stores the array's data.
2507 inline double* data_start();
2509 inline void FillWithHoles(int from, int to);
2511 // Code Generation support.
2512 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2514 DECLARE_CAST(FixedDoubleArray)
2516 // Maximal allowed size, in bytes, of a single FixedDoubleArray.
2517 // Prevents overflowing size computations, as well as extreme memory
2519 static const int kMaxSize = 512 * MB;
2520 // Maximally allowed length of a FixedArray.
2521 static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
2523 // Dispatched behavior.
2524 DECLARE_PRINTER(FixedDoubleArray)
2525 DECLARE_VERIFIER(FixedDoubleArray)
2528 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
2532 class WeakFixedArray : public FixedArray {
2534 enum SearchForDuplicates { kAlwaysAdd, kAddIfNotFound };
2536 // If |maybe_array| is not a WeakFixedArray, a fresh one will be allocated.
2537 static Handle<WeakFixedArray> Add(
2538 Handle<Object> maybe_array, Handle<HeapObject> value,
2539 SearchForDuplicates search_for_duplicates = kAlwaysAdd,
2540 bool* was_present = NULL);
2542 // Returns true if an entry was found and removed.
2543 bool Remove(Handle<HeapObject> value);
2547 inline Object* Get(int index) const;
2548 inline void Clear(int index);
2549 inline int Length() const;
2551 inline bool IsEmptySlot(int index) const;
2552 static Object* Empty() { return Smi::FromInt(0); }
2554 DECLARE_CAST(WeakFixedArray)
2557 static const int kLastUsedIndexIndex = 0;
2558 static const int kFirstIndex = 1;
2560 static Handle<WeakFixedArray> Allocate(
2561 Isolate* isolate, int size, Handle<WeakFixedArray> initialize_from);
2563 static void Set(Handle<WeakFixedArray> array, int index,
2564 Handle<HeapObject> value);
2565 inline void clear(int index);
2567 inline int last_used_index() const;
2568 inline void set_last_used_index(int index);
2570 // Disallow inherited setters.
2571 void set(int index, Smi* value);
2572 void set(int index, Object* value);
2573 void set(int index, Object* value, WriteBarrierMode mode);
2574 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakFixedArray);
2578 // Generic array grows dynamically with O(1) amortized insertion.
2579 class ArrayList : public FixedArray {
2583 // Use this if GC can delete elements from the array.
2584 kReloadLengthAfterAllocation,
2586 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj,
2587 AddMode mode = kNone);
2588 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj1,
2589 Handle<Object> obj2, AddMode = kNone);
2590 inline int Length();
2591 inline void SetLength(int length);
2592 inline Object* Get(int index);
2593 inline Object** Slot(int index);
2594 inline void Set(int index, Object* obj);
2595 inline void Clear(int index, Object* undefined);
2596 DECLARE_CAST(ArrayList)
2599 static Handle<ArrayList> EnsureSpace(Handle<ArrayList> array, int length);
2600 static const int kLengthIndex = 0;
2601 static const int kFirstIndex = 1;
2602 DISALLOW_IMPLICIT_CONSTRUCTORS(ArrayList);
2606 // DescriptorArrays are fixed arrays used to hold instance descriptors.
2607 // The format of the these objects is:
2608 // [0]: Number of descriptors
2609 // [1]: Either Smi(0) if uninitialized, or a pointer to small fixed array:
2610 // [0]: pointer to fixed array with enum cache
2611 // [1]: either Smi(0) or pointer to fixed array with indices
2613 // [2 + number of descriptors * kDescriptorSize]: start of slack
2614 class DescriptorArray: public FixedArray {
2616 // Returns true for both shared empty_descriptor_array and for smis, which the
2617 // map uses to encode additional bit fields when the descriptor array is not
2619 inline bool IsEmpty();
2621 // Returns the number of descriptors in the array.
2622 int number_of_descriptors() {
2623 DCHECK(length() >= kFirstIndex || IsEmpty());
2625 return len == 0 ? 0 : Smi::cast(get(kDescriptorLengthIndex))->value();
2628 int number_of_descriptors_storage() {
2630 return len == 0 ? 0 : (len - kFirstIndex) / kDescriptorSize;
2633 int NumberOfSlackDescriptors() {
2634 return number_of_descriptors_storage() - number_of_descriptors();
2637 inline void SetNumberOfDescriptors(int number_of_descriptors);
2638 inline int number_of_entries() { return number_of_descriptors(); }
2640 bool HasEnumCache() {
2641 return !IsEmpty() && !get(kEnumCacheIndex)->IsSmi();
2644 void CopyEnumCacheFrom(DescriptorArray* array) {
2645 set(kEnumCacheIndex, array->get(kEnumCacheIndex));
2648 FixedArray* GetEnumCache() {
2649 DCHECK(HasEnumCache());
2650 FixedArray* bridge = FixedArray::cast(get(kEnumCacheIndex));
2651 return FixedArray::cast(bridge->get(kEnumCacheBridgeCacheIndex));
2654 bool HasEnumIndicesCache() {
2655 if (IsEmpty()) return false;
2656 Object* object = get(kEnumCacheIndex);
2657 if (object->IsSmi()) return false;
2658 FixedArray* bridge = FixedArray::cast(object);
2659 return !bridge->get(kEnumCacheBridgeIndicesCacheIndex)->IsSmi();
2662 FixedArray* GetEnumIndicesCache() {
2663 DCHECK(HasEnumIndicesCache());
2664 FixedArray* bridge = FixedArray::cast(get(kEnumCacheIndex));
2665 return FixedArray::cast(bridge->get(kEnumCacheBridgeIndicesCacheIndex));
2668 Object** GetEnumCacheSlot() {
2669 DCHECK(HasEnumCache());
2670 return HeapObject::RawField(reinterpret_cast<HeapObject*>(this),
2674 void ClearEnumCache();
2676 // Initialize or change the enum cache,
2677 // using the supplied storage for the small "bridge".
2678 void SetEnumCache(FixedArray* bridge_storage,
2679 FixedArray* new_cache,
2680 Object* new_index_cache);
2682 bool CanHoldValue(int descriptor, Object* value);
2684 // Accessors for fetching instance descriptor at descriptor number.
2685 inline Name* GetKey(int descriptor_number);
2686 inline Object** GetKeySlot(int descriptor_number);
2687 inline Object* GetValue(int descriptor_number);
2688 inline void SetValue(int descriptor_number, Object* value);
2689 inline Object** GetValueSlot(int descriptor_number);
2690 static inline int GetValueOffset(int descriptor_number);
2691 inline Object** GetDescriptorStartSlot(int descriptor_number);
2692 inline Object** GetDescriptorEndSlot(int descriptor_number);
2693 inline PropertyDetails GetDetails(int descriptor_number);
2694 inline PropertyType GetType(int descriptor_number);
2695 inline int GetFieldIndex(int descriptor_number);
2696 inline HeapType* GetFieldType(int descriptor_number);
2697 inline Object* GetConstant(int descriptor_number);
2698 inline Object* GetCallbacksObject(int descriptor_number);
2699 inline AccessorDescriptor* GetCallbacks(int descriptor_number);
2701 inline Name* GetSortedKey(int descriptor_number);
2702 inline int GetSortedKeyIndex(int descriptor_number);
2703 inline void SetSortedKey(int pointer, int descriptor_number);
2704 inline void SetRepresentation(int descriptor_number,
2705 Representation representation);
2707 // Accessor for complete descriptor.
2708 inline void Get(int descriptor_number, Descriptor* desc);
2709 inline void Set(int descriptor_number, Descriptor* desc);
2710 void Replace(int descriptor_number, Descriptor* descriptor);
2712 // Append automatically sets the enumeration index. This should only be used
2713 // to add descriptors in bulk at the end, followed by sorting the descriptor
2715 inline void Append(Descriptor* desc);
2717 static Handle<DescriptorArray> CopyUpTo(Handle<DescriptorArray> desc,
2718 int enumeration_index,
2721 static Handle<DescriptorArray> CopyUpToAddAttributes(
2722 Handle<DescriptorArray> desc,
2723 int enumeration_index,
2724 PropertyAttributes attributes,
2727 // Sort the instance descriptors by the hash codes of their keys.
2730 // Search the instance descriptors for given name.
2731 INLINE(int Search(Name* name, int number_of_own_descriptors));
2733 // As the above, but uses DescriptorLookupCache and updates it when
2735 INLINE(int SearchWithCache(Name* name, Map* map));
2737 // Allocates a DescriptorArray, but returns the singleton
2738 // empty descriptor array object if number_of_descriptors is 0.
2739 static Handle<DescriptorArray> Allocate(Isolate* isolate,
2740 int number_of_descriptors,
2743 DECLARE_CAST(DescriptorArray)
2745 // Constant for denoting key was not found.
2746 static const int kNotFound = -1;
2748 static const int kDescriptorLengthIndex = 0;
2749 static const int kEnumCacheIndex = 1;
2750 static const int kFirstIndex = 2;
2752 // The length of the "bridge" to the enum cache.
2753 static const int kEnumCacheBridgeLength = 2;
2754 static const int kEnumCacheBridgeCacheIndex = 0;
2755 static const int kEnumCacheBridgeIndicesCacheIndex = 1;
2757 // Layout description.
2758 static const int kDescriptorLengthOffset = FixedArray::kHeaderSize;
2759 static const int kEnumCacheOffset = kDescriptorLengthOffset + kPointerSize;
2760 static const int kFirstOffset = kEnumCacheOffset + kPointerSize;
2762 // Layout description for the bridge array.
2763 static const int kEnumCacheBridgeCacheOffset = FixedArray::kHeaderSize;
2765 // Layout of descriptor.
2766 static const int kDescriptorKey = 0;
2767 static const int kDescriptorDetails = 1;
2768 static const int kDescriptorValue = 2;
2769 static const int kDescriptorSize = 3;
2771 #if defined(DEBUG) || defined(OBJECT_PRINT)
2772 // For our gdb macros, we should perhaps change these in the future.
2775 // Print all the descriptors.
2776 void PrintDescriptors(std::ostream& os); // NOLINT
2780 // Is the descriptor array sorted and without duplicates?
2781 bool IsSortedNoDuplicates(int valid_descriptors = -1);
2783 // Is the descriptor array consistent with the back pointers in targets?
2784 bool IsConsistentWithBackPointers(Map* current_map);
2786 // Are two DescriptorArrays equal?
2787 bool IsEqualTo(DescriptorArray* other);
2790 // Returns the fixed array length required to hold number_of_descriptors
2792 static int LengthFor(int number_of_descriptors) {
2793 return ToKeyIndex(number_of_descriptors);
2797 // WhitenessWitness is used to prove that a descriptor array is white
2798 // (unmarked), so incremental write barriers can be skipped because the
2799 // marking invariant cannot be broken and slots pointing into evacuation
2800 // candidates will be discovered when the object is scanned. A witness is
2801 // always stack-allocated right after creating an array. By allocating a
2802 // witness, incremental marking is globally disabled. The witness is then
2803 // passed along wherever needed to statically prove that the array is known to
2805 class WhitenessWitness {
2807 inline explicit WhitenessWitness(DescriptorArray* array);
2808 inline ~WhitenessWitness();
2811 IncrementalMarking* marking_;
2814 // An entry in a DescriptorArray, represented as an (array, index) pair.
2817 inline explicit Entry(DescriptorArray* descs, int index) :
2818 descs_(descs), index_(index) { }
2820 inline PropertyType type() { return descs_->GetType(index_); }
2821 inline Object* GetCallbackObject() { return descs_->GetValue(index_); }
2824 DescriptorArray* descs_;
2828 // Conversion from descriptor number to array indices.
2829 static int ToKeyIndex(int descriptor_number) {
2830 return kFirstIndex +
2831 (descriptor_number * kDescriptorSize) +
2835 static int ToDetailsIndex(int descriptor_number) {
2836 return kFirstIndex +
2837 (descriptor_number * kDescriptorSize) +
2841 static int ToValueIndex(int descriptor_number) {
2842 return kFirstIndex +
2843 (descriptor_number * kDescriptorSize) +
2847 // Transfer a complete descriptor from the src descriptor array to this
2848 // descriptor array.
2849 void CopyFrom(int index, DescriptorArray* src, const WhitenessWitness&);
2851 inline void Set(int descriptor_number,
2853 const WhitenessWitness&);
2855 // Swap first and second descriptor.
2856 inline void SwapSortedKeys(int first, int second);
2858 DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
2862 enum SearchMode { ALL_ENTRIES, VALID_ENTRIES };
2864 template <SearchMode search_mode, typename T>
2865 inline int Search(T* array, Name* name, int valid_entries = 0,
2866 int* out_insertion_index = NULL);
2869 // HashTable is a subclass of FixedArray that implements a hash table
2870 // that uses open addressing and quadratic probing.
2872 // In order for the quadratic probing to work, elements that have not
2873 // yet been used and elements that have been deleted are
2874 // distinguished. Probing continues when deleted elements are
2875 // encountered and stops when unused elements are encountered.
2877 // - Elements with key == undefined have not been used yet.
2878 // - Elements with key == the_hole have been deleted.
2880 // The hash table class is parameterized with a Shape and a Key.
2881 // Shape must be a class with the following interface:
2882 // class ExampleShape {
2884 // // Tells whether key matches other.
2885 // static bool IsMatch(Key key, Object* other);
2886 // // Returns the hash value for key.
2887 // static uint32_t Hash(Key key);
2888 // // Returns the hash value for object.
2889 // static uint32_t HashForObject(Key key, Object* object);
2890 // // Convert key to an object.
2891 // static inline Handle<Object> AsHandle(Isolate* isolate, Key key);
2892 // // The prefix size indicates number of elements in the beginning
2893 // // of the backing storage.
2894 // static const int kPrefixSize = ..;
2895 // // The Element size indicates number of elements per entry.
2896 // static const int kEntrySize = ..;
2898 // The prefix size indicates an amount of memory in the
2899 // beginning of the backing storage that can be used for non-element
2900 // information by subclasses.
2902 template<typename Key>
2905 static const bool UsesSeed = false;
2906 static uint32_t Hash(Key key) { return 0; }
2907 static uint32_t SeededHash(Key key, uint32_t seed) {
2911 static uint32_t HashForObject(Key key, Object* object) { return 0; }
2912 static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
2914 return HashForObject(key, object);
2919 class HashTableBase : public FixedArray {
2921 // Returns the number of elements in the hash table.
2922 int NumberOfElements() {
2923 return Smi::cast(get(kNumberOfElementsIndex))->value();
2926 // Returns the number of deleted elements in the hash table.
2927 int NumberOfDeletedElements() {
2928 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
2931 // Returns the capacity of the hash table.
2933 return Smi::cast(get(kCapacityIndex))->value();
2936 // ElementAdded should be called whenever an element is added to a
2938 void ElementAdded() { SetNumberOfElements(NumberOfElements() + 1); }
2940 // ElementRemoved should be called whenever an element is removed from
2942 void ElementRemoved() {
2943 SetNumberOfElements(NumberOfElements() - 1);
2944 SetNumberOfDeletedElements(NumberOfDeletedElements() + 1);
2946 void ElementsRemoved(int n) {
2947 SetNumberOfElements(NumberOfElements() - n);
2948 SetNumberOfDeletedElements(NumberOfDeletedElements() + n);
2951 // Computes the required capacity for a table holding the given
2952 // number of elements. May be more than HashTable::kMaxCapacity.
2953 static inline int ComputeCapacity(int at_least_space_for);
2955 // Tells whether k is a real key. The hole and undefined are not allowed
2956 // as keys and can be used to indicate missing or deleted elements.
2957 bool IsKey(Object* k) {
2958 return !k->IsTheHole() && !k->IsUndefined();
2961 // Compute the probe offset (quadratic probing).
2962 INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
2963 return (n + n * n) >> 1;
2966 static const int kNumberOfElementsIndex = 0;
2967 static const int kNumberOfDeletedElementsIndex = 1;
2968 static const int kCapacityIndex = 2;
2969 static const int kPrefixStartIndex = 3;
2971 // Constant used for denoting a absent entry.
2972 static const int kNotFound = -1;
2975 // Update the number of elements in the hash table.
2976 void SetNumberOfElements(int nof) {
2977 set(kNumberOfElementsIndex, Smi::FromInt(nof));
2980 // Update the number of deleted elements in the hash table.
2981 void SetNumberOfDeletedElements(int nod) {
2982 set(kNumberOfDeletedElementsIndex, Smi::FromInt(nod));
2985 // Returns probe entry.
2986 static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
2987 DCHECK(base::bits::IsPowerOfTwo32(size));
2988 return (hash + GetProbeOffset(number)) & (size - 1);
2991 inline static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
2992 return hash & (size - 1);
2995 inline static uint32_t NextProbe(
2996 uint32_t last, uint32_t number, uint32_t size) {
2997 return (last + number) & (size - 1);
3002 template <typename Derived, typename Shape, typename Key>
3003 class HashTable : public HashTableBase {
3006 inline uint32_t Hash(Key key) {
3007 if (Shape::UsesSeed) {
3008 return Shape::SeededHash(key, GetHeap()->HashSeed());
3010 return Shape::Hash(key);
3014 inline uint32_t HashForObject(Key key, Object* object) {
3015 if (Shape::UsesSeed) {
3016 return Shape::SeededHashForObject(key, GetHeap()->HashSeed(), object);
3018 return Shape::HashForObject(key, object);
3022 // Returns a new HashTable object.
3023 MUST_USE_RESULT static Handle<Derived> New(
3024 Isolate* isolate, int at_least_space_for,
3025 MinimumCapacity capacity_option = USE_DEFAULT_MINIMUM_CAPACITY,
3026 PretenureFlag pretenure = NOT_TENURED);
3028 DECLARE_CAST(HashTable)
3030 // Garbage collection support.
3031 void IteratePrefix(ObjectVisitor* visitor);
3032 void IterateElements(ObjectVisitor* visitor);
3034 // Find entry for key otherwise return kNotFound.
3035 inline int FindEntry(Key key);
3036 inline int FindEntry(Isolate* isolate, Key key, int32_t hash);
3037 int FindEntry(Isolate* isolate, Key key);
3039 // Rehashes the table in-place.
3040 void Rehash(Key key);
3042 // Returns the key at entry.
3043 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3045 static const int kElementsStartIndex = kPrefixStartIndex + Shape::kPrefixSize;
3046 static const int kEntrySize = Shape::kEntrySize;
3047 static const int kElementsStartOffset =
3048 kHeaderSize + kElementsStartIndex * kPointerSize;
3049 static const int kCapacityOffset =
3050 kHeaderSize + kCapacityIndex * kPointerSize;
3052 // Returns the index for an entry (of the key)
3053 static inline int EntryToIndex(int entry) {
3054 return (entry * kEntrySize) + kElementsStartIndex;
3058 friend class ObjectHashTable;
3060 // Find the entry at which to insert element with the given key that
3061 // has the given hash value.
3062 uint32_t FindInsertionEntry(uint32_t hash);
3064 // Attempt to shrink hash table after removal of key.
3065 MUST_USE_RESULT static Handle<Derived> Shrink(Handle<Derived> table, Key key);
3067 // Ensure enough space for n additional elements.
3068 MUST_USE_RESULT static Handle<Derived> EnsureCapacity(
3069 Handle<Derived> table,
3072 PretenureFlag pretenure = NOT_TENURED);
3074 // Sets the capacity of the hash table.
3075 void SetCapacity(int capacity) {
3076 // To scale a computed hash code to fit within the hash table, we
3077 // use bit-wise AND with a mask, so the capacity must be positive
3079 DCHECK(capacity > 0);
3080 DCHECK(capacity <= kMaxCapacity);
3081 set(kCapacityIndex, Smi::FromInt(capacity));
3084 // Maximal capacity of HashTable. Based on maximal length of underlying
3085 // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
3087 static const int kMaxCapacity =
3088 (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
3091 // Returns _expected_ if one of entries given by the first _probe_ probes is
3092 // equal to _expected_. Otherwise, returns the entry given by the probe
3094 uint32_t EntryForProbe(Key key, Object* k, int probe, uint32_t expected);
3096 void Swap(uint32_t entry1, uint32_t entry2, WriteBarrierMode mode);
3098 // Rehashes this hash-table into the new table.
3099 void Rehash(Handle<Derived> new_table, Key key);
3103 // HashTableKey is an abstract superclass for virtual key behavior.
3104 class HashTableKey {
3106 // Returns whether the other object matches this key.
3107 virtual bool IsMatch(Object* other) = 0;
3108 // Returns the hash value for this key.
3109 virtual uint32_t Hash() = 0;
3110 // Returns the hash value for object.
3111 virtual uint32_t HashForObject(Object* key) = 0;
3112 // Returns the key object for storing into the hash table.
3113 MUST_USE_RESULT virtual Handle<Object> AsHandle(Isolate* isolate) = 0;
3115 virtual ~HashTableKey() {}
3119 class StringTableShape : public BaseShape<HashTableKey*> {
3121 static inline bool IsMatch(HashTableKey* key, Object* value) {
3122 return key->IsMatch(value);
3125 static inline uint32_t Hash(HashTableKey* key) {
3129 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3130 return key->HashForObject(object);
3133 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3135 static const int kPrefixSize = 0;
3136 static const int kEntrySize = 1;
3139 class SeqOneByteString;
3143 // No special elements in the prefix and the element size is 1
3144 // because only the string itself (the key) needs to be stored.
3145 class StringTable: public HashTable<StringTable,
3149 // Find string in the string table. If it is not there yet, it is
3150 // added. The return value is the string found.
3151 static Handle<String> LookupString(Isolate* isolate, Handle<String> key);
3152 static Handle<String> LookupKey(Isolate* isolate, HashTableKey* key);
3153 static String* LookupKeyIfExists(Isolate* isolate, HashTableKey* key);
3155 // Tries to internalize given string and returns string handle on success
3156 // or an empty handle otherwise.
3157 MUST_USE_RESULT static MaybeHandle<String> InternalizeStringIfExists(
3159 Handle<String> string);
3161 // Looks up a string that is equal to the given string and returns
3162 // string handle if it is found, or an empty handle otherwise.
3163 MUST_USE_RESULT static MaybeHandle<String> LookupStringIfExists(
3165 Handle<String> str);
3166 MUST_USE_RESULT static MaybeHandle<String> LookupTwoCharsStringIfExists(
3171 static void EnsureCapacityForDeserialization(Isolate* isolate, int expected);
3173 DECLARE_CAST(StringTable)
3176 template <bool seq_one_byte>
3177 friend class JsonParser;
3179 DISALLOW_IMPLICIT_CONSTRUCTORS(StringTable);
3183 template <typename Derived, typename Shape, typename Key>
3184 class Dictionary: public HashTable<Derived, Shape, Key> {
3185 typedef HashTable<Derived, Shape, Key> DerivedHashTable;
3188 // Returns the value at entry.
3189 Object* ValueAt(int entry) {
3190 return this->get(Derived::EntryToIndex(entry) + 1);
3193 // Set the value for entry.
3194 void ValueAtPut(int entry, Object* value) {
3195 this->set(Derived::EntryToIndex(entry) + 1, value);
3198 // Returns the property details for the property at entry.
3199 PropertyDetails DetailsAt(int entry) {
3200 return Shape::DetailsAt(static_cast<Derived*>(this), entry);
3203 // Set the details for entry.
3204 void DetailsAtPut(int entry, PropertyDetails value) {
3205 Shape::DetailsAtPut(static_cast<Derived*>(this), entry, value);
3208 // Returns true if property at given entry is deleted.
3209 bool IsDeleted(int entry) {
3210 return Shape::IsDeleted(static_cast<Derived*>(this), entry);
3213 // Delete a property from the dictionary.
3214 static Handle<Object> DeleteProperty(Handle<Derived> dictionary, int entry);
3216 // Attempt to shrink the dictionary after deletion of key.
3217 MUST_USE_RESULT static inline Handle<Derived> Shrink(
3218 Handle<Derived> dictionary,
3220 return DerivedHashTable::Shrink(dictionary, key);
3224 // TODO(dcarney): templatize or move to SeededNumberDictionary
3225 void CopyValuesTo(FixedArray* elements);
3227 // Returns the number of elements in the dictionary filtering out properties
3228 // with the specified attributes.
3229 int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3231 // Returns the number of enumerable elements in the dictionary.
3232 int NumberOfEnumElements() {
3233 return NumberOfElementsFilterAttributes(
3234 static_cast<PropertyAttributes>(DONT_ENUM | SYMBOLIC));
3237 // Returns true if the dictionary contains any elements that are non-writable,
3238 // non-configurable, non-enumerable, or have getters/setters.
3239 bool HasComplexElements();
3241 enum SortMode { UNSORTED, SORTED };
3243 // Fill in details for properties into storage.
3244 // Returns the number of properties added.
3245 int CopyKeysTo(FixedArray* storage, int index, PropertyAttributes filter,
3246 SortMode sort_mode);
3248 // Copies enumerable keys to preallocated fixed array.
3249 void CopyEnumKeysTo(FixedArray* storage);
3251 // Accessors for next enumeration index.
3252 void SetNextEnumerationIndex(int index) {
3254 this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
3257 int NextEnumerationIndex() {
3258 return Smi::cast(this->get(kNextEnumerationIndexIndex))->value();
3261 // Creates a new dictionary.
3262 MUST_USE_RESULT static Handle<Derived> New(
3264 int at_least_space_for,
3265 PretenureFlag pretenure = NOT_TENURED);
3267 // Ensure enough space for n additional elements.
3268 static Handle<Derived> EnsureCapacity(Handle<Derived> obj, int n, Key key);
3271 void Print(std::ostream& os); // NOLINT
3273 // Returns the key (slow).
3274 Object* SlowReverseLookup(Object* value);
3276 // Sets the entry to (key, value) pair.
3277 inline void SetEntry(int entry,
3279 Handle<Object> value);
3280 inline void SetEntry(int entry,
3282 Handle<Object> value,
3283 PropertyDetails details);
3285 MUST_USE_RESULT static Handle<Derived> Add(
3286 Handle<Derived> dictionary,
3288 Handle<Object> value,
3289 PropertyDetails details);
3291 // Returns iteration indices array for the |dictionary|.
3292 // Values are direct indices in the |HashTable| array.
3293 static Handle<FixedArray> BuildIterationIndicesArray(
3294 Handle<Derived> dictionary);
3297 // Generic at put operation.
3298 MUST_USE_RESULT static Handle<Derived> AtPut(
3299 Handle<Derived> dictionary,
3301 Handle<Object> value);
3303 // Add entry to dictionary.
3304 static void AddEntry(
3305 Handle<Derived> dictionary,
3307 Handle<Object> value,
3308 PropertyDetails details,
3311 // Generate new enumeration indices to avoid enumeration index overflow.
3312 // Returns iteration indices array for the |dictionary|.
3313 static Handle<FixedArray> GenerateNewEnumerationIndices(
3314 Handle<Derived> dictionary);
3315 static const int kMaxNumberKeyIndex = DerivedHashTable::kPrefixStartIndex;
3316 static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
3320 template <typename Derived, typename Shape>
3321 class NameDictionaryBase : public Dictionary<Derived, Shape, Handle<Name> > {
3322 typedef Dictionary<Derived, Shape, Handle<Name> > DerivedDictionary;
3325 // Find entry for key, otherwise return kNotFound. Optimized version of
3326 // HashTable::FindEntry.
3327 int FindEntry(Handle<Name> key);
3331 template <typename Key>
3332 class BaseDictionaryShape : public BaseShape<Key> {
3334 template <typename Dictionary>
3335 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry) {
3336 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3337 DCHECK(entry >= 0); // Not found is -1, which is not caught by get().
3338 return PropertyDetails(
3339 Smi::cast(dict->get(Dictionary::EntryToIndex(entry) + 2)));
3342 template <typename Dictionary>
3343 static inline void DetailsAtPut(Dictionary* dict, int entry,
3344 PropertyDetails value) {
3345 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3346 dict->set(Dictionary::EntryToIndex(entry) + 2, value.AsSmi());
3349 template <typename Dictionary>
3350 static bool IsDeleted(Dictionary* dict, int entry) {
3354 template <typename Dictionary>
3355 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3356 Handle<Object> value, PropertyDetails details);
3360 class NameDictionaryShape : public BaseDictionaryShape<Handle<Name> > {
3362 static inline bool IsMatch(Handle<Name> key, Object* other);
3363 static inline uint32_t Hash(Handle<Name> key);
3364 static inline uint32_t HashForObject(Handle<Name> key, Object* object);
3365 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Name> key);
3366 static const int kPrefixSize = 2;
3367 static const int kEntrySize = 3;
3368 static const bool kIsEnumerable = true;
3372 class NameDictionary
3373 : public NameDictionaryBase<NameDictionary, NameDictionaryShape> {
3374 typedef NameDictionaryBase<NameDictionary, NameDictionaryShape>
3378 DECLARE_CAST(NameDictionary)
3380 inline static Handle<FixedArray> DoGenerateNewEnumerationIndices(
3381 Handle<NameDictionary> dictionary);
3385 class GlobalDictionaryShape : public NameDictionaryShape {
3387 static const int kEntrySize = 2; // Overrides NameDictionaryShape::kEntrySize
3389 template <typename Dictionary>
3390 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry);
3392 template <typename Dictionary>
3393 static inline void DetailsAtPut(Dictionary* dict, int entry,
3394 PropertyDetails value);
3396 template <typename Dictionary>
3397 static bool IsDeleted(Dictionary* dict, int entry);
3399 template <typename Dictionary>
3400 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3401 Handle<Object> value, PropertyDetails details);
3405 class GlobalDictionary
3406 : public NameDictionaryBase<GlobalDictionary, GlobalDictionaryShape> {
3408 DECLARE_CAST(GlobalDictionary)
3412 class NumberDictionaryShape : public BaseDictionaryShape<uint32_t> {
3414 static inline bool IsMatch(uint32_t key, Object* other);
3415 static inline Handle<Object> AsHandle(Isolate* isolate, uint32_t key);
3416 static const int kEntrySize = 3;
3417 static const bool kIsEnumerable = false;
3421 class SeededNumberDictionaryShape : public NumberDictionaryShape {
3423 static const bool UsesSeed = true;
3424 static const int kPrefixSize = 2;
3426 static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
3427 static inline uint32_t SeededHashForObject(uint32_t key,
3433 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
3435 static const int kPrefixSize = 0;
3437 static inline uint32_t Hash(uint32_t key);
3438 static inline uint32_t HashForObject(uint32_t key, Object* object);
3442 class SeededNumberDictionary
3443 : public Dictionary<SeededNumberDictionary,
3444 SeededNumberDictionaryShape,
3447 DECLARE_CAST(SeededNumberDictionary)
3449 // Type specific at put (default NONE attributes is used when adding).
3450 MUST_USE_RESULT static Handle<SeededNumberDictionary> AtNumberPut(
3451 Handle<SeededNumberDictionary> dictionary,
3453 Handle<Object> value);
3454 MUST_USE_RESULT static Handle<SeededNumberDictionary> AddNumberEntry(
3455 Handle<SeededNumberDictionary> dictionary,
3457 Handle<Object> value,
3458 PropertyDetails details);
3460 // Set an existing entry or add a new one if needed.
3461 // Return the updated dictionary.
3462 MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
3463 Handle<SeededNumberDictionary> dictionary,
3465 Handle<Object> value,
3466 PropertyDetails details);
3468 void UpdateMaxNumberKey(uint32_t key);
3470 // If slow elements are required we will never go back to fast-case
3471 // for the elements kept in this dictionary. We require slow
3472 // elements if an element has been added at an index larger than
3473 // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
3474 // when defining a getter or setter with a number key.
3475 inline bool requires_slow_elements();
3476 inline void set_requires_slow_elements();
3478 // Get the value of the max number key that has been added to this
3479 // dictionary. max_number_key can only be called if
3480 // requires_slow_elements returns false.
3481 inline uint32_t max_number_key();
3484 static const int kRequiresSlowElementsMask = 1;
3485 static const int kRequiresSlowElementsTagSize = 1;
3486 static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
3490 class UnseededNumberDictionary
3491 : public Dictionary<UnseededNumberDictionary,
3492 UnseededNumberDictionaryShape,
3495 DECLARE_CAST(UnseededNumberDictionary)
3497 // Type specific at put (default NONE attributes is used when adding).
3498 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AtNumberPut(
3499 Handle<UnseededNumberDictionary> dictionary,
3501 Handle<Object> value);
3502 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AddNumberEntry(
3503 Handle<UnseededNumberDictionary> dictionary,
3505 Handle<Object> value);
3507 // Set an existing entry or add a new one if needed.
3508 // Return the updated dictionary.
3509 MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
3510 Handle<UnseededNumberDictionary> dictionary,
3512 Handle<Object> value);
3516 class ObjectHashTableShape : public BaseShape<Handle<Object> > {
3518 static inline bool IsMatch(Handle<Object> key, Object* other);
3519 static inline uint32_t Hash(Handle<Object> key);
3520 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3521 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3522 static const int kPrefixSize = 0;
3523 static const int kEntrySize = 2;
3527 // ObjectHashTable maps keys that are arbitrary objects to object values by
3528 // using the identity hash of the key for hashing purposes.
3529 class ObjectHashTable: public HashTable<ObjectHashTable,
3530 ObjectHashTableShape,
3533 ObjectHashTable, ObjectHashTableShape, Handle<Object> > DerivedHashTable;
3535 DECLARE_CAST(ObjectHashTable)
3537 // Attempt to shrink hash table after removal of key.
3538 MUST_USE_RESULT static inline Handle<ObjectHashTable> Shrink(
3539 Handle<ObjectHashTable> table,
3540 Handle<Object> key);
3542 // Looks up the value associated with the given key. The hole value is
3543 // returned in case the key is not present.
3544 Object* Lookup(Handle<Object> key);
3545 Object* Lookup(Handle<Object> key, int32_t hash);
3546 Object* Lookup(Isolate* isolate, Handle<Object> key, int32_t hash);
3548 // Adds (or overwrites) the value associated with the given key.
3549 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3551 Handle<Object> value);
3552 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3553 Handle<Object> key, Handle<Object> value,
3556 // Returns an ObjectHashTable (possibly |table|) where |key| has been removed.
3557 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3560 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3561 Handle<Object> key, bool* was_present,
3565 friend class MarkCompactCollector;
3567 void AddEntry(int entry, Object* key, Object* value);
3568 void RemoveEntry(int entry);
3570 // Returns the index to the value of an entry.
3571 static inline int EntryToValueIndex(int entry) {
3572 return EntryToIndex(entry) + 1;
3577 // OrderedHashTable is a HashTable with Object keys that preserves
3578 // insertion order. There are Map and Set interfaces (OrderedHashMap
3579 // and OrderedHashTable, below). It is meant to be used by JSMap/JSSet.
3581 // Only Object* keys are supported, with Object::SameValueZero() used as the
3582 // equality operator and Object::GetHash() for the hash function.
3584 // Based on the "Deterministic Hash Table" as described by Jason Orendorff at
3585 // https://wiki.mozilla.org/User:Jorend/Deterministic_hash_tables
3586 // Originally attributed to Tyler Close.
3589 // [0]: bucket count
3590 // [1]: element count
3591 // [2]: deleted element count
3592 // [3..(3 + NumberOfBuckets() - 1)]: "hash table", where each item is an
3593 // offset into the data table (see below) where the
3594 // first item in this bucket is stored.
3595 // [3 + NumberOfBuckets()..length]: "data table", an array of length
3596 // Capacity() * kEntrySize, where the first entrysize
3597 // items are handled by the derived class and the
3598 // item at kChainOffset is another entry into the
3599 // data table indicating the next entry in this hash
3602 // When we transition the table to a new version we obsolete it and reuse parts
3603 // of the memory to store information how to transition an iterator to the new
3606 // Memory layout for obsolete table:
3607 // [0]: bucket count
3608 // [1]: Next newer table
3609 // [2]: Number of removed holes or -1 when the table was cleared.
3610 // [3..(3 + NumberOfRemovedHoles() - 1)]: The indexes of the removed holes.
3611 // [3 + NumberOfRemovedHoles()..length]: Not used
3613 template<class Derived, class Iterator, int entrysize>
3614 class OrderedHashTable: public FixedArray {
3616 // Returns an OrderedHashTable with a capacity of at least |capacity|.
3617 static Handle<Derived> Allocate(
3618 Isolate* isolate, int capacity, PretenureFlag pretenure = NOT_TENURED);
3620 // Returns an OrderedHashTable (possibly |table|) with enough space
3621 // to add at least one new element.
3622 static Handle<Derived> EnsureGrowable(Handle<Derived> table);
3624 // Returns an OrderedHashTable (possibly |table|) that's shrunken
3626 static Handle<Derived> Shrink(Handle<Derived> table);
3628 // Returns a new empty OrderedHashTable and records the clearing so that
3629 // exisiting iterators can be updated.
3630 static Handle<Derived> Clear(Handle<Derived> table);
3632 int NumberOfElements() {
3633 return Smi::cast(get(kNumberOfElementsIndex))->value();
3636 int NumberOfDeletedElements() {
3637 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3640 int UsedCapacity() { return NumberOfElements() + NumberOfDeletedElements(); }
3642 int NumberOfBuckets() {
3643 return Smi::cast(get(kNumberOfBucketsIndex))->value();
3646 // Returns an index into |this| for the given entry.
3647 int EntryToIndex(int entry) {
3648 return kHashTableStartIndex + NumberOfBuckets() + (entry * kEntrySize);
3651 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3654 return !get(kNextTableIndex)->IsSmi();
3657 // The next newer table. This is only valid if the table is obsolete.
3658 Derived* NextTable() {
3659 return Derived::cast(get(kNextTableIndex));
3662 // When the table is obsolete we store the indexes of the removed holes.
3663 int RemovedIndexAt(int index) {
3664 return Smi::cast(get(kRemovedHolesIndex + index))->value();
3667 static const int kNotFound = -1;
3668 static const int kMinCapacity = 4;
3670 static const int kNumberOfBucketsIndex = 0;
3671 static const int kNumberOfElementsIndex = kNumberOfBucketsIndex + 1;
3672 static const int kNumberOfDeletedElementsIndex = kNumberOfElementsIndex + 1;
3673 static const int kHashTableStartIndex = kNumberOfDeletedElementsIndex + 1;
3674 static const int kNextTableIndex = kNumberOfElementsIndex;
3676 static const int kNumberOfBucketsOffset =
3677 kHeaderSize + kNumberOfBucketsIndex * kPointerSize;
3678 static const int kNumberOfElementsOffset =
3679 kHeaderSize + kNumberOfElementsIndex * kPointerSize;
3680 static const int kNumberOfDeletedElementsOffset =
3681 kHeaderSize + kNumberOfDeletedElementsIndex * kPointerSize;
3682 static const int kHashTableStartOffset =
3683 kHeaderSize + kHashTableStartIndex * kPointerSize;
3684 static const int kNextTableOffset =
3685 kHeaderSize + kNextTableIndex * kPointerSize;
3687 static const int kEntrySize = entrysize + 1;
3688 static const int kChainOffset = entrysize;
3690 static const int kLoadFactor = 2;
3692 // NumberOfDeletedElements is set to kClearedTableSentinel when
3693 // the table is cleared, which allows iterator transitions to
3694 // optimize that case.
3695 static const int kClearedTableSentinel = -1;
3698 static Handle<Derived> Rehash(Handle<Derived> table, int new_capacity);
3700 void SetNumberOfBuckets(int num) {
3701 set(kNumberOfBucketsIndex, Smi::FromInt(num));
3704 void SetNumberOfElements(int num) {
3705 set(kNumberOfElementsIndex, Smi::FromInt(num));
3708 void SetNumberOfDeletedElements(int num) {
3709 set(kNumberOfDeletedElementsIndex, Smi::FromInt(num));
3713 return NumberOfBuckets() * kLoadFactor;
3716 void SetNextTable(Derived* next_table) {
3717 set(kNextTableIndex, next_table);
3720 void SetRemovedIndexAt(int index, int removed_index) {
3721 return set(kRemovedHolesIndex + index, Smi::FromInt(removed_index));
3724 static const int kRemovedHolesIndex = kHashTableStartIndex;
3726 static const int kMaxCapacity =
3727 (FixedArray::kMaxLength - kHashTableStartIndex)
3728 / (1 + (kEntrySize * kLoadFactor));
3732 class JSSetIterator;
3735 class OrderedHashSet: public OrderedHashTable<
3736 OrderedHashSet, JSSetIterator, 1> {
3738 DECLARE_CAST(OrderedHashSet)
3742 class JSMapIterator;
3745 class OrderedHashMap
3746 : public OrderedHashTable<OrderedHashMap, JSMapIterator, 2> {
3748 DECLARE_CAST(OrderedHashMap)
3750 Object* ValueAt(int entry) {
3751 return get(EntryToIndex(entry) + kValueOffset);
3754 static const int kValueOffset = 1;
3758 template <int entrysize>
3759 class WeakHashTableShape : public BaseShape<Handle<Object> > {
3761 static inline bool IsMatch(Handle<Object> key, Object* other);
3762 static inline uint32_t Hash(Handle<Object> key);
3763 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3764 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3765 static const int kPrefixSize = 0;
3766 static const int kEntrySize = entrysize;
3770 // WeakHashTable maps keys that are arbitrary heap objects to heap object
3771 // values. The table wraps the keys in weak cells and store values directly.
3772 // Thus it references keys weakly and values strongly.
3773 class WeakHashTable: public HashTable<WeakHashTable,
3774 WeakHashTableShape<2>,
3777 WeakHashTable, WeakHashTableShape<2>, Handle<Object> > DerivedHashTable;
3779 DECLARE_CAST(WeakHashTable)
3781 // Looks up the value associated with the given key. The hole value is
3782 // returned in case the key is not present.
3783 Object* Lookup(Handle<HeapObject> key);
3785 // Adds (or overwrites) the value associated with the given key. Mapping a
3786 // key to the hole value causes removal of the whole entry.
3787 MUST_USE_RESULT static Handle<WeakHashTable> Put(Handle<WeakHashTable> table,
3788 Handle<HeapObject> key,
3789 Handle<HeapObject> value);
3791 static Handle<FixedArray> GetValues(Handle<WeakHashTable> table);
3794 friend class MarkCompactCollector;
3796 void AddEntry(int entry, Handle<WeakCell> key, Handle<HeapObject> value);
3798 // Returns the index to the value of an entry.
3799 static inline int EntryToValueIndex(int entry) {
3800 return EntryToIndex(entry) + 1;
3805 class WeakValueHashTable : public ObjectHashTable {
3807 DECLARE_CAST(WeakValueHashTable)
3810 // Looks up the value associated with the given key. The hole value is
3811 // returned in case the key is not present.
3812 Object* LookupWeak(Handle<Object> key);
3815 // Adds (or overwrites) the value associated with the given key. Mapping a
3816 // key to the hole value causes removal of the whole entry.
3817 MUST_USE_RESULT static Handle<WeakValueHashTable> PutWeak(
3818 Handle<WeakValueHashTable> table, Handle<Object> key,
3819 Handle<HeapObject> value);
3821 static Handle<FixedArray> GetWeakValues(Handle<WeakValueHashTable> table);
3825 // ScopeInfo represents information about different scopes of a source
3826 // program and the allocation of the scope's variables. Scope information
3827 // is stored in a compressed form in ScopeInfo objects and is used
3828 // at runtime (stack dumps, deoptimization, etc.).
3830 // This object provides quick access to scope info details for runtime
3832 class ScopeInfo : public FixedArray {
3834 DECLARE_CAST(ScopeInfo)
3836 // Return the type of this scope.
3837 ScopeType scope_type();
3839 // Does this scope call eval?
3842 // Return the language mode of this scope.
3843 LanguageMode language_mode();
3845 // Does this scope make a sloppy eval call?
3846 bool CallsSloppyEval() { return CallsEval() && is_sloppy(language_mode()); }
3848 // Return the total number of locals allocated on the stack and in the
3849 // context. This includes the parameters that are allocated in the context.
3852 // Return the number of stack slots for code. This number consists of two
3854 // 1. One stack slot per stack allocated local.
3855 // 2. One stack slot for the function name if it is stack allocated.
3856 int StackSlotCount();
3858 // Return the number of context slots for code if a context is allocated. This
3859 // number consists of three parts:
3860 // 1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
3861 // 2. One context slot per context allocated local.
3862 // 3. One context slot for the function name if it is context allocated.
3863 // Parameters allocated in the context count as context allocated locals. If
3864 // no contexts are allocated for this scope ContextLength returns 0.
3865 int ContextLength();
3867 // Does this scope declare a "this" binding?
3870 // Does this scope declare a "this" binding, and the "this" binding is stack-
3871 // or context-allocated?
3872 bool HasAllocatedReceiver();
3874 // Is this scope the scope of a named function expression?
3875 bool HasFunctionName();
3877 // Return if this has context allocated locals.
3878 bool HasHeapAllocatedLocals();
3880 // Return if contexts are allocated for this scope.
3883 // Return if this is a function scope with "use asm".
3884 bool IsAsmModule() { return AsmModuleField::decode(Flags()); }
3886 // Return if this is a nested function within an asm module scope.
3887 bool IsAsmFunction() { return AsmFunctionField::decode(Flags()); }
3889 bool HasSimpleParameters() {
3890 return HasSimpleParametersField::decode(Flags());
3893 // Return the function_name if present.
3894 String* FunctionName();
3896 // Return the name of the given parameter.
3897 String* ParameterName(int var);
3899 // Return the name of the given local.
3900 String* LocalName(int var);
3902 // Return the name of the given stack local.
3903 String* StackLocalName(int var);
3905 // Return the name of the given stack local.
3906 int StackLocalIndex(int var);
3908 // Return the name of the given context local.
3909 String* ContextLocalName(int var);
3911 // Return the mode of the given context local.
3912 VariableMode ContextLocalMode(int var);
3914 // Return the initialization flag of the given context local.
3915 InitializationFlag ContextLocalInitFlag(int var);
3917 // Return the initialization flag of the given context local.
3918 MaybeAssignedFlag ContextLocalMaybeAssignedFlag(int var);
3920 // Return true if this local was introduced by the compiler, and should not be
3921 // exposed to the user in a debugger.
3922 bool LocalIsSynthetic(int var);
3924 String* StrongModeFreeVariableName(int var);
3925 int StrongModeFreeVariableStartPosition(int var);
3926 int StrongModeFreeVariableEndPosition(int var);
3928 // Lookup support for serialized scope info. Returns the
3929 // the stack slot index for a given slot name if the slot is
3930 // present; otherwise returns a value < 0. The name must be an internalized
3932 int StackSlotIndex(String* name);
3934 // Lookup support for serialized scope info. Returns the
3935 // context slot index for a given slot name if the slot is present; otherwise
3936 // returns a value < 0. The name must be an internalized string.
3937 // If the slot is present and mode != NULL, sets *mode to the corresponding
3938 // mode for that variable.
3939 static int ContextSlotIndex(Handle<ScopeInfo> scope_info, Handle<String> name,
3940 VariableMode* mode, VariableLocation* location,
3941 InitializationFlag* init_flag,
3942 MaybeAssignedFlag* maybe_assigned_flag);
3944 // Lookup the name of a certain context slot by its index.
3945 String* ContextSlotName(int slot_index);
3947 // Lookup support for serialized scope info. Returns the
3948 // parameter index for a given parameter name if the parameter is present;
3949 // otherwise returns a value < 0. The name must be an internalized string.
3950 int ParameterIndex(String* name);
3952 // Lookup support for serialized scope info. Returns the function context
3953 // slot index if the function name is present and context-allocated (named
3954 // function expressions, only), otherwise returns a value < 0. The name
3955 // must be an internalized string.
3956 int FunctionContextSlotIndex(String* name, VariableMode* mode);
3958 // Lookup support for serialized scope info. Returns the receiver context
3959 // slot index if scope has a "this" binding, and the binding is
3960 // context-allocated. Otherwise returns a value < 0.
3961 int ReceiverContextSlotIndex();
3963 FunctionKind function_kind();
3965 static Handle<ScopeInfo> Create(Isolate* isolate, Zone* zone, Scope* scope);
3966 static Handle<ScopeInfo> CreateGlobalThisBinding(Isolate* isolate);
3968 // Serializes empty scope info.
3969 static ScopeInfo* Empty(Isolate* isolate);
3975 // The layout of the static part of a ScopeInfo is as follows. Each entry is
3976 // numeric and occupies one array slot.
3977 // 1. A set of properties of the scope
3978 // 2. The number of parameters. This only applies to function scopes. For
3979 // non-function scopes this is 0.
3980 // 3. The number of non-parameter variables allocated on the stack.
3981 // 4. The number of non-parameter and parameter variables allocated in the
3983 #define FOR_EACH_NUMERIC_FIELD(V) \
3986 V(StackLocalCount) \
3987 V(ContextLocalCount) \
3988 V(ContextGlobalCount) \
3989 V(StrongModeFreeVariableCount)
3991 #define FIELD_ACCESSORS(name) \
3992 void Set##name(int value) { \
3993 set(k##name, Smi::FromInt(value)); \
3996 if (length() > 0) { \
3997 return Smi::cast(get(k##name))->value(); \
4002 FOR_EACH_NUMERIC_FIELD(FIELD_ACCESSORS)
4003 #undef FIELD_ACCESSORS
4007 #define DECL_INDEX(name) k##name,
4008 FOR_EACH_NUMERIC_FIELD(DECL_INDEX)
4010 #undef FOR_EACH_NUMERIC_FIELD
4014 // The layout of the variable part of a ScopeInfo is as follows:
4015 // 1. ParameterEntries:
4016 // This part stores the names of the parameters for function scopes. One
4017 // slot is used per parameter, so in total this part occupies
4018 // ParameterCount() slots in the array. For other scopes than function
4019 // scopes ParameterCount() is 0.
4020 // 2. StackLocalFirstSlot:
4021 // Index of a first stack slot for stack local. Stack locals belonging to
4022 // this scope are located on a stack at slots starting from this index.
4023 // 3. StackLocalEntries:
4024 // Contains the names of local variables that are allocated on the stack,
4025 // in increasing order of the stack slot index. First local variable has
4026 // a stack slot index defined in StackLocalFirstSlot (point 2 above).
4027 // One slot is used per stack local, so in total this part occupies
4028 // StackLocalCount() slots in the array.
4029 // 4. ContextLocalNameEntries:
4030 // Contains the names of local variables and parameters that are allocated
4031 // in the context. They are stored in increasing order of the context slot
4032 // index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
4033 // context local, so in total this part occupies ContextLocalCount() slots
4035 // 5. ContextLocalInfoEntries:
4036 // Contains the variable modes and initialization flags corresponding to
4037 // the context locals in ContextLocalNameEntries. One slot is used per
4038 // context local, so in total this part occupies ContextLocalCount()
4039 // slots in the array.
4040 // 6. StrongModeFreeVariableNameEntries:
4041 // Stores the names of strong mode free variables.
4042 // 7. StrongModeFreeVariablePositionEntries:
4043 // Stores the locations (start and end position) of strong mode free
4045 // 8. RecieverEntryIndex:
4046 // If the scope binds a "this" value, one slot is reserved to hold the
4047 // context or stack slot index for the variable.
4048 // 9. FunctionNameEntryIndex:
4049 // If the scope belongs to a named function expression this part contains
4050 // information about the function variable. It always occupies two array
4051 // slots: a. The name of the function variable.
4052 // b. The context or stack slot index for the variable.
4053 int ParameterEntriesIndex();
4054 int StackLocalFirstSlotIndex();
4055 int StackLocalEntriesIndex();
4056 int ContextLocalNameEntriesIndex();
4057 int ContextGlobalNameEntriesIndex();
4058 int ContextLocalInfoEntriesIndex();
4059 int ContextGlobalInfoEntriesIndex();
4060 int StrongModeFreeVariableNameEntriesIndex();
4061 int StrongModeFreeVariablePositionEntriesIndex();
4062 int ReceiverEntryIndex();
4063 int FunctionNameEntryIndex();
4065 int Lookup(Handle<String> name, int start, int end, VariableMode* mode,
4066 VariableLocation* location, InitializationFlag* init_flag,
4067 MaybeAssignedFlag* maybe_assigned_flag);
4069 // Used for the function name variable for named function expressions, and for
4071 enum VariableAllocationInfo { NONE, STACK, CONTEXT, UNUSED };
4073 // Properties of scopes.
4074 class ScopeTypeField : public BitField<ScopeType, 0, 4> {};
4075 class CallsEvalField : public BitField<bool, ScopeTypeField::kNext, 1> {};
4076 STATIC_ASSERT(LANGUAGE_END == 3);
4077 class LanguageModeField
4078 : public BitField<LanguageMode, CallsEvalField::kNext, 2> {};
4079 class ReceiverVariableField
4080 : public BitField<VariableAllocationInfo, LanguageModeField::kNext, 2> {};
4081 class FunctionVariableField
4082 : public BitField<VariableAllocationInfo, ReceiverVariableField::kNext,
4084 class FunctionVariableMode
4085 : public BitField<VariableMode, FunctionVariableField::kNext, 3> {};
4086 class AsmModuleField : public BitField<bool, FunctionVariableMode::kNext, 1> {
4088 class AsmFunctionField : public BitField<bool, AsmModuleField::kNext, 1> {};
4089 class HasSimpleParametersField
4090 : public BitField<bool, AsmFunctionField::kNext, 1> {};
4091 class FunctionKindField
4092 : public BitField<FunctionKind, HasSimpleParametersField::kNext, 8> {};
4094 // BitFields representing the encoded information for context locals in the
4095 // ContextLocalInfoEntries part.
4096 class ContextLocalMode: public BitField<VariableMode, 0, 3> {};
4097 class ContextLocalInitFlag: public BitField<InitializationFlag, 3, 1> {};
4098 class ContextLocalMaybeAssignedFlag
4099 : public BitField<MaybeAssignedFlag, 4, 1> {};
4101 friend class ScopeIterator;
4105 // The cache for maps used by normalized (dictionary mode) objects.
4106 // Such maps do not have property descriptors, so a typical program
4107 // needs very limited number of distinct normalized maps.
4108 class NormalizedMapCache: public FixedArray {
4110 static Handle<NormalizedMapCache> New(Isolate* isolate);
4112 MUST_USE_RESULT MaybeHandle<Map> Get(Handle<Map> fast_map,
4113 PropertyNormalizationMode mode);
4114 void Set(Handle<Map> fast_map, Handle<Map> normalized_map);
4118 DECLARE_CAST(NormalizedMapCache)
4120 static inline bool IsNormalizedMapCache(const Object* obj);
4122 DECLARE_VERIFIER(NormalizedMapCache)
4124 static const int kEntries = 64;
4126 static inline int GetIndex(Handle<Map> map);
4128 // The following declarations hide base class methods.
4129 Object* get(int index);
4130 void set(int index, Object* value);
4134 // ByteArray represents fixed sized byte arrays. Used for the relocation info
4135 // that is attached to code objects.
4136 class ByteArray: public FixedArrayBase {
4138 inline int Size() { return RoundUp(length() + kHeaderSize, kPointerSize); }
4140 // Setter and getter.
4141 inline byte get(int index);
4142 inline void set(int index, byte value);
4144 // Treat contents as an int array.
4145 inline int get_int(int index);
4147 static int SizeFor(int length) {
4148 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4150 // We use byte arrays for free blocks in the heap. Given a desired size in
4151 // bytes that is a multiple of the word size and big enough to hold a byte
4152 // array, this function returns the number of elements a byte array should
4154 static int LengthFor(int size_in_bytes) {
4155 DCHECK(IsAligned(size_in_bytes, kPointerSize));
4156 DCHECK(size_in_bytes >= kHeaderSize);
4157 return size_in_bytes - kHeaderSize;
4160 // Returns data start address.
4161 inline Address GetDataStartAddress();
4163 // Returns a pointer to the ByteArray object for a given data start address.
4164 static inline ByteArray* FromDataStartAddress(Address address);
4166 DECLARE_CAST(ByteArray)
4168 // Dispatched behavior.
4169 inline int ByteArraySize() {
4170 return SizeFor(this->length());
4172 DECLARE_PRINTER(ByteArray)
4173 DECLARE_VERIFIER(ByteArray)
4175 // Layout description.
4176 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4178 // Maximal memory consumption for a single ByteArray.
4179 static const int kMaxSize = 512 * MB;
4180 // Maximal length of a single ByteArray.
4181 static const int kMaxLength = kMaxSize - kHeaderSize;
4184 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4188 // BytecodeArray represents a sequence of interpreter bytecodes.
4189 class BytecodeArray : public FixedArrayBase {
4191 static int SizeFor(int length) {
4192 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4195 // Setter and getter
4196 inline byte get(int index);
4197 inline void set(int index, byte value);
4199 // Returns data start address.
4200 inline Address GetFirstBytecodeAddress();
4202 // Accessors for frame size and the number of locals
4203 inline int frame_size() const;
4204 inline void set_frame_size(int value);
4206 DECLARE_CAST(BytecodeArray)
4208 // Dispatched behavior.
4209 inline int BytecodeArraySize() { return SizeFor(this->length()); }
4211 DECLARE_PRINTER(BytecodeArray)
4212 DECLARE_VERIFIER(BytecodeArray)
4214 void Disassemble(std::ostream& os);
4216 // Layout description.
4217 static const int kFrameSizeOffset = FixedArrayBase::kHeaderSize;
4218 static const int kHeaderSize = kFrameSizeOffset + kIntSize;
4220 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4222 // Maximal memory consumption for a single BytecodeArray.
4223 static const int kMaxSize = 512 * MB;
4224 // Maximal length of a single BytecodeArray.
4225 static const int kMaxLength = kMaxSize - kHeaderSize;
4228 DISALLOW_IMPLICIT_CONSTRUCTORS(BytecodeArray);
4232 // FreeSpace are fixed-size free memory blocks used by the heap and GC.
4233 // They look like heap objects (are heap object tagged and have a map) so that
4234 // the heap remains iterable. They have a size and a next pointer.
4235 // The next pointer is the raw address of the next FreeSpace object (or NULL)
4236 // in the free list.
4237 class FreeSpace: public HeapObject {
4239 // [size]: size of the free space including the header.
4240 inline int size() const;
4241 inline void set_size(int value);
4243 inline int nobarrier_size() const;
4244 inline void nobarrier_set_size(int value);
4246 inline int Size() { return size(); }
4248 // Accessors for the next field.
4249 inline FreeSpace* next();
4250 inline FreeSpace** next_address();
4251 inline void set_next(FreeSpace* next);
4253 inline static FreeSpace* cast(HeapObject* obj);
4255 // Dispatched behavior.
4256 DECLARE_PRINTER(FreeSpace)
4257 DECLARE_VERIFIER(FreeSpace)
4259 // Layout description.
4260 // Size is smi tagged when it is stored.
4261 static const int kSizeOffset = HeapObject::kHeaderSize;
4262 static const int kNextOffset = POINTER_SIZE_ALIGN(kSizeOffset + kPointerSize);
4265 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
4269 // V has parameters (Type, type, TYPE, C type, element_size)
4270 #define TYPED_ARRAYS(V) \
4271 V(Uint8, uint8, UINT8, uint8_t, 1) \
4272 V(Int8, int8, INT8, int8_t, 1) \
4273 V(Uint16, uint16, UINT16, uint16_t, 2) \
4274 V(Int16, int16, INT16, int16_t, 2) \
4275 V(Uint32, uint32, UINT32, uint32_t, 4) \
4276 V(Int32, int32, INT32, int32_t, 4) \
4277 V(Float32, float32, FLOAT32, float, 4) \
4278 V(Float64, float64, FLOAT64, double, 8) \
4279 V(Uint8Clamped, uint8_clamped, UINT8_CLAMPED, uint8_t, 1)
4282 class FixedTypedArrayBase: public FixedArrayBase {
4284 // [base_pointer]: Either points to the FixedTypedArrayBase itself or nullptr.
4285 DECL_ACCESSORS(base_pointer, Object)
4287 // [external_pointer]: Contains the offset between base_pointer and the start
4288 // of the data. If the base_pointer is a nullptr, the external_pointer
4289 // therefore points to the actual backing store.
4290 DECL_ACCESSORS(external_pointer, void)
4292 // Dispatched behavior.
4293 inline void FixedTypedArrayBaseIterateBody(ObjectVisitor* v);
4295 template <typename StaticVisitor>
4296 inline void FixedTypedArrayBaseIterateBody();
4298 DECLARE_CAST(FixedTypedArrayBase)
4300 static const int kBasePointerOffset = FixedArrayBase::kHeaderSize;
4301 static const int kExternalPointerOffset = kBasePointerOffset + kPointerSize;
4302 static const int kHeaderSize =
4303 DOUBLE_POINTER_ALIGN(kExternalPointerOffset + kPointerSize);
4305 static const int kDataOffset = kHeaderSize;
4309 static inline int TypedArraySize(InstanceType type, int length);
4310 inline int TypedArraySize(InstanceType type);
4312 // Use with care: returns raw pointer into heap.
4313 inline void* DataPtr();
4315 inline int DataSize();
4318 static inline int ElementSize(InstanceType type);
4320 inline int DataSize(InstanceType type);
4322 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
4326 template <class Traits>
4327 class FixedTypedArray: public FixedTypedArrayBase {
4329 typedef typename Traits::ElementType ElementType;
4330 static const InstanceType kInstanceType = Traits::kInstanceType;
4332 DECLARE_CAST(FixedTypedArray<Traits>)
4334 inline ElementType get_scalar(int index);
4335 static inline Handle<Object> get(Handle<FixedTypedArray> array, int index);
4336 inline void set(int index, ElementType value);
4338 static inline ElementType from_int(int value);
4339 static inline ElementType from_double(double value);
4341 // This accessor applies the correct conversion from Smi, HeapNumber
4343 void SetValue(uint32_t index, Object* value);
4345 DECLARE_PRINTER(FixedTypedArray)
4346 DECLARE_VERIFIER(FixedTypedArray)
4349 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
4352 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size) \
4353 class Type##ArrayTraits { \
4354 public: /* NOLINT */ \
4355 typedef elementType ElementType; \
4356 static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE; \
4357 static const char* Designator() { return #type " array"; } \
4358 static inline Handle<Object> ToHandle(Isolate* isolate, \
4359 elementType scalar); \
4360 static inline elementType defaultValue(); \
4363 typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
4365 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
4367 #undef FIXED_TYPED_ARRAY_TRAITS
4370 // DeoptimizationInputData is a fixed array used to hold the deoptimization
4371 // data for code generated by the Hydrogen/Lithium compiler. It also
4372 // contains information about functions that were inlined. If N different
4373 // functions were inlined then first N elements of the literal array will
4374 // contain these functions.
4377 class DeoptimizationInputData: public FixedArray {
4379 // Layout description. Indices in the array.
4380 static const int kTranslationByteArrayIndex = 0;
4381 static const int kInlinedFunctionCountIndex = 1;
4382 static const int kLiteralArrayIndex = 2;
4383 static const int kOsrAstIdIndex = 3;
4384 static const int kOsrPcOffsetIndex = 4;
4385 static const int kOptimizationIdIndex = 5;
4386 static const int kSharedFunctionInfoIndex = 6;
4387 static const int kWeakCellCacheIndex = 7;
4388 static const int kFirstDeoptEntryIndex = 8;
4390 // Offsets of deopt entry elements relative to the start of the entry.
4391 static const int kAstIdRawOffset = 0;
4392 static const int kTranslationIndexOffset = 1;
4393 static const int kArgumentsStackHeightOffset = 2;
4394 static const int kPcOffset = 3;
4395 static const int kDeoptEntrySize = 4;
4397 // Simple element accessors.
4398 #define DEFINE_ELEMENT_ACCESSORS(name, type) \
4400 return type::cast(get(k##name##Index)); \
4402 void Set##name(type* value) { \
4403 set(k##name##Index, value); \
4406 DEFINE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
4407 DEFINE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
4408 DEFINE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
4409 DEFINE_ELEMENT_ACCESSORS(OsrAstId, Smi)
4410 DEFINE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
4411 DEFINE_ELEMENT_ACCESSORS(OptimizationId, Smi)
4412 DEFINE_ELEMENT_ACCESSORS(SharedFunctionInfo, Object)
4413 DEFINE_ELEMENT_ACCESSORS(WeakCellCache, Object)
4415 #undef DEFINE_ELEMENT_ACCESSORS
4417 // Accessors for elements of the ith deoptimization entry.
4418 #define DEFINE_ENTRY_ACCESSORS(name, type) \
4419 type* name(int i) { \
4420 return type::cast(get(IndexForEntry(i) + k##name##Offset)); \
4422 void Set##name(int i, type* value) { \
4423 set(IndexForEntry(i) + k##name##Offset, value); \
4426 DEFINE_ENTRY_ACCESSORS(AstIdRaw, Smi)
4427 DEFINE_ENTRY_ACCESSORS(TranslationIndex, Smi)
4428 DEFINE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
4429 DEFINE_ENTRY_ACCESSORS(Pc, Smi)
4431 #undef DEFINE_DEOPT_ENTRY_ACCESSORS
4433 BailoutId AstId(int i) {
4434 return BailoutId(AstIdRaw(i)->value());
4437 void SetAstId(int i, BailoutId value) {
4438 SetAstIdRaw(i, Smi::FromInt(value.ToInt()));
4442 return (length() - kFirstDeoptEntryIndex) / kDeoptEntrySize;
4445 // Allocates a DeoptimizationInputData.
4446 static Handle<DeoptimizationInputData> New(Isolate* isolate,
4447 int deopt_entry_count,
4448 PretenureFlag pretenure);
4450 DECLARE_CAST(DeoptimizationInputData)
4452 #ifdef ENABLE_DISASSEMBLER
4453 void DeoptimizationInputDataPrint(std::ostream& os); // NOLINT
4457 static int IndexForEntry(int i) {
4458 return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
4462 static int LengthFor(int entry_count) { return IndexForEntry(entry_count); }
4466 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
4467 // data for code generated by the full compiler.
4468 // The format of the these objects is
4469 // [i * 2]: Ast ID for ith deoptimization.
4470 // [i * 2 + 1]: PC and state of ith deoptimization
4471 class DeoptimizationOutputData: public FixedArray {
4473 int DeoptPoints() { return length() / 2; }
4475 BailoutId AstId(int index) {
4476 return BailoutId(Smi::cast(get(index * 2))->value());
4479 void SetAstId(int index, BailoutId id) {
4480 set(index * 2, Smi::FromInt(id.ToInt()));
4483 Smi* PcAndState(int index) { return Smi::cast(get(1 + index * 2)); }
4484 void SetPcAndState(int index, Smi* offset) { set(1 + index * 2, offset); }
4486 static int LengthOfFixedArray(int deopt_points) {
4487 return deopt_points * 2;
4490 // Allocates a DeoptimizationOutputData.
4491 static Handle<DeoptimizationOutputData> New(Isolate* isolate,
4492 int number_of_deopt_points,
4493 PretenureFlag pretenure);
4495 DECLARE_CAST(DeoptimizationOutputData)
4497 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4498 void DeoptimizationOutputDataPrint(std::ostream& os); // NOLINT
4503 // HandlerTable is a fixed array containing entries for exception handlers in
4504 // the code object it is associated with. The tables comes in two flavors:
4505 // 1) Based on ranges: Used for unoptimized code. Contains one entry per
4506 // exception handler and a range representing the try-block covered by that
4507 // handler. Layout looks as follows:
4508 // [ range-start , range-end , handler-offset , stack-depth ]
4509 // 2) Based on return addresses: Used for turbofanned code. Contains one entry
4510 // per call-site that could throw an exception. Layout looks as follows:
4511 // [ return-address-offset , handler-offset ]
4512 class HandlerTable : public FixedArray {
4514 // Conservative prediction whether a given handler will locally catch an
4515 // exception or cause a re-throw to outside the code boundary. Since this is
4516 // undecidable it is merely an approximation (e.g. useful for debugger).
4517 enum CatchPrediction { UNCAUGHT, CAUGHT };
4519 // Accessors for handler table based on ranges.
4520 void SetRangeStart(int index, int value) {
4521 set(index * kRangeEntrySize + kRangeStartIndex, Smi::FromInt(value));
4523 void SetRangeEnd(int index, int value) {
4524 set(index * kRangeEntrySize + kRangeEndIndex, Smi::FromInt(value));
4526 void SetRangeHandler(int index, int offset, CatchPrediction prediction) {
4527 int value = HandlerOffsetField::encode(offset) |
4528 HandlerPredictionField::encode(prediction);
4529 set(index * kRangeEntrySize + kRangeHandlerIndex, Smi::FromInt(value));
4531 void SetRangeDepth(int index, int value) {
4532 set(index * kRangeEntrySize + kRangeDepthIndex, Smi::FromInt(value));
4535 // Accessors for handler table based on return addresses.
4536 void SetReturnOffset(int index, int value) {
4537 set(index * kReturnEntrySize + kReturnOffsetIndex, Smi::FromInt(value));
4539 void SetReturnHandler(int index, int offset, CatchPrediction prediction) {
4540 int value = HandlerOffsetField::encode(offset) |
4541 HandlerPredictionField::encode(prediction);
4542 set(index * kReturnEntrySize + kReturnHandlerIndex, Smi::FromInt(value));
4545 // Lookup handler in a table based on ranges.
4546 int LookupRange(int pc_offset, int* stack_depth, CatchPrediction* prediction);
4548 // Lookup handler in a table based on return addresses.
4549 int LookupReturn(int pc_offset, CatchPrediction* prediction);
4551 // Returns the required length of the underlying fixed array.
4552 static int LengthForRange(int entries) { return entries * kRangeEntrySize; }
4553 static int LengthForReturn(int entries) { return entries * kReturnEntrySize; }
4555 DECLARE_CAST(HandlerTable)
4557 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4558 void HandlerTableRangePrint(std::ostream& os); // NOLINT
4559 void HandlerTableReturnPrint(std::ostream& os); // NOLINT
4563 // Layout description for handler table based on ranges.
4564 static const int kRangeStartIndex = 0;
4565 static const int kRangeEndIndex = 1;
4566 static const int kRangeHandlerIndex = 2;
4567 static const int kRangeDepthIndex = 3;
4568 static const int kRangeEntrySize = 4;
4570 // Layout description for handler table based on return addresses.
4571 static const int kReturnOffsetIndex = 0;
4572 static const int kReturnHandlerIndex = 1;
4573 static const int kReturnEntrySize = 2;
4575 // Encoding of the {handler} field.
4576 class HandlerPredictionField : public BitField<CatchPrediction, 0, 1> {};
4577 class HandlerOffsetField : public BitField<int, 1, 30> {};
4581 // Code describes objects with on-the-fly generated machine code.
4582 class Code: public HeapObject {
4584 // Opaque data type for encapsulating code flags like kind, inline
4585 // cache state, and arguments count.
4586 typedef uint32_t Flags;
4588 #define NON_IC_KIND_LIST(V) \
4590 V(OPTIMIZED_FUNCTION) \
4596 #define IC_KIND_LIST(V) \
4607 #define CODE_KIND_LIST(V) \
4608 NON_IC_KIND_LIST(V) \
4612 #define DEFINE_CODE_KIND_ENUM(name) name,
4613 CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
4614 #undef DEFINE_CODE_KIND_ENUM
4618 // No more than 16 kinds. The value is currently encoded in four bits in
4620 STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
4622 static const char* Kind2String(Kind kind);
4630 static const int kPrologueOffsetNotSet = -1;
4632 #ifdef ENABLE_DISASSEMBLER
4634 static const char* ICState2String(InlineCacheState state);
4635 static const char* StubType2String(StubType type);
4636 static void PrintExtraICState(std::ostream& os, // NOLINT
4637 Kind kind, ExtraICState extra);
4638 void Disassemble(const char* name, std::ostream& os); // NOLINT
4639 #endif // ENABLE_DISASSEMBLER
4641 // [instruction_size]: Size of the native instructions
4642 inline int instruction_size() const;
4643 inline void set_instruction_size(int value);
4645 // [relocation_info]: Code relocation information
4646 DECL_ACCESSORS(relocation_info, ByteArray)
4647 void InvalidateRelocation();
4648 void InvalidateEmbeddedObjects();
4650 // [handler_table]: Fixed array containing offsets of exception handlers.
4651 DECL_ACCESSORS(handler_table, FixedArray)
4653 // [deoptimization_data]: Array containing data for deopt.
4654 DECL_ACCESSORS(deoptimization_data, FixedArray)
4656 // [raw_type_feedback_info]: This field stores various things, depending on
4657 // the kind of the code object.
4658 // FUNCTION => type feedback information.
4659 // STUB and ICs => major/minor key as Smi.
4660 DECL_ACCESSORS(raw_type_feedback_info, Object)
4661 inline Object* type_feedback_info();
4662 inline void set_type_feedback_info(
4663 Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
4664 inline uint32_t stub_key();
4665 inline void set_stub_key(uint32_t key);
4667 // [next_code_link]: Link for lists of optimized or deoptimized code.
4668 // Note that storage for this field is overlapped with typefeedback_info.
4669 DECL_ACCESSORS(next_code_link, Object)
4671 // [gc_metadata]: Field used to hold GC related metadata. The contents of this
4672 // field does not have to be traced during garbage collection since
4673 // it is only used by the garbage collector itself.
4674 DECL_ACCESSORS(gc_metadata, Object)
4676 // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
4677 // at the moment when this object was created.
4678 inline void set_ic_age(int count);
4679 inline int ic_age() const;
4681 // [prologue_offset]: Offset of the function prologue, used for aging
4682 // FUNCTIONs and OPTIMIZED_FUNCTIONs.
4683 inline int prologue_offset() const;
4684 inline void set_prologue_offset(int offset);
4686 // [constant_pool offset]: Offset of the constant pool.
4687 // Valid for FLAG_enable_embedded_constant_pool only
4688 inline int constant_pool_offset() const;
4689 inline void set_constant_pool_offset(int offset);
4691 // Unchecked accessors to be used during GC.
4692 inline ByteArray* unchecked_relocation_info();
4694 inline int relocation_size();
4696 // [flags]: Various code flags.
4697 inline Flags flags();
4698 inline void set_flags(Flags flags);
4700 // [flags]: Access to specific code flags.
4702 inline InlineCacheState ic_state(); // Only valid for IC stubs.
4703 inline ExtraICState extra_ic_state(); // Only valid for IC stubs.
4705 inline StubType type(); // Only valid for monomorphic IC stubs.
4707 // Testers for IC stub kinds.
4708 inline bool is_inline_cache_stub();
4709 inline bool is_debug_stub();
4710 inline bool is_handler() { return kind() == HANDLER; }
4711 inline bool is_load_stub() { return kind() == LOAD_IC; }
4712 inline bool is_keyed_load_stub() { return kind() == KEYED_LOAD_IC; }
4713 inline bool is_store_stub() { return kind() == STORE_IC; }
4714 inline bool is_keyed_store_stub() { return kind() == KEYED_STORE_IC; }
4715 inline bool is_call_stub() { return kind() == CALL_IC; }
4716 inline bool is_binary_op_stub() { return kind() == BINARY_OP_IC; }
4717 inline bool is_compare_ic_stub() { return kind() == COMPARE_IC; }
4718 inline bool is_compare_nil_ic_stub() { return kind() == COMPARE_NIL_IC; }
4719 inline bool is_to_boolean_ic_stub() { return kind() == TO_BOOLEAN_IC; }
4720 inline bool is_keyed_stub();
4721 inline bool is_optimized_code() { return kind() == OPTIMIZED_FUNCTION; }
4722 inline bool embeds_maps_weakly() {
4724 return (k == LOAD_IC || k == STORE_IC || k == KEYED_LOAD_IC ||
4725 k == KEYED_STORE_IC || k == COMPARE_NIL_IC) &&
4726 ic_state() == MONOMORPHIC;
4729 inline bool IsCodeStubOrIC();
4731 inline void set_raw_kind_specific_flags1(int value);
4732 inline void set_raw_kind_specific_flags2(int value);
4734 // [is_crankshafted]: For kind STUB or ICs, tells whether or not a code
4735 // object was generated by either the hydrogen or the TurboFan optimizing
4736 // compiler (but it may not be an optimized function).
4737 inline bool is_crankshafted();
4738 inline bool is_hydrogen_stub(); // Crankshafted, but not a function.
4739 inline void set_is_crankshafted(bool value);
4741 // [is_turbofanned]: For kind STUB or OPTIMIZED_FUNCTION, tells whether the
4742 // code object was generated by the TurboFan optimizing compiler.
4743 inline bool is_turbofanned();
4744 inline void set_is_turbofanned(bool value);
4746 // [can_have_weak_objects]: For kind OPTIMIZED_FUNCTION, tells whether the
4747 // embedded objects in code should be treated weakly.
4748 inline bool can_have_weak_objects();
4749 inline void set_can_have_weak_objects(bool value);
4751 // [has_deoptimization_support]: For FUNCTION kind, tells if it has
4752 // deoptimization support.
4753 inline bool has_deoptimization_support();
4754 inline void set_has_deoptimization_support(bool value);
4756 // [has_debug_break_slots]: For FUNCTION kind, tells if it has
4757 // been compiled with debug break slots.
4758 inline bool has_debug_break_slots();
4759 inline void set_has_debug_break_slots(bool value);
4761 // [has_reloc_info_for_serialization]: For FUNCTION kind, tells if its
4762 // reloc info includes runtime and external references to support
4763 // serialization/deserialization.
4764 inline bool has_reloc_info_for_serialization();
4765 inline void set_has_reloc_info_for_serialization(bool value);
4767 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
4768 // how long the function has been marked for OSR and therefore which
4769 // level of loop nesting we are willing to do on-stack replacement
4771 inline void set_allow_osr_at_loop_nesting_level(int level);
4772 inline int allow_osr_at_loop_nesting_level();
4774 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
4775 // the code object was seen on the stack with no IC patching going on.
4776 inline int profiler_ticks();
4777 inline void set_profiler_ticks(int ticks);
4779 // [builtin_index]: For BUILTIN kind, tells which builtin index it has.
4780 // For builtins, tells which builtin index it has.
4781 // Note that builtins can have a code kind other than BUILTIN, which means
4782 // that for arbitrary code objects, this index value may be random garbage.
4783 // To verify in that case, compare the code object to the indexed builtin.
4784 inline int builtin_index();
4785 inline void set_builtin_index(int id);
4787 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
4788 // reserved in the code prologue.
4789 inline unsigned stack_slots();
4790 inline void set_stack_slots(unsigned slots);
4792 // [safepoint_table_start]: For kind OPTIMIZED_FUNCTION, the offset in
4793 // the instruction stream where the safepoint table starts.
4794 inline unsigned safepoint_table_offset();
4795 inline void set_safepoint_table_offset(unsigned offset);
4797 // [back_edge_table_start]: For kind FUNCTION, the offset in the
4798 // instruction stream where the back edge table starts.
4799 inline unsigned back_edge_table_offset();
4800 inline void set_back_edge_table_offset(unsigned offset);
4802 inline bool back_edges_patched_for_osr();
4804 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
4805 inline uint16_t to_boolean_state();
4807 // [has_function_cache]: For kind STUB tells whether there is a function
4808 // cache is passed to the stub.
4809 inline bool has_function_cache();
4810 inline void set_has_function_cache(bool flag);
4813 // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
4814 // the code is going to be deoptimized because of dead embedded maps.
4815 inline bool marked_for_deoptimization();
4816 inline void set_marked_for_deoptimization(bool flag);
4818 // [constant_pool]: The constant pool for this function.
4819 inline Address constant_pool();
4821 // Get the safepoint entry for the given pc.
4822 SafepointEntry GetSafepointEntry(Address pc);
4824 // Find an object in a stub with a specified map
4825 Object* FindNthObject(int n, Map* match_map);
4827 // Find the first allocation site in an IC stub.
4828 AllocationSite* FindFirstAllocationSite();
4830 // Find the first map in an IC stub.
4831 Map* FindFirstMap();
4832 void FindAllMaps(MapHandleList* maps);
4834 // Find the first handler in an IC stub.
4835 Code* FindFirstHandler();
4837 // Find |length| handlers and put them into |code_list|. Returns false if not
4838 // enough handlers can be found.
4839 bool FindHandlers(CodeHandleList* code_list, int length = -1);
4841 // Find the handler for |map|.
4842 MaybeHandle<Code> FindHandlerForMap(Map* map);
4844 // Find the first name in an IC stub.
4845 Name* FindFirstName();
4847 class FindAndReplacePattern;
4848 // For each (map-to-find, object-to-replace) pair in the pattern, this
4849 // function replaces the corresponding placeholder in the code with the
4850 // object-to-replace. The function assumes that pairs in the pattern come in
4851 // the same order as the placeholders in the code.
4852 // If the placeholder is a weak cell, then the value of weak cell is matched
4853 // against the map-to-find.
4854 void FindAndReplace(const FindAndReplacePattern& pattern);
4856 // The entire code object including its header is copied verbatim to the
4857 // snapshot so that it can be written in one, fast, memcpy during
4858 // deserialization. The deserializer will overwrite some pointers, rather
4859 // like a runtime linker, but the random allocation addresses used in the
4860 // mksnapshot process would still be present in the unlinked snapshot data,
4861 // which would make snapshot production non-reproducible. This method wipes
4862 // out the to-be-overwritten header data for reproducible snapshots.
4863 inline void WipeOutHeader();
4865 // Flags operations.
4866 static inline Flags ComputeFlags(
4867 Kind kind, InlineCacheState ic_state = UNINITIALIZED,
4868 ExtraICState extra_ic_state = kNoExtraICState, StubType type = NORMAL,
4869 CacheHolderFlag holder = kCacheOnReceiver);
4871 static inline Flags ComputeMonomorphicFlags(
4872 Kind kind, ExtraICState extra_ic_state = kNoExtraICState,
4873 CacheHolderFlag holder = kCacheOnReceiver, StubType type = NORMAL);
4875 static inline Flags ComputeHandlerFlags(
4876 Kind handler_kind, StubType type = NORMAL,
4877 CacheHolderFlag holder = kCacheOnReceiver);
4879 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
4880 static inline StubType ExtractTypeFromFlags(Flags flags);
4881 static inline CacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
4882 static inline Kind ExtractKindFromFlags(Flags flags);
4883 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
4885 static inline Flags RemoveTypeFromFlags(Flags flags);
4886 static inline Flags RemoveTypeAndHolderFromFlags(Flags flags);
4888 // Convert a target address into a code object.
4889 static inline Code* GetCodeFromTargetAddress(Address address);
4891 // Convert an entry address into an object.
4892 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
4894 // Returns the address of the first instruction.
4895 inline byte* instruction_start();
4897 // Returns the address right after the last instruction.
4898 inline byte* instruction_end();
4900 // Returns the size of the instructions, padding, and relocation information.
4901 inline int body_size();
4903 // Returns the address of the first relocation info (read backwards!).
4904 inline byte* relocation_start();
4906 // Code entry point.
4907 inline byte* entry();
4909 // Returns true if pc is inside this object's instructions.
4910 inline bool contains(byte* pc);
4912 // Relocate the code by delta bytes. Called to signal that this code
4913 // object has been moved by delta bytes.
4914 void Relocate(intptr_t delta);
4916 // Migrate code described by desc.
4917 void CopyFrom(const CodeDesc& desc);
4919 // Returns the object size for a given body (used for allocation).
4920 static int SizeFor(int body_size) {
4921 DCHECK_SIZE_TAG_ALIGNED(body_size);
4922 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
4925 // Calculate the size of the code object to report for log events. This takes
4926 // the layout of the code object into account.
4927 int ExecutableSize() {
4928 // Check that the assumptions about the layout of the code object holds.
4929 DCHECK_EQ(static_cast<int>(instruction_start() - address()),
4931 return instruction_size() + Code::kHeaderSize;
4934 // Locating source position.
4935 int SourcePosition(Address pc);
4936 int SourceStatementPosition(Address pc);
4940 // Dispatched behavior.
4941 int CodeSize() { return SizeFor(body_size()); }
4942 inline void CodeIterateBody(ObjectVisitor* v);
4944 template<typename StaticVisitor>
4945 inline void CodeIterateBody(Heap* heap);
4947 DECLARE_PRINTER(Code)
4948 DECLARE_VERIFIER(Code)
4950 void ClearInlineCaches();
4951 void ClearInlineCaches(Kind kind);
4953 BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
4954 uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
4956 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
4958 kToBeExecutedOnceCodeAge = -3,
4959 kNotExecutedCodeAge = -2,
4960 kExecutedOnceCodeAge = -1,
4962 CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
4964 kFirstCodeAge = kToBeExecutedOnceCodeAge,
4965 kLastCodeAge = kAfterLastCodeAge - 1,
4966 kCodeAgeCount = kAfterLastCodeAge - kFirstCodeAge - 1,
4967 kIsOldCodeAge = kSexagenarianCodeAge,
4968 kPreAgedCodeAge = kIsOldCodeAge - 1
4970 #undef DECLARE_CODE_AGE_ENUM
4972 // Code aging. Indicates how many full GCs this code has survived without
4973 // being entered through the prologue. Used to determine when it is
4974 // relatively safe to flush this code object and replace it with the lazy
4975 // compilation stub.
4976 static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
4977 static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
4978 void MakeYoung(Isolate* isolate);
4979 void MarkToBeExecutedOnce(Isolate* isolate);
4980 void MakeOlder(MarkingParity);
4981 static bool IsYoungSequence(Isolate* isolate, byte* sequence);
4984 static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
4985 return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
4988 void PrintDeoptLocation(FILE* out, Address pc);
4989 bool CanDeoptAt(Address pc);
4992 void VerifyEmbeddedObjectsDependency();
4996 enum VerifyMode { kNoContextSpecificPointers, kNoContextRetainingPointers };
4997 void VerifyEmbeddedObjects(VerifyMode mode = kNoContextRetainingPointers);
4998 static void VerifyRecompiledCode(Code* old_code, Code* new_code);
5001 inline bool CanContainWeakObjects() {
5002 // is_turbofanned() implies !can_have_weak_objects().
5003 DCHECK(!is_optimized_code() || !is_turbofanned() ||
5004 !can_have_weak_objects());
5005 return is_optimized_code() && can_have_weak_objects();
5008 inline bool IsWeakObject(Object* object) {
5009 return (CanContainWeakObjects() && IsWeakObjectInOptimizedCode(object));
5012 static inline bool IsWeakObjectInOptimizedCode(Object* object);
5014 static Handle<WeakCell> WeakCellFor(Handle<Code> code);
5015 WeakCell* CachedWeakCell();
5017 // Max loop nesting marker used to postpose OSR. We don't take loop
5018 // nesting that is deeper than 5 levels into account.
5019 static const int kMaxLoopNestingMarker = 6;
5021 static const int kConstantPoolSize =
5022 FLAG_enable_embedded_constant_pool ? kIntSize : 0;
5024 // Layout description.
5025 static const int kRelocationInfoOffset = HeapObject::kHeaderSize;
5026 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
5027 static const int kDeoptimizationDataOffset =
5028 kHandlerTableOffset + kPointerSize;
5029 // For FUNCTION kind, we store the type feedback info here.
5030 static const int kTypeFeedbackInfoOffset =
5031 kDeoptimizationDataOffset + kPointerSize;
5032 static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
5033 static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
5034 static const int kInstructionSizeOffset = kGCMetadataOffset + kPointerSize;
5035 static const int kICAgeOffset = kInstructionSizeOffset + kIntSize;
5036 static const int kFlagsOffset = kICAgeOffset + kIntSize;
5037 static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
5038 static const int kKindSpecificFlags2Offset =
5039 kKindSpecificFlags1Offset + kIntSize;
5040 // Note: We might be able to squeeze this into the flags above.
5041 static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
5042 static const int kConstantPoolOffset = kPrologueOffset + kIntSize;
5043 static const int kHeaderPaddingStart =
5044 kConstantPoolOffset + kConstantPoolSize;
5046 // Add padding to align the instruction start following right after
5047 // the Code object header.
5048 static const int kHeaderSize =
5049 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
5051 // Byte offsets within kKindSpecificFlags1Offset.
5052 static const int kFullCodeFlags = kKindSpecificFlags1Offset;
5053 class FullCodeFlagsHasDeoptimizationSupportField:
5054 public BitField<bool, 0, 1> {}; // NOLINT
5055 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
5056 class FullCodeFlagsHasRelocInfoForSerialization
5057 : public BitField<bool, 2, 1> {};
5058 // Bit 3 in this bitfield is unused.
5059 class ProfilerTicksField : public BitField<int, 4, 28> {};
5061 // Flags layout. BitField<type, shift, size>.
5062 class ICStateField : public BitField<InlineCacheState, 0, 4> {};
5063 class TypeField : public BitField<StubType, 4, 1> {};
5064 class CacheHolderField : public BitField<CacheHolderFlag, 5, 2> {};
5065 class KindField : public BitField<Kind, 7, 4> {};
5066 class ExtraICStateField: public BitField<ExtraICState, 11,
5067 PlatformSmiTagging::kSmiValueSize - 11 + 1> {}; // NOLINT
5069 // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
5070 static const int kStackSlotsFirstBit = 0;
5071 static const int kStackSlotsBitCount = 24;
5072 static const int kHasFunctionCacheBit =
5073 kStackSlotsFirstBit + kStackSlotsBitCount;
5074 static const int kMarkedForDeoptimizationBit = kHasFunctionCacheBit + 1;
5075 static const int kIsTurbofannedBit = kMarkedForDeoptimizationBit + 1;
5076 static const int kCanHaveWeakObjects = kIsTurbofannedBit + 1;
5078 STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
5079 STATIC_ASSERT(kCanHaveWeakObjects + 1 <= 32);
5081 class StackSlotsField: public BitField<int,
5082 kStackSlotsFirstBit, kStackSlotsBitCount> {}; // NOLINT
5083 class HasFunctionCacheField : public BitField<bool, kHasFunctionCacheBit, 1> {
5085 class MarkedForDeoptimizationField
5086 : public BitField<bool, kMarkedForDeoptimizationBit, 1> {}; // NOLINT
5087 class IsTurbofannedField : public BitField<bool, kIsTurbofannedBit, 1> {
5089 class CanHaveWeakObjectsField
5090 : public BitField<bool, kCanHaveWeakObjects, 1> {}; // NOLINT
5092 // KindSpecificFlags2 layout (ALL)
5093 static const int kIsCrankshaftedBit = 0;
5094 class IsCrankshaftedField: public BitField<bool,
5095 kIsCrankshaftedBit, 1> {}; // NOLINT
5097 // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
5098 static const int kSafepointTableOffsetFirstBit = kIsCrankshaftedBit + 1;
5099 static const int kSafepointTableOffsetBitCount = 30;
5101 STATIC_ASSERT(kSafepointTableOffsetFirstBit +
5102 kSafepointTableOffsetBitCount <= 32);
5103 STATIC_ASSERT(1 + kSafepointTableOffsetBitCount <= 32);
5105 class SafepointTableOffsetField: public BitField<int,
5106 kSafepointTableOffsetFirstBit,
5107 kSafepointTableOffsetBitCount> {}; // NOLINT
5109 // KindSpecificFlags2 layout (FUNCTION)
5110 class BackEdgeTableOffsetField: public BitField<int,
5111 kIsCrankshaftedBit + 1, 27> {}; // NOLINT
5112 class AllowOSRAtLoopNestingLevelField: public BitField<int,
5113 kIsCrankshaftedBit + 1 + 27, 4> {}; // NOLINT
5114 STATIC_ASSERT(AllowOSRAtLoopNestingLevelField::kMax >= kMaxLoopNestingMarker);
5116 static const int kArgumentsBits = 16;
5117 static const int kMaxArguments = (1 << kArgumentsBits) - 1;
5119 // This constant should be encodable in an ARM instruction.
5120 static const int kFlagsNotUsedInLookup =
5121 TypeField::kMask | CacheHolderField::kMask;
5124 friend class RelocIterator;
5125 friend class Deoptimizer; // For FindCodeAgeSequence.
5127 void ClearInlineCaches(Kind* kind);
5130 byte* FindCodeAgeSequence();
5131 static void GetCodeAgeAndParity(Code* code, Age* age,
5132 MarkingParity* parity);
5133 static void GetCodeAgeAndParity(Isolate* isolate, byte* sequence, Age* age,
5134 MarkingParity* parity);
5135 static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
5137 // Code aging -- platform-specific
5138 static void PatchPlatformCodeAge(Isolate* isolate,
5139 byte* sequence, Age age,
5140 MarkingParity parity);
5142 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5146 // This class describes the layout of dependent codes array of a map. The
5147 // array is partitioned into several groups of dependent codes. Each group
5148 // contains codes with the same dependency on the map. The array has the
5149 // following layout for n dependency groups:
5151 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5152 // | C1 | C2 | ... | Cn | group 1 | group 2 | ... | group n | undefined |
5153 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5155 // The first n elements are Smis, each of them specifies the number of codes
5156 // in the corresponding group. The subsequent elements contain grouped code
5157 // objects in weak cells. The suffix of the array can be filled with the
5158 // undefined value if the number of codes is less than the length of the
5159 // array. The order of the code objects within a group is not preserved.
5161 // All code indexes used in the class are counted starting from the first
5162 // code object of the first group. In other words, code index 0 corresponds
5163 // to array index n = kCodesStartIndex.
5165 class DependentCode: public FixedArray {
5167 enum DependencyGroup {
5168 // Group of code that weakly embed this map and depend on being
5169 // deoptimized when the map is garbage collected.
5171 // Group of code that embed a transition to this map, and depend on being
5172 // deoptimized when the transition is replaced by a new version.
5174 // Group of code that omit run-time prototype checks for prototypes
5175 // described by this map. The group is deoptimized whenever an object
5176 // described by this map changes shape (and transitions to a new map),
5177 // possibly invalidating the assumptions embedded in the code.
5178 kPrototypeCheckGroup,
5179 // Group of code that depends on global property values in property cells
5180 // not being changed.
5181 kPropertyCellChangedGroup,
5182 // Group of code that omit run-time type checks for the field(s) introduced
5185 // Group of code that omit run-time type checks for initial maps of
5187 kInitialMapChangedGroup,
5188 // Group of code that depends on tenuring information in AllocationSites
5189 // not being changed.
5190 kAllocationSiteTenuringChangedGroup,
5191 // Group of code that depends on element transition information in
5192 // AllocationSites not being changed.
5193 kAllocationSiteTransitionChangedGroup
5196 static const int kGroupCount = kAllocationSiteTransitionChangedGroup + 1;
5198 // Array for holding the index of the first code object of each group.
5199 // The last element stores the total number of code objects.
5200 class GroupStartIndexes {
5202 explicit GroupStartIndexes(DependentCode* entries);
5203 void Recompute(DependentCode* entries);
5204 int at(int i) { return start_indexes_[i]; }
5205 int number_of_entries() { return start_indexes_[kGroupCount]; }
5207 int start_indexes_[kGroupCount + 1];
5210 bool Contains(DependencyGroup group, WeakCell* code_cell);
5212 static Handle<DependentCode> InsertCompilationDependencies(
5213 Handle<DependentCode> entries, DependencyGroup group,
5214 Handle<Foreign> info);
5216 static Handle<DependentCode> InsertWeakCode(Handle<DependentCode> entries,
5217 DependencyGroup group,
5218 Handle<WeakCell> code_cell);
5220 void UpdateToFinishedCode(DependencyGroup group, Foreign* info,
5221 WeakCell* code_cell);
5223 void RemoveCompilationDependencies(DependentCode::DependencyGroup group,
5226 void DeoptimizeDependentCodeGroup(Isolate* isolate,
5227 DependentCode::DependencyGroup group);
5229 bool MarkCodeForDeoptimization(Isolate* isolate,
5230 DependentCode::DependencyGroup group);
5232 // The following low-level accessors should only be used by this class
5233 // and the mark compact collector.
5234 inline int number_of_entries(DependencyGroup group);
5235 inline void set_number_of_entries(DependencyGroup group, int value);
5236 inline Object* object_at(int i);
5237 inline void set_object_at(int i, Object* object);
5238 inline void clear_at(int i);
5239 inline void copy(int from, int to);
5240 DECLARE_CAST(DependentCode)
5242 static const char* DependencyGroupName(DependencyGroup group);
5243 static void SetMarkedForDeoptimization(Code* code, DependencyGroup group);
5246 static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5247 DependencyGroup group,
5248 Handle<Object> object);
5249 static Handle<DependentCode> EnsureSpace(Handle<DependentCode> entries);
5250 // Make a room at the end of the given group by moving out the first
5251 // code objects of the subsequent groups.
5252 inline void ExtendGroup(DependencyGroup group);
5253 // Compact by removing cleared weak cells and return true if there was
5254 // any cleared weak cell.
5256 static int Grow(int number_of_entries) {
5257 if (number_of_entries < 5) return number_of_entries + 1;
5258 return number_of_entries * 5 / 4;
5260 static const int kCodesStartIndex = kGroupCount;
5264 class PrototypeInfo;
5267 // All heap objects have a Map that describes their structure.
5268 // A Map contains information about:
5269 // - Size information about the object
5270 // - How to iterate over an object (for garbage collection)
5271 class Map: public HeapObject {
5274 // Size in bytes or kVariableSizeSentinel if instances do not have
5276 inline int instance_size();
5277 inline void set_instance_size(int value);
5279 // Only to clear an unused byte, remove once byte is used.
5280 inline void clear_unused();
5282 // Count of properties allocated in the object.
5283 inline int inobject_properties();
5284 inline void set_inobject_properties(int value);
5287 inline InstanceType instance_type();
5288 inline void set_instance_type(InstanceType value);
5290 // Tells how many unused property fields are available in the
5291 // instance (only used for JSObject in fast mode).
5292 inline int unused_property_fields();
5293 inline void set_unused_property_fields(int value);
5296 inline byte bit_field() const;
5297 inline void set_bit_field(byte value);
5300 inline byte bit_field2() const;
5301 inline void set_bit_field2(byte value);
5304 inline uint32_t bit_field3() const;
5305 inline void set_bit_field3(uint32_t bits);
5307 class EnumLengthBits: public BitField<int,
5308 0, kDescriptorIndexBitCount> {}; // NOLINT
5309 class NumberOfOwnDescriptorsBits: public BitField<int,
5310 kDescriptorIndexBitCount, kDescriptorIndexBitCount> {}; // NOLINT
5311 STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
5312 class DictionaryMap : public BitField<bool, 20, 1> {};
5313 class OwnsDescriptors : public BitField<bool, 21, 1> {};
5314 class HasInstanceCallHandler : public BitField<bool, 22, 1> {};
5315 class Deprecated : public BitField<bool, 23, 1> {};
5316 class IsUnstable : public BitField<bool, 24, 1> {};
5317 class IsMigrationTarget : public BitField<bool, 25, 1> {};
5318 class IsStrong : public BitField<bool, 26, 1> {};
5321 // Keep this bit field at the very end for better code in
5322 // Builtins::kJSConstructStubGeneric stub.
5323 // This counter is used for in-object slack tracking and for map aging.
5324 // The in-object slack tracking is considered enabled when the counter is
5325 // in the range [kSlackTrackingCounterStart, kSlackTrackingCounterEnd].
5326 class Counter : public BitField<int, 28, 4> {};
5327 static const int kSlackTrackingCounterStart = 14;
5328 static const int kSlackTrackingCounterEnd = 8;
5329 static const int kRetainingCounterStart = kSlackTrackingCounterEnd - 1;
5330 static const int kRetainingCounterEnd = 0;
5332 // Tells whether the object in the prototype property will be used
5333 // for instances created from this function. If the prototype
5334 // property is set to a value that is not a JSObject, the prototype
5335 // property will not be used to create instances of the function.
5336 // See ECMA-262, 13.2.2.
5337 inline void set_non_instance_prototype(bool value);
5338 inline bool has_non_instance_prototype();
5340 // Tells whether function has special prototype property. If not, prototype
5341 // property will not be created when accessed (will return undefined),
5342 // and construction from this function will not be allowed.
5343 inline void set_function_with_prototype(bool value);
5344 inline bool function_with_prototype();
5346 // Tells whether the instance with this map should be ignored by the
5347 // Object.getPrototypeOf() function and the __proto__ accessor.
5348 inline void set_is_hidden_prototype() {
5349 set_bit_field(bit_field() | (1 << kIsHiddenPrototype));
5352 inline bool is_hidden_prototype() {
5353 return ((1 << kIsHiddenPrototype) & bit_field()) != 0;
5356 // Records and queries whether the instance has a named interceptor.
5357 inline void set_has_named_interceptor() {
5358 set_bit_field(bit_field() | (1 << kHasNamedInterceptor));
5361 inline bool has_named_interceptor() {
5362 return ((1 << kHasNamedInterceptor) & bit_field()) != 0;
5365 // Records and queries whether the instance has an indexed interceptor.
5366 inline void set_has_indexed_interceptor() {
5367 set_bit_field(bit_field() | (1 << kHasIndexedInterceptor));
5370 inline bool has_indexed_interceptor() {
5371 return ((1 << kHasIndexedInterceptor) & bit_field()) != 0;
5374 // Tells whether the instance is undetectable.
5375 // An undetectable object is a special class of JSObject: 'typeof' operator
5376 // returns undefined, ToBoolean returns false. Otherwise it behaves like
5377 // a normal JS object. It is useful for implementing undetectable
5378 // document.all in Firefox & Safari.
5379 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
5380 inline void set_is_undetectable() {
5381 set_bit_field(bit_field() | (1 << kIsUndetectable));
5384 inline bool is_undetectable() {
5385 return ((1 << kIsUndetectable) & bit_field()) != 0;
5388 // Tells whether the instance has a call-as-function handler.
5389 inline void set_is_observed() {
5390 set_bit_field(bit_field() | (1 << kIsObserved));
5393 inline bool is_observed() {
5394 return ((1 << kIsObserved) & bit_field()) != 0;
5397 inline void set_is_strong();
5398 inline bool is_strong();
5399 inline void set_is_extensible(bool value);
5400 inline bool is_extensible();
5401 inline void set_is_prototype_map(bool value);
5402 inline bool is_prototype_map() const;
5404 inline void set_elements_kind(ElementsKind elements_kind) {
5405 DCHECK(static_cast<int>(elements_kind) < kElementsKindCount);
5406 DCHECK(kElementsKindCount <= (1 << Map::ElementsKindBits::kSize));
5407 set_bit_field2(Map::ElementsKindBits::update(bit_field2(), elements_kind));
5408 DCHECK(this->elements_kind() == elements_kind);
5411 inline ElementsKind elements_kind() {
5412 return Map::ElementsKindBits::decode(bit_field2());
5415 // Tells whether the instance has fast elements that are only Smis.
5416 inline bool has_fast_smi_elements() {
5417 return IsFastSmiElementsKind(elements_kind());
5420 // Tells whether the instance has fast elements.
5421 inline bool has_fast_object_elements() {
5422 return IsFastObjectElementsKind(elements_kind());
5425 inline bool has_fast_smi_or_object_elements() {
5426 return IsFastSmiOrObjectElementsKind(elements_kind());
5429 inline bool has_fast_double_elements() {
5430 return IsFastDoubleElementsKind(elements_kind());
5433 inline bool has_fast_elements() {
5434 return IsFastElementsKind(elements_kind());
5437 inline bool has_sloppy_arguments_elements() {
5438 return IsSloppyArgumentsElements(elements_kind());
5441 inline bool has_fixed_typed_array_elements() {
5442 return IsFixedTypedArrayElementsKind(elements_kind());
5445 inline bool has_dictionary_elements() {
5446 return IsDictionaryElementsKind(elements_kind());
5449 static bool IsValidElementsTransition(ElementsKind from_kind,
5450 ElementsKind to_kind);
5452 // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
5453 // map with DICTIONARY_ELEMENTS was found in the prototype chain.
5454 bool DictionaryElementsInPrototypeChainOnly();
5456 inline Map* ElementsTransitionMap();
5458 inline FixedArrayBase* GetInitialElements();
5460 // [raw_transitions]: Provides access to the transitions storage field.
5461 // Don't call set_raw_transitions() directly to overwrite transitions, use
5462 // the TransitionArray::ReplaceTransitions() wrapper instead!
5463 DECL_ACCESSORS(raw_transitions, Object)
5464 // [prototype_info]: Per-prototype metadata. Aliased with transitions
5465 // (which prototype maps don't have).
5466 DECL_ACCESSORS(prototype_info, Object)
5467 // PrototypeInfo is created lazily using this helper (which installs it on
5468 // the given prototype's map).
5469 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5470 Handle<JSObject> prototype, Isolate* isolate);
5472 // [prototype chain validity cell]: Associated with a prototype object,
5473 // stored in that object's map's PrototypeInfo, indicates that prototype
5474 // chains through this object are currently valid. The cell will be
5475 // invalidated and replaced when the prototype chain changes.
5476 static Handle<Cell> GetOrCreatePrototypeChainValidityCell(Handle<Map> map,
5478 static const int kPrototypeChainValid = 0;
5479 static const int kPrototypeChainInvalid = 1;
5482 Map* FindFieldOwner(int descriptor);
5484 inline int GetInObjectPropertyOffset(int index);
5486 int NumberOfFields();
5488 // TODO(ishell): candidate with JSObject::MigrateToMap().
5489 bool InstancesNeedRewriting(Map* target, int target_number_of_fields,
5490 int target_inobject, int target_unused,
5491 int* old_number_of_fields);
5492 // TODO(ishell): moveit!
5493 static Handle<Map> GeneralizeAllFieldRepresentations(Handle<Map> map);
5494 MUST_USE_RESULT static Handle<HeapType> GeneralizeFieldType(
5495 Handle<HeapType> type1,
5496 Handle<HeapType> type2,
5498 static void GeneralizeFieldType(Handle<Map> map, int modify_index,
5499 Representation new_representation,
5500 Handle<HeapType> new_field_type);
5501 static Handle<Map> ReconfigureProperty(Handle<Map> map, int modify_index,
5502 PropertyKind new_kind,
5503 PropertyAttributes new_attributes,
5504 Representation new_representation,
5505 Handle<HeapType> new_field_type,
5506 StoreMode store_mode);
5507 static Handle<Map> CopyGeneralizeAllRepresentations(
5508 Handle<Map> map, int modify_index, StoreMode store_mode,
5509 PropertyKind kind, PropertyAttributes attributes, const char* reason);
5511 static Handle<Map> PrepareForDataProperty(Handle<Map> old_map,
5512 int descriptor_number,
5513 Handle<Object> value);
5515 static Handle<Map> Normalize(Handle<Map> map, PropertyNormalizationMode mode,
5516 const char* reason);
5518 // Returns the constructor name (the name (possibly, inferred name) of the
5519 // function that was used to instantiate the object).
5520 String* constructor_name();
5522 // Tells whether the map is used for JSObjects in dictionary mode (ie
5523 // normalized objects, ie objects for which HasFastProperties returns false).
5524 // A map can never be used for both dictionary mode and fast mode JSObjects.
5525 // False by default and for HeapObjects that are not JSObjects.
5526 inline void set_dictionary_map(bool value);
5527 inline bool is_dictionary_map();
5529 // Tells whether the instance needs security checks when accessing its
5531 inline void set_is_access_check_needed(bool access_check_needed);
5532 inline bool is_access_check_needed();
5534 // Returns true if map has a non-empty stub code cache.
5535 inline bool has_code_cache();
5537 // [prototype]: implicit prototype object.
5538 DECL_ACCESSORS(prototype, Object)
5539 // TODO(jkummerow): make set_prototype private.
5540 static void SetPrototype(
5541 Handle<Map> map, Handle<Object> prototype,
5542 PrototypeOptimizationMode proto_mode = FAST_PROTOTYPE);
5544 // [constructor]: points back to the function responsible for this map.
5545 // The field overlaps with the back pointer. All maps in a transition tree
5546 // have the same constructor, so maps with back pointers can walk the
5547 // back pointer chain until they find the map holding their constructor.
5548 DECL_ACCESSORS(constructor_or_backpointer, Object)
5549 inline Object* GetConstructor() const;
5550 inline void SetConstructor(Object* constructor,
5551 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5552 // [back pointer]: points back to the parent map from which a transition
5553 // leads to this map. The field overlaps with the constructor (see above).
5554 inline Object* GetBackPointer();
5555 inline void SetBackPointer(Object* value,
5556 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5558 // [instance descriptors]: describes the object.
5559 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
5561 // [layout descriptor]: describes the object layout.
5562 DECL_ACCESSORS(layout_descriptor, LayoutDescriptor)
5563 // |layout descriptor| accessor which can be used from GC.
5564 inline LayoutDescriptor* layout_descriptor_gc_safe();
5565 inline bool HasFastPointerLayout() const;
5567 // |layout descriptor| accessor that is safe to call even when
5568 // FLAG_unbox_double_fields is disabled (in this case Map does not contain
5569 // |layout_descriptor| field at all).
5570 inline LayoutDescriptor* GetLayoutDescriptor();
5572 inline void UpdateDescriptors(DescriptorArray* descriptors,
5573 LayoutDescriptor* layout_descriptor);
5574 inline void InitializeDescriptors(DescriptorArray* descriptors,
5575 LayoutDescriptor* layout_descriptor);
5577 // [stub cache]: contains stubs compiled for this map.
5578 DECL_ACCESSORS(code_cache, Object)
5580 // [dependent code]: list of optimized codes that weakly embed this map.
5581 DECL_ACCESSORS(dependent_code, DependentCode)
5583 // [weak cell cache]: cache that stores a weak cell pointing to this map.
5584 DECL_ACCESSORS(weak_cell_cache, Object)
5586 inline PropertyDetails GetLastDescriptorDetails();
5589 int number_of_own_descriptors = NumberOfOwnDescriptors();
5590 DCHECK(number_of_own_descriptors > 0);
5591 return number_of_own_descriptors - 1;
5594 int NumberOfOwnDescriptors() {
5595 return NumberOfOwnDescriptorsBits::decode(bit_field3());
5598 void SetNumberOfOwnDescriptors(int number) {
5599 DCHECK(number <= instance_descriptors()->number_of_descriptors());
5600 set_bit_field3(NumberOfOwnDescriptorsBits::update(bit_field3(), number));
5603 inline Cell* RetrieveDescriptorsPointer();
5606 return EnumLengthBits::decode(bit_field3());
5609 void SetEnumLength(int length) {
5610 if (length != kInvalidEnumCacheSentinel) {
5611 DCHECK(length >= 0);
5612 DCHECK(length == 0 || instance_descriptors()->HasEnumCache());
5613 DCHECK(length <= NumberOfOwnDescriptors());
5615 set_bit_field3(EnumLengthBits::update(bit_field3(), length));
5618 inline bool owns_descriptors();
5619 inline void set_owns_descriptors(bool owns_descriptors);
5620 inline bool has_instance_call_handler();
5621 inline void set_has_instance_call_handler();
5622 inline void mark_unstable();
5623 inline bool is_stable();
5624 inline void set_migration_target(bool value);
5625 inline bool is_migration_target();
5626 inline void set_counter(int value);
5627 inline int counter();
5628 inline void deprecate();
5629 inline bool is_deprecated();
5630 inline bool CanBeDeprecated();
5631 // Returns a non-deprecated version of the input. If the input was not
5632 // deprecated, it is directly returned. Otherwise, the non-deprecated version
5633 // is found by re-transitioning from the root of the transition tree using the
5634 // descriptor array of the map. Returns MaybeHandle<Map>() if no updated map
5636 static MaybeHandle<Map> TryUpdate(Handle<Map> map) WARN_UNUSED_RESULT;
5638 // Returns a non-deprecated version of the input. This method may deprecate
5639 // existing maps along the way if encodings conflict. Not for use while
5640 // gathering type feedback. Use TryUpdate in those cases instead.
5641 static Handle<Map> Update(Handle<Map> map);
5643 static Handle<Map> CopyDropDescriptors(Handle<Map> map);
5644 static Handle<Map> CopyInsertDescriptor(Handle<Map> map,
5645 Descriptor* descriptor,
5646 TransitionFlag flag);
5648 MUST_USE_RESULT static MaybeHandle<Map> CopyWithField(
5651 Handle<HeapType> type,
5652 PropertyAttributes attributes,
5653 Representation representation,
5654 TransitionFlag flag);
5656 MUST_USE_RESULT static MaybeHandle<Map> CopyWithConstant(
5659 Handle<Object> constant,
5660 PropertyAttributes attributes,
5661 TransitionFlag flag);
5663 // Returns a new map with all transitions dropped from the given map and
5664 // the ElementsKind set.
5665 static Handle<Map> TransitionElementsTo(Handle<Map> map,
5666 ElementsKind to_kind);
5668 static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
5670 static Handle<Map> CopyAsElementsKind(Handle<Map> map,
5672 TransitionFlag flag);
5674 static Handle<Map> CopyForObserved(Handle<Map> map);
5676 static Handle<Map> CopyForPreventExtensions(Handle<Map> map,
5677 PropertyAttributes attrs_to_add,
5678 Handle<Symbol> transition_marker,
5679 const char* reason);
5681 static Handle<Map> FixProxy(Handle<Map> map, InstanceType type, int size);
5684 // Maximal number of fast properties. Used to restrict the number of map
5685 // transitions to avoid an explosion in the number of maps for objects used as
5687 inline bool TooManyFastProperties(StoreFromKeyed store_mode);
5688 static Handle<Map> TransitionToDataProperty(Handle<Map> map,
5690 Handle<Object> value,
5691 PropertyAttributes attributes,
5692 StoreFromKeyed store_mode);
5693 static Handle<Map> TransitionToAccessorProperty(
5694 Handle<Map> map, Handle<Name> name, AccessorComponent component,
5695 Handle<Object> accessor, PropertyAttributes attributes);
5696 static Handle<Map> ReconfigureExistingProperty(Handle<Map> map,
5699 PropertyAttributes attributes);
5701 inline void AppendDescriptor(Descriptor* desc);
5703 // Returns a copy of the map, prepared for inserting into the transition
5704 // tree (if the |map| owns descriptors then the new one will share
5705 // descriptors with |map|).
5706 static Handle<Map> CopyForTransition(Handle<Map> map, const char* reason);
5708 // Returns a copy of the map, with all transitions dropped from the
5709 // instance descriptors.
5710 static Handle<Map> Copy(Handle<Map> map, const char* reason);
5711 static Handle<Map> Create(Isolate* isolate, int inobject_properties);
5713 // Returns the next free property index (only valid for FAST MODE).
5714 int NextFreePropertyIndex();
5716 // Returns the number of properties described in instance_descriptors
5717 // filtering out properties with the specified attributes.
5718 int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
5719 PropertyAttributes filter = NONE);
5723 // Code cache operations.
5725 // Clears the code cache.
5726 inline void ClearCodeCache(Heap* heap);
5728 // Update code cache.
5729 static void UpdateCodeCache(Handle<Map> map,
5733 // Extend the descriptor array of the map with the list of descriptors.
5734 // In case of duplicates, the latest descriptor is used.
5735 static void AppendCallbackDescriptors(Handle<Map> map,
5736 Handle<Object> descriptors);
5738 static inline int SlackForArraySize(int old_size, int size_limit);
5740 static void EnsureDescriptorSlack(Handle<Map> map, int slack);
5742 // Returns the found code or undefined if absent.
5743 Object* FindInCodeCache(Name* name, Code::Flags flags);
5745 // Returns the non-negative index of the code object if it is in the
5746 // cache and -1 otherwise.
5747 int IndexInCodeCache(Object* name, Code* code);
5749 // Removes a code object from the code cache at the given index.
5750 void RemoveFromCodeCache(Name* name, Code* code, int index);
5752 // Computes a hash value for this map, to be used in HashTables and such.
5755 // Returns the map that this map transitions to if its elements_kind
5756 // is changed to |elements_kind|, or NULL if no such map is cached yet.
5757 // |safe_to_add_transitions| is set to false if adding transitions is not
5759 Map* LookupElementsTransitionMap(ElementsKind elements_kind);
5761 // Returns the transitioned map for this map with the most generic
5762 // elements_kind that's found in |candidates|, or null handle if no match is
5764 static Handle<Map> FindTransitionedMap(Handle<Map> map,
5765 MapHandleList* candidates);
5767 bool CanTransition() {
5768 // Only JSObject and subtypes have map transitions and back pointers.
5769 STATIC_ASSERT(LAST_TYPE == LAST_JS_OBJECT_TYPE);
5770 return instance_type() >= FIRST_JS_OBJECT_TYPE;
5773 bool IsJSObjectMap() {
5774 return instance_type() >= FIRST_JS_OBJECT_TYPE;
5776 bool IsJSArrayMap() { return instance_type() == JS_ARRAY_TYPE; }
5777 bool IsStringMap() { return instance_type() < FIRST_NONSTRING_TYPE; }
5778 bool IsJSProxyMap() {
5779 InstanceType type = instance_type();
5780 return FIRST_JS_PROXY_TYPE <= type && type <= LAST_JS_PROXY_TYPE;
5782 bool IsJSGlobalProxyMap() {
5783 return instance_type() == JS_GLOBAL_PROXY_TYPE;
5785 bool IsJSGlobalObjectMap() {
5786 return instance_type() == JS_GLOBAL_OBJECT_TYPE;
5788 bool IsGlobalObjectMap() {
5789 const InstanceType type = instance_type();
5790 return type == JS_GLOBAL_OBJECT_TYPE || type == JS_BUILTINS_OBJECT_TYPE;
5793 inline bool CanOmitMapChecks();
5795 static void AddDependentCode(Handle<Map> map,
5796 DependentCode::DependencyGroup group,
5799 bool IsMapInArrayPrototypeChain();
5801 static Handle<WeakCell> WeakCellForMap(Handle<Map> map);
5803 // Dispatched behavior.
5804 DECLARE_PRINTER(Map)
5805 DECLARE_VERIFIER(Map)
5808 void DictionaryMapVerify();
5809 void VerifyOmittedMapChecks();
5812 inline int visitor_id();
5813 inline void set_visitor_id(int visitor_id);
5815 static Handle<Map> TransitionToPrototype(Handle<Map> map,
5816 Handle<Object> prototype,
5817 PrototypeOptimizationMode mode);
5819 static const int kMaxPreAllocatedPropertyFields = 255;
5821 // Layout description.
5822 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
5823 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
5824 static const int kBitField3Offset = kInstanceAttributesOffset + kIntSize;
5825 static const int kPrototypeOffset = kBitField3Offset + kPointerSize;
5826 static const int kConstructorOrBackPointerOffset =
5827 kPrototypeOffset + kPointerSize;
5828 // When there is only one transition, it is stored directly in this field;
5829 // otherwise a transition array is used.
5830 // For prototype maps, this slot is used to store this map's PrototypeInfo
5832 static const int kTransitionsOrPrototypeInfoOffset =
5833 kConstructorOrBackPointerOffset + kPointerSize;
5834 static const int kDescriptorsOffset =
5835 kTransitionsOrPrototypeInfoOffset + kPointerSize;
5836 #if V8_DOUBLE_FIELDS_UNBOXING
5837 static const int kLayoutDecriptorOffset = kDescriptorsOffset + kPointerSize;
5838 static const int kCodeCacheOffset = kLayoutDecriptorOffset + kPointerSize;
5840 static const int kLayoutDecriptorOffset = 1; // Must not be ever accessed.
5841 static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
5843 static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
5844 static const int kWeakCellCacheOffset = kDependentCodeOffset + kPointerSize;
5845 static const int kSize = kWeakCellCacheOffset + kPointerSize;
5847 // Layout of pointer fields. Heap iteration code relies on them
5848 // being continuously allocated.
5849 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
5850 static const int kPointerFieldsEndOffset = kSize;
5852 // Byte offsets within kInstanceSizesOffset.
5853 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
5854 static const int kInObjectPropertiesByte = 1;
5855 static const int kInObjectPropertiesOffset =
5856 kInstanceSizesOffset + kInObjectPropertiesByte;
5857 // Note there is one byte available for use here.
5858 static const int kUnusedByte = 2;
5859 static const int kUnusedOffset = kInstanceSizesOffset + kUnusedByte;
5860 static const int kVisitorIdByte = 3;
5861 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
5863 // Byte offsets within kInstanceAttributesOffset attributes.
5864 #if V8_TARGET_LITTLE_ENDIAN
5865 // Order instance type and bit field together such that they can be loaded
5866 // together as a 16-bit word with instance type in the lower 8 bits regardless
5867 // of endianess. Also provide endian-independent offset to that 16-bit word.
5868 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
5869 static const int kBitFieldOffset = kInstanceAttributesOffset + 1;
5871 static const int kBitFieldOffset = kInstanceAttributesOffset + 0;
5872 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 1;
5874 static const int kInstanceTypeAndBitFieldOffset =
5875 kInstanceAttributesOffset + 0;
5876 static const int kBitField2Offset = kInstanceAttributesOffset + 2;
5877 static const int kUnusedPropertyFieldsByte = 3;
5878 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 3;
5880 STATIC_ASSERT(kInstanceTypeAndBitFieldOffset ==
5881 Internals::kMapInstanceTypeAndBitFieldOffset);
5883 // Bit positions for bit field.
5884 static const int kHasNonInstancePrototype = 0;
5885 static const int kIsHiddenPrototype = 1;
5886 static const int kHasNamedInterceptor = 2;
5887 static const int kHasIndexedInterceptor = 3;
5888 static const int kIsUndetectable = 4;
5889 static const int kIsObserved = 5;
5890 static const int kIsAccessCheckNeeded = 6;
5891 class FunctionWithPrototype: public BitField<bool, 7, 1> {};
5893 // Bit positions for bit field 2
5894 static const int kIsExtensible = 0;
5895 static const int kStringWrapperSafeForDefaultValueOf = 1;
5896 class IsPrototypeMapBits : public BitField<bool, 2, 1> {};
5897 class ElementsKindBits: public BitField<ElementsKind, 3, 5> {};
5899 // Derived values from bit field 2
5900 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
5901 (FAST_ELEMENTS + 1) << Map::ElementsKindBits::kShift) - 1;
5902 static const int8_t kMaximumBitField2FastSmiElementValue =
5903 static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
5904 Map::ElementsKindBits::kShift) - 1;
5905 static const int8_t kMaximumBitField2FastHoleyElementValue =
5906 static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
5907 Map::ElementsKindBits::kShift) - 1;
5908 static const int8_t kMaximumBitField2FastHoleySmiElementValue =
5909 static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
5910 Map::ElementsKindBits::kShift) - 1;
5912 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
5913 kPointerFieldsEndOffset,
5914 kSize> BodyDescriptor;
5916 // Compares this map to another to see if they describe equivalent objects.
5917 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
5918 // it had exactly zero inobject properties.
5919 // The "shared" flags of both this map and |other| are ignored.
5920 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
5922 // Returns true if given field is unboxed double.
5923 inline bool IsUnboxedDoubleField(FieldIndex index);
5926 static void TraceTransition(const char* what, Map* from, Map* to, Name* name);
5927 static void TraceAllTransitions(Map* map);
5930 static inline Handle<Map> CopyInstallDescriptorsForTesting(
5931 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5932 Handle<LayoutDescriptor> layout_descriptor);
5935 static void ConnectTransition(Handle<Map> parent, Handle<Map> child,
5936 Handle<Name> name, SimpleTransitionFlag flag);
5938 bool EquivalentToForTransition(Map* other);
5939 static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
5940 static Handle<Map> ShareDescriptor(Handle<Map> map,
5941 Handle<DescriptorArray> descriptors,
5942 Descriptor* descriptor);
5943 static Handle<Map> CopyInstallDescriptors(
5944 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5945 Handle<LayoutDescriptor> layout_descriptor);
5946 static Handle<Map> CopyAddDescriptor(Handle<Map> map,
5947 Descriptor* descriptor,
5948 TransitionFlag flag);
5949 static Handle<Map> CopyReplaceDescriptors(
5950 Handle<Map> map, Handle<DescriptorArray> descriptors,
5951 Handle<LayoutDescriptor> layout_descriptor, TransitionFlag flag,
5952 MaybeHandle<Name> maybe_name, const char* reason,
5953 SimpleTransitionFlag simple_flag);
5955 static Handle<Map> CopyReplaceDescriptor(Handle<Map> map,
5956 Handle<DescriptorArray> descriptors,
5957 Descriptor* descriptor,
5959 TransitionFlag flag);
5960 static MUST_USE_RESULT MaybeHandle<Map> TryReconfigureExistingProperty(
5961 Handle<Map> map, int descriptor, PropertyKind kind,
5962 PropertyAttributes attributes, const char** reason);
5964 static Handle<Map> CopyNormalized(Handle<Map> map,
5965 PropertyNormalizationMode mode);
5967 // Fires when the layout of an object with a leaf map changes.
5968 // This includes adding transitions to the leaf map or changing
5969 // the descriptor array.
5970 inline void NotifyLeafMapLayoutChange();
5972 void DeprecateTransitionTree();
5973 bool DeprecateTarget(PropertyKind kind, Name* key,
5974 PropertyAttributes attributes,
5975 DescriptorArray* new_descriptors,
5976 LayoutDescriptor* new_layout_descriptor);
5978 Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
5980 // Update field type of the given descriptor to new representation and new
5981 // type. The type must be prepared for storing in descriptor array:
5982 // it must be either a simple type or a map wrapped in a weak cell.
5983 void UpdateFieldType(int descriptor_number, Handle<Name> name,
5984 Representation new_representation,
5985 Handle<Object> new_wrapped_type);
5987 void PrintReconfiguration(FILE* file, int modify_index, PropertyKind kind,
5988 PropertyAttributes attributes);
5989 void PrintGeneralization(FILE* file,
5994 bool constant_to_field,
5995 Representation old_representation,
5996 Representation new_representation,
5997 HeapType* old_field_type,
5998 HeapType* new_field_type);
6000 static const int kFastPropertiesSoftLimit = 12;
6001 static const int kMaxFastProperties = 128;
6003 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
6007 // An abstract superclass, a marker class really, for simple structure classes.
6008 // It doesn't carry much functionality but allows struct classes to be
6009 // identified in the type system.
6010 class Struct: public HeapObject {
6012 inline void InitializeBody(int object_size);
6013 DECLARE_CAST(Struct)
6017 // A simple one-element struct, useful where smis need to be boxed.
6018 class Box : public Struct {
6020 // [value]: the boxed contents.
6021 DECL_ACCESSORS(value, Object)
6025 // Dispatched behavior.
6026 DECLARE_PRINTER(Box)
6027 DECLARE_VERIFIER(Box)
6029 static const int kValueOffset = HeapObject::kHeaderSize;
6030 static const int kSize = kValueOffset + kPointerSize;
6033 DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
6037 // Container for metadata stored on each prototype map.
6038 class PrototypeInfo : public Struct {
6040 // [prototype_users]: WeakFixedArray containing maps using this prototype,
6041 // or Smi(0) if uninitialized.
6042 DECL_ACCESSORS(prototype_users, Object)
6043 // [validity_cell]: Cell containing the validity bit for prototype chains
6044 // going through this object, or Smi(0) if uninitialized.
6045 DECL_ACCESSORS(validity_cell, Object)
6046 // [constructor_name]: User-friendly name of the original constructor.
6047 DECL_ACCESSORS(constructor_name, Object)
6049 DECLARE_CAST(PrototypeInfo)
6051 // Dispatched behavior.
6052 DECLARE_PRINTER(PrototypeInfo)
6053 DECLARE_VERIFIER(PrototypeInfo)
6055 static const int kPrototypeUsersOffset = HeapObject::kHeaderSize;
6056 static const int kValidityCellOffset = kPrototypeUsersOffset + kPointerSize;
6057 static const int kConstructorNameOffset = kValidityCellOffset + kPointerSize;
6058 static const int kSize = kConstructorNameOffset + kPointerSize;
6061 DISALLOW_IMPLICIT_CONSTRUCTORS(PrototypeInfo);
6065 // Script describes a script which has been added to the VM.
6066 class Script: public Struct {
6075 // Script compilation types.
6076 enum CompilationType {
6077 COMPILATION_TYPE_HOST = 0,
6078 COMPILATION_TYPE_EVAL = 1
6081 // Script compilation state.
6082 enum CompilationState {
6083 COMPILATION_STATE_INITIAL = 0,
6084 COMPILATION_STATE_COMPILED = 1
6087 // [source]: the script source.
6088 DECL_ACCESSORS(source, Object)
6090 // [name]: the script name.
6091 DECL_ACCESSORS(name, Object)
6093 // [id]: the script id.
6094 DECL_ACCESSORS(id, Smi)
6096 // [line_offset]: script line offset in resource from where it was extracted.
6097 DECL_ACCESSORS(line_offset, Smi)
6099 // [column_offset]: script column offset in resource from where it was
6101 DECL_ACCESSORS(column_offset, Smi)
6103 // [context_data]: context data for the context this script was compiled in.
6104 DECL_ACCESSORS(context_data, Object)
6106 // [wrapper]: the wrapper cache. This is either undefined or a WeakCell.
6107 DECL_ACCESSORS(wrapper, HeapObject)
6109 // [type]: the script type.
6110 DECL_ACCESSORS(type, Smi)
6112 // [line_ends]: FixedArray of line ends positions.
6113 DECL_ACCESSORS(line_ends, Object)
6115 // [eval_from_shared]: for eval scripts the shared funcion info for the
6116 // function from which eval was called.
6117 DECL_ACCESSORS(eval_from_shared, Object)
6119 // [eval_from_instructions_offset]: the instruction offset in the code for the
6120 // function from which eval was called where eval was called.
6121 DECL_ACCESSORS(eval_from_instructions_offset, Smi)
6123 // [shared_function_infos]: weak fixed array containing all shared
6124 // function infos created from this script.
6125 DECL_ACCESSORS(shared_function_infos, Object)
6127 // [flags]: Holds an exciting bitfield.
6128 DECL_ACCESSORS(flags, Smi)
6130 // [source_url]: sourceURL from magic comment
6131 DECL_ACCESSORS(source_url, Object)
6133 // [source_url]: sourceMappingURL magic comment
6134 DECL_ACCESSORS(source_mapping_url, Object)
6136 // [compilation_type]: how the the script was compiled. Encoded in the
6138 inline CompilationType compilation_type();
6139 inline void set_compilation_type(CompilationType type);
6141 // [compilation_state]: determines whether the script has already been
6142 // compiled. Encoded in the 'flags' field.
6143 inline CompilationState compilation_state();
6144 inline void set_compilation_state(CompilationState state);
6146 // [origin_options]: optional attributes set by the embedder via ScriptOrigin,
6147 // and used by the embedder to make decisions about the script. V8 just passes
6148 // this through. Encoded in the 'flags' field.
6149 inline v8::ScriptOriginOptions origin_options();
6150 inline void set_origin_options(ScriptOriginOptions origin_options);
6152 DECLARE_CAST(Script)
6154 // If script source is an external string, check that the underlying
6155 // resource is accessible. Otherwise, always return true.
6156 inline bool HasValidSource();
6158 // Convert code position into column number.
6159 static int GetColumnNumber(Handle<Script> script, int code_pos);
6161 // Convert code position into (zero-based) line number.
6162 // The non-handlified version does not allocate, but may be much slower.
6163 static int GetLineNumber(Handle<Script> script, int code_pos);
6164 int GetLineNumber(int code_pos);
6166 static Handle<Object> GetNameOrSourceURL(Handle<Script> script);
6168 // Init line_ends array with code positions of line ends inside script source.
6169 static void InitLineEnds(Handle<Script> script);
6171 // Get the JS object wrapping the given script; create it if none exists.
6172 static Handle<JSObject> GetWrapper(Handle<Script> script);
6174 // Look through the list of existing shared function infos to find one
6175 // that matches the function literal. Return empty handle if not found.
6176 MaybeHandle<SharedFunctionInfo> FindSharedFunctionInfo(FunctionLiteral* fun);
6178 // Dispatched behavior.
6179 DECLARE_PRINTER(Script)
6180 DECLARE_VERIFIER(Script)
6182 static const int kSourceOffset = HeapObject::kHeaderSize;
6183 static const int kNameOffset = kSourceOffset + kPointerSize;
6184 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
6185 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
6186 static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
6187 static const int kWrapperOffset = kContextOffset + kPointerSize;
6188 static const int kTypeOffset = kWrapperOffset + kPointerSize;
6189 static const int kLineEndsOffset = kTypeOffset + kPointerSize;
6190 static const int kIdOffset = kLineEndsOffset + kPointerSize;
6191 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
6192 static const int kEvalFrominstructionsOffsetOffset =
6193 kEvalFromSharedOffset + kPointerSize;
6194 static const int kSharedFunctionInfosOffset =
6195 kEvalFrominstructionsOffsetOffset + kPointerSize;
6196 static const int kFlagsOffset = kSharedFunctionInfosOffset + kPointerSize;
6197 static const int kSourceUrlOffset = kFlagsOffset + kPointerSize;
6198 static const int kSourceMappingUrlOffset = kSourceUrlOffset + kPointerSize;
6199 static const int kSize = kSourceMappingUrlOffset + kPointerSize;
6202 int GetLineNumberWithArray(int code_pos);
6204 // Bit positions in the flags field.
6205 static const int kCompilationTypeBit = 0;
6206 static const int kCompilationStateBit = 1;
6207 static const int kOriginOptionsShift = 2;
6208 static const int kOriginOptionsSize = 3;
6209 static const int kOriginOptionsMask = ((1 << kOriginOptionsSize) - 1)
6210 << kOriginOptionsShift;
6212 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6216 // List of builtin functions we want to identify to improve code
6219 // Each entry has a name of a global object property holding an object
6220 // optionally followed by ".prototype", a name of a builtin function
6221 // on the object (the one the id is set for), and a label.
6223 // Installation of ids for the selected builtin functions is handled
6224 // by the bootstrapper.
6225 #define FUNCTIONS_WITH_ID_LIST(V) \
6226 V(Array.prototype, indexOf, ArrayIndexOf) \
6227 V(Array.prototype, lastIndexOf, ArrayLastIndexOf) \
6228 V(Array.prototype, push, ArrayPush) \
6229 V(Array.prototype, pop, ArrayPop) \
6230 V(Array.prototype, shift, ArrayShift) \
6231 V(Function.prototype, apply, FunctionApply) \
6232 V(Function.prototype, call, FunctionCall) \
6233 V(String.prototype, charCodeAt, StringCharCodeAt) \
6234 V(String.prototype, charAt, StringCharAt) \
6235 V(String, fromCharCode, StringFromCharCode) \
6236 V(Math, random, MathRandom) \
6237 V(Math, floor, MathFloor) \
6238 V(Math, round, MathRound) \
6239 V(Math, ceil, MathCeil) \
6240 V(Math, abs, MathAbs) \
6241 V(Math, log, MathLog) \
6242 V(Math, exp, MathExp) \
6243 V(Math, sqrt, MathSqrt) \
6244 V(Math, pow, MathPow) \
6245 V(Math, max, MathMax) \
6246 V(Math, min, MathMin) \
6247 V(Math, cos, MathCos) \
6248 V(Math, sin, MathSin) \
6249 V(Math, tan, MathTan) \
6250 V(Math, acos, MathAcos) \
6251 V(Math, asin, MathAsin) \
6252 V(Math, atan, MathAtan) \
6253 V(Math, atan2, MathAtan2) \
6254 V(Math, imul, MathImul) \
6255 V(Math, clz32, MathClz32) \
6256 V(Math, fround, MathFround)
6258 #define ATOMIC_FUNCTIONS_WITH_ID_LIST(V) \
6259 V(Atomics, load, AtomicsLoad) \
6260 V(Atomics, store, AtomicsStore)
6262 enum BuiltinFunctionId {
6264 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
6266 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6267 ATOMIC_FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6268 #undef DECLARE_FUNCTION_ID
6269 // Fake id for a special case of Math.pow. Note, it continues the
6270 // list of math functions.
6275 // Result of searching in an optimized code map of a SharedFunctionInfo. Note
6276 // that both {code} and {literals} can be NULL to pass search result status.
6277 struct CodeAndLiterals {
6278 Code* code; // Cached optimized code.
6279 FixedArray* literals; // Cached literals array.
6283 // SharedFunctionInfo describes the JSFunction information that can be
6284 // shared by multiple instances of the function.
6285 class SharedFunctionInfo: public HeapObject {
6287 // [name]: Function name.
6288 DECL_ACCESSORS(name, Object)
6290 // [code]: Function code.
6291 DECL_ACCESSORS(code, Code)
6292 inline void ReplaceCode(Code* code);
6294 // [optimized_code_map]: Map from native context to optimized code
6295 // and a shared literals array or Smi(0) if none.
6296 DECL_ACCESSORS(optimized_code_map, Object)
6298 // Returns entry from optimized code map for specified context and OSR entry.
6299 // Note that {code == nullptr} indicates no matching entry has been found,
6300 // whereas {literals == nullptr} indicates the code is context-independent.
6301 CodeAndLiterals SearchOptimizedCodeMap(Context* native_context,
6302 BailoutId osr_ast_id);
6304 // Clear optimized code map.
6305 void ClearOptimizedCodeMap();
6307 // Removed a specific optimized code object from the optimized code map.
6308 void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
6310 // Trims the optimized code map after entries have been removed.
6311 void TrimOptimizedCodeMap(int shrink_by);
6313 // Add a new entry to the optimized code map for context-independent code.
6314 static void AddSharedCodeToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6317 // Add a new entry to the optimized code map for context-dependent code.
6318 static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6319 Handle<Context> native_context,
6321 Handle<FixedArray> literals,
6322 BailoutId osr_ast_id);
6324 // Set up the link between shared function info and the script. The shared
6325 // function info is added to the list on the script.
6326 static void SetScript(Handle<SharedFunctionInfo> shared,
6327 Handle<Object> script_object);
6329 // Layout description of the optimized code map.
6330 static const int kNextMapIndex = 0;
6331 static const int kSharedCodeIndex = 1;
6332 static const int kEntriesStart = 2;
6333 static const int kContextOffset = 0;
6334 static const int kCachedCodeOffset = 1;
6335 static const int kLiteralsOffset = 2;
6336 static const int kOsrAstIdOffset = 3;
6337 static const int kEntryLength = 4;
6338 static const int kInitialLength = kEntriesStart + kEntryLength;
6340 // [scope_info]: Scope info.
6341 DECL_ACCESSORS(scope_info, ScopeInfo)
6343 // [construct stub]: Code stub for constructing instances of this function.
6344 DECL_ACCESSORS(construct_stub, Code)
6346 // Returns if this function has been compiled to native code yet.
6347 inline bool is_compiled();
6349 // [length]: The function length - usually the number of declared parameters.
6350 // Use up to 2^30 parameters.
6351 inline int length() const;
6352 inline void set_length(int value);
6354 // [internal formal parameter count]: The declared number of parameters.
6355 // For subclass constructors, also includes new.target.
6356 // The size of function's frame is internal_formal_parameter_count + 1.
6357 inline int internal_formal_parameter_count() const;
6358 inline void set_internal_formal_parameter_count(int value);
6360 // Set the formal parameter count so the function code will be
6361 // called without using argument adaptor frames.
6362 inline void DontAdaptArguments();
6364 // [expected_nof_properties]: Expected number of properties for the function.
6365 inline int expected_nof_properties() const;
6366 inline void set_expected_nof_properties(int value);
6368 // [feedback_vector] - accumulates ast node feedback from full-codegen and
6369 // (increasingly) from crankshafted code where sufficient feedback isn't
6371 DECL_ACCESSORS(feedback_vector, TypeFeedbackVector)
6373 // Unconditionally clear the type feedback vector (including vector ICs).
6374 void ClearTypeFeedbackInfo();
6376 // Clear the type feedback vector with a more subtle policy at GC time.
6377 void ClearTypeFeedbackInfoAtGCTime();
6380 // [unique_id] - For --trace-maps purposes, an identifier that's persistent
6381 // even if the GC moves this SharedFunctionInfo.
6382 inline int unique_id() const;
6383 inline void set_unique_id(int value);
6386 // [instance class name]: class name for instances.
6387 DECL_ACCESSORS(instance_class_name, Object)
6389 // [function data]: This field holds some additional data for function.
6390 // Currently it has one of:
6391 // - a FunctionTemplateInfo to make benefit the API [IsApiFunction()].
6392 // - a Smi identifying a builtin function [HasBuiltinFunctionId()].
6393 // - a BytecodeArray for the interpreter [HasBytecodeArray()].
6394 // In the long run we don't want all functions to have this field but
6395 // we can fix that when we have a better model for storing hidden data
6397 DECL_ACCESSORS(function_data, Object)
6399 inline bool IsApiFunction();
6400 inline FunctionTemplateInfo* get_api_func_data();
6401 inline bool HasBuiltinFunctionId();
6402 inline BuiltinFunctionId builtin_function_id();
6403 inline bool HasBytecodeArray();
6404 inline BytecodeArray* bytecode_array();
6406 // [script info]: Script from which the function originates.
6407 DECL_ACCESSORS(script, Object)
6409 // [num_literals]: Number of literals used by this function.
6410 inline int num_literals() const;
6411 inline void set_num_literals(int value);
6413 // [start_position_and_type]: Field used to store both the source code
6414 // position, whether or not the function is a function expression,
6415 // and whether or not the function is a toplevel function. The two
6416 // least significants bit indicates whether the function is an
6417 // expression and the rest contains the source code position.
6418 inline int start_position_and_type() const;
6419 inline void set_start_position_and_type(int value);
6421 // The function is subject to debugging if a debug info is attached.
6422 inline bool HasDebugInfo();
6423 inline DebugInfo* GetDebugInfo();
6425 // A function has debug code if the compiled code has debug break slots.
6426 inline bool HasDebugCode();
6428 // [debug info]: Debug information.
6429 DECL_ACCESSORS(debug_info, Object)
6431 // [inferred name]: Name inferred from variable or property
6432 // assignment of this function. Used to facilitate debugging and
6433 // profiling of JavaScript code written in OO style, where almost
6434 // all functions are anonymous but are assigned to object
6436 DECL_ACCESSORS(inferred_name, String)
6438 // The function's name if it is non-empty, otherwise the inferred name.
6439 String* DebugName();
6441 // Position of the 'function' token in the script source.
6442 inline int function_token_position() const;
6443 inline void set_function_token_position(int function_token_position);
6445 // Position of this function in the script source.
6446 inline int start_position() const;
6447 inline void set_start_position(int start_position);
6449 // End position of this function in the script source.
6450 inline int end_position() const;
6451 inline void set_end_position(int end_position);
6453 // Is this function a function expression in the source code.
6454 DECL_BOOLEAN_ACCESSORS(is_expression)
6456 // Is this function a top-level function (scripts, evals).
6457 DECL_BOOLEAN_ACCESSORS(is_toplevel)
6459 // Bit field containing various information collected by the compiler to
6460 // drive optimization.
6461 inline int compiler_hints() const;
6462 inline void set_compiler_hints(int value);
6464 inline int ast_node_count() const;
6465 inline void set_ast_node_count(int count);
6467 inline int profiler_ticks() const;
6468 inline void set_profiler_ticks(int ticks);
6470 // Inline cache age is used to infer whether the function survived a context
6471 // disposal or not. In the former case we reset the opt_count.
6472 inline int ic_age();
6473 inline void set_ic_age(int age);
6475 // Indicates if this function can be lazy compiled.
6476 // This is used to determine if we can safely flush code from a function
6477 // when doing GC if we expect that the function will no longer be used.
6478 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
6480 // Indicates if this function can be lazy compiled without a context.
6481 // This is used to determine if we can force compilation without reaching
6482 // the function through program execution but through other means (e.g. heap
6483 // iteration by the debugger).
6484 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
6486 // Indicates whether optimizations have been disabled for this
6487 // shared function info. If a function is repeatedly optimized or if
6488 // we cannot optimize the function we disable optimization to avoid
6489 // spending time attempting to optimize it again.
6490 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
6492 // Indicates the language mode.
6493 inline LanguageMode language_mode();
6494 inline void set_language_mode(LanguageMode language_mode);
6496 // False if the function definitely does not allocate an arguments object.
6497 DECL_BOOLEAN_ACCESSORS(uses_arguments)
6499 // Indicates that this function uses a super property (or an eval that may
6500 // use a super property).
6501 // This is needed to set up the [[HomeObject]] on the function instance.
6502 DECL_BOOLEAN_ACCESSORS(needs_home_object)
6504 // True if the function has any duplicated parameter names.
6505 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
6507 // Indicates whether the function is a native function.
6508 // These needs special treatment in .call and .apply since
6509 // null passed as the receiver should not be translated to the
6511 DECL_BOOLEAN_ACCESSORS(native)
6513 // Indicate that this function should always be inlined in optimized code.
6514 DECL_BOOLEAN_ACCESSORS(force_inline)
6516 // Indicates that the function was created by the Function function.
6517 // Though it's anonymous, toString should treat it as if it had the name
6518 // "anonymous". We don't set the name itself so that the system does not
6519 // see a binding for it.
6520 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
6522 // Indicates whether the function is a bound function created using
6523 // the bind function.
6524 DECL_BOOLEAN_ACCESSORS(bound)
6526 // Indicates that the function is anonymous (the name field can be set
6527 // through the API, which does not change this flag).
6528 DECL_BOOLEAN_ACCESSORS(is_anonymous)
6530 // Is this a function or top-level/eval code.
6531 DECL_BOOLEAN_ACCESSORS(is_function)
6533 // Indicates that code for this function cannot be compiled with Crankshaft.
6534 DECL_BOOLEAN_ACCESSORS(dont_crankshaft)
6536 // Indicates that code for this function cannot be flushed.
6537 DECL_BOOLEAN_ACCESSORS(dont_flush)
6539 // Indicates that this function is a generator.
6540 DECL_BOOLEAN_ACCESSORS(is_generator)
6542 // Indicates that this function is an arrow function.
6543 DECL_BOOLEAN_ACCESSORS(is_arrow)
6545 // Indicates that this function is a concise method.
6546 DECL_BOOLEAN_ACCESSORS(is_concise_method)
6548 // Indicates that this function is an accessor (getter or setter).
6549 DECL_BOOLEAN_ACCESSORS(is_accessor_function)
6551 // Indicates that this function is a default constructor.
6552 DECL_BOOLEAN_ACCESSORS(is_default_constructor)
6554 // Indicates that this function is an asm function.
6555 DECL_BOOLEAN_ACCESSORS(asm_function)
6557 // Indicates that the the shared function info is deserialized from cache.
6558 DECL_BOOLEAN_ACCESSORS(deserialized)
6560 // Indicates that the the shared function info has never been compiled before.
6561 DECL_BOOLEAN_ACCESSORS(never_compiled)
6563 inline FunctionKind kind();
6564 inline void set_kind(FunctionKind kind);
6566 // Indicates whether or not the code in the shared function support
6568 inline bool has_deoptimization_support();
6570 // Enable deoptimization support through recompiled code.
6571 void EnableDeoptimizationSupport(Code* recompiled);
6573 // Disable (further) attempted optimization of all functions sharing this
6574 // shared function info.
6575 void DisableOptimization(BailoutReason reason);
6577 inline BailoutReason disable_optimization_reason();
6579 // Lookup the bailout ID and DCHECK that it exists in the non-optimized
6580 // code, returns whether it asserted (i.e., always true if assertions are
6582 bool VerifyBailoutId(BailoutId id);
6584 // [source code]: Source code for the function.
6585 bool HasSourceCode() const;
6586 Handle<Object> GetSourceCode();
6588 // Number of times the function was optimized.
6589 inline int opt_count();
6590 inline void set_opt_count(int opt_count);
6592 // Number of times the function was deoptimized.
6593 inline void set_deopt_count(int value);
6594 inline int deopt_count();
6595 inline void increment_deopt_count();
6597 // Number of time we tried to re-enable optimization after it
6598 // was disabled due to high number of deoptimizations.
6599 inline void set_opt_reenable_tries(int value);
6600 inline int opt_reenable_tries();
6602 inline void TryReenableOptimization();
6604 // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
6605 inline void set_counters(int value);
6606 inline int counters() const;
6608 // Stores opt_count and bailout_reason as bit-fields.
6609 inline void set_opt_count_and_bailout_reason(int value);
6610 inline int opt_count_and_bailout_reason() const;
6612 void set_disable_optimization_reason(BailoutReason reason) {
6613 set_opt_count_and_bailout_reason(
6614 DisabledOptimizationReasonBits::update(opt_count_and_bailout_reason(),
6618 // Tells whether this function should be subject to debugging.
6619 inline bool IsSubjectToDebugging();
6621 // Check whether or not this function is inlineable.
6622 bool IsInlineable();
6624 // Source size of this function.
6627 // Calculate the instance size.
6628 int CalculateInstanceSize();
6630 // Calculate the number of in-object properties.
6631 int CalculateInObjectProperties();
6633 inline bool has_simple_parameters();
6635 // Initialize a SharedFunctionInfo from a parsed function literal.
6636 static void InitFromFunctionLiteral(Handle<SharedFunctionInfo> shared_info,
6637 FunctionLiteral* lit);
6639 // Dispatched behavior.
6640 DECLARE_PRINTER(SharedFunctionInfo)
6641 DECLARE_VERIFIER(SharedFunctionInfo)
6643 void ResetForNewContext(int new_ic_age);
6645 DECLARE_CAST(SharedFunctionInfo)
6648 static const int kDontAdaptArgumentsSentinel = -1;
6650 // Layout description.
6652 static const int kNameOffset = HeapObject::kHeaderSize;
6653 static const int kCodeOffset = kNameOffset + kPointerSize;
6654 static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
6655 static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
6656 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
6657 static const int kInstanceClassNameOffset =
6658 kConstructStubOffset + kPointerSize;
6659 static const int kFunctionDataOffset =
6660 kInstanceClassNameOffset + kPointerSize;
6661 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
6662 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
6663 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
6664 static const int kFeedbackVectorOffset =
6665 kInferredNameOffset + kPointerSize;
6667 static const int kUniqueIdOffset = kFeedbackVectorOffset + kPointerSize;
6668 static const int kLastPointerFieldOffset = kUniqueIdOffset;
6670 // Just to not break the postmortrem support with conditional offsets
6671 static const int kUniqueIdOffset = kFeedbackVectorOffset;
6672 static const int kLastPointerFieldOffset = kFeedbackVectorOffset;
6675 #if V8_HOST_ARCH_32_BIT
6677 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6678 static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
6679 static const int kExpectedNofPropertiesOffset =
6680 kFormalParameterCountOffset + kPointerSize;
6681 static const int kNumLiteralsOffset =
6682 kExpectedNofPropertiesOffset + kPointerSize;
6683 static const int kStartPositionAndTypeOffset =
6684 kNumLiteralsOffset + kPointerSize;
6685 static const int kEndPositionOffset =
6686 kStartPositionAndTypeOffset + kPointerSize;
6687 static const int kFunctionTokenPositionOffset =
6688 kEndPositionOffset + kPointerSize;
6689 static const int kCompilerHintsOffset =
6690 kFunctionTokenPositionOffset + kPointerSize;
6691 static const int kOptCountAndBailoutReasonOffset =
6692 kCompilerHintsOffset + kPointerSize;
6693 static const int kCountersOffset =
6694 kOptCountAndBailoutReasonOffset + kPointerSize;
6695 static const int kAstNodeCountOffset =
6696 kCountersOffset + kPointerSize;
6697 static const int kProfilerTicksOffset =
6698 kAstNodeCountOffset + kPointerSize;
6701 static const int kSize = kProfilerTicksOffset + kPointerSize;
6703 // The only reason to use smi fields instead of int fields
6704 // is to allow iteration without maps decoding during
6705 // garbage collections.
6706 // To avoid wasting space on 64-bit architectures we use
6707 // the following trick: we group integer fields into pairs
6708 // The least significant integer in each pair is shifted left by 1.
6709 // By doing this we guarantee that LSB of each kPointerSize aligned
6710 // word is not set and thus this word cannot be treated as pointer
6711 // to HeapObject during old space traversal.
6712 #if V8_TARGET_LITTLE_ENDIAN
6713 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6714 static const int kFormalParameterCountOffset =
6715 kLengthOffset + kIntSize;
6717 static const int kExpectedNofPropertiesOffset =
6718 kFormalParameterCountOffset + kIntSize;
6719 static const int kNumLiteralsOffset =
6720 kExpectedNofPropertiesOffset + kIntSize;
6722 static const int kEndPositionOffset =
6723 kNumLiteralsOffset + kIntSize;
6724 static const int kStartPositionAndTypeOffset =
6725 kEndPositionOffset + kIntSize;
6727 static const int kFunctionTokenPositionOffset =
6728 kStartPositionAndTypeOffset + kIntSize;
6729 static const int kCompilerHintsOffset =
6730 kFunctionTokenPositionOffset + kIntSize;
6732 static const int kOptCountAndBailoutReasonOffset =
6733 kCompilerHintsOffset + kIntSize;
6734 static const int kCountersOffset =
6735 kOptCountAndBailoutReasonOffset + kIntSize;
6737 static const int kAstNodeCountOffset =
6738 kCountersOffset + kIntSize;
6739 static const int kProfilerTicksOffset =
6740 kAstNodeCountOffset + kIntSize;
6743 static const int kSize = kProfilerTicksOffset + kIntSize;
6745 #elif V8_TARGET_BIG_ENDIAN
6746 static const int kFormalParameterCountOffset =
6747 kLastPointerFieldOffset + kPointerSize;
6748 static const int kLengthOffset = kFormalParameterCountOffset + kIntSize;
6750 static const int kNumLiteralsOffset = kLengthOffset + kIntSize;
6751 static const int kExpectedNofPropertiesOffset = kNumLiteralsOffset + kIntSize;
6753 static const int kStartPositionAndTypeOffset =
6754 kExpectedNofPropertiesOffset + kIntSize;
6755 static const int kEndPositionOffset = kStartPositionAndTypeOffset + kIntSize;
6757 static const int kCompilerHintsOffset = kEndPositionOffset + kIntSize;
6758 static const int kFunctionTokenPositionOffset =
6759 kCompilerHintsOffset + kIntSize;
6761 static const int kCountersOffset = kFunctionTokenPositionOffset + kIntSize;
6762 static const int kOptCountAndBailoutReasonOffset = kCountersOffset + kIntSize;
6764 static const int kProfilerTicksOffset =
6765 kOptCountAndBailoutReasonOffset + kIntSize;
6766 static const int kAstNodeCountOffset = kProfilerTicksOffset + kIntSize;
6769 static const int kSize = kAstNodeCountOffset + kIntSize;
6772 #error Unknown byte ordering
6773 #endif // Big endian
6777 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
6779 typedef FixedBodyDescriptor<kNameOffset,
6780 kLastPointerFieldOffset + kPointerSize,
6781 kSize> BodyDescriptor;
6783 // Bit positions in start_position_and_type.
6784 // The source code start position is in the 30 most significant bits of
6785 // the start_position_and_type field.
6786 static const int kIsExpressionBit = 0;
6787 static const int kIsTopLevelBit = 1;
6788 static const int kStartPositionShift = 2;
6789 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
6791 // Bit positions in compiler_hints.
6792 enum CompilerHints {
6793 kAllowLazyCompilation,
6794 kAllowLazyCompilationWithoutContext,
6795 kOptimizationDisabled,
6796 kStrictModeFunction,
6797 kStrongModeFunction,
6800 kHasDuplicateParameters,
6805 kNameShouldPrintAsAnonymous,
6812 kIsAccessorFunction,
6813 kIsDefaultConstructor,
6814 kIsSubclassConstructor,
6820 kCompilerHintsCount // Pseudo entry
6822 // Add hints for other modes when they're added.
6823 STATIC_ASSERT(LANGUAGE_END == 3);
6825 class FunctionKindBits : public BitField<FunctionKind, kIsArrow, 8> {};
6827 class DeoptCountBits : public BitField<int, 0, 4> {};
6828 class OptReenableTriesBits : public BitField<int, 4, 18> {};
6829 class ICAgeBits : public BitField<int, 22, 8> {};
6831 class OptCountBits : public BitField<int, 0, 22> {};
6832 class DisabledOptimizationReasonBits : public BitField<int, 22, 8> {};
6835 #if V8_HOST_ARCH_32_BIT
6836 // On 32 bit platforms, compiler hints is a smi.
6837 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
6838 static const int kCompilerHintsSize = kPointerSize;
6840 // On 64 bit platforms, compiler hints is not a smi, see comment above.
6841 static const int kCompilerHintsSmiTagSize = 0;
6842 static const int kCompilerHintsSize = kIntSize;
6845 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
6846 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
6849 // Constants for optimizing codegen for strict mode function and
6851 // Allows to use byte-width instructions.
6852 static const int kStrictModeBitWithinByte =
6853 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6854 static const int kStrongModeBitWithinByte =
6855 (kStrongModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6857 static const int kNativeBitWithinByte =
6858 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
6860 #if defined(V8_TARGET_LITTLE_ENDIAN)
6861 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6862 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6863 static const int kStrongModeByteOffset =
6864 kCompilerHintsOffset +
6865 (kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6866 static const int kNativeByteOffset = kCompilerHintsOffset +
6867 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
6868 #elif defined(V8_TARGET_BIG_ENDIAN)
6869 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6870 (kCompilerHintsSize - 1) -
6871 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6872 static const int kStrongModeByteOffset =
6873 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6874 ((kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6875 static const int kNativeByteOffset = kCompilerHintsOffset +
6876 (kCompilerHintsSize - 1) -
6877 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
6879 #error Unknown byte ordering
6883 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
6887 // Printing support.
6888 struct SourceCodeOf {
6889 explicit SourceCodeOf(SharedFunctionInfo* v, int max = -1)
6890 : value(v), max_length(max) {}
6891 const SharedFunctionInfo* value;
6896 std::ostream& operator<<(std::ostream& os, const SourceCodeOf& v);
6899 class JSGeneratorObject: public JSObject {
6901 // [function]: The function corresponding to this generator object.
6902 DECL_ACCESSORS(function, JSFunction)
6904 // [context]: The context of the suspended computation.
6905 DECL_ACCESSORS(context, Context)
6907 // [receiver]: The receiver of the suspended computation.
6908 DECL_ACCESSORS(receiver, Object)
6910 // [continuation]: Offset into code of continuation.
6912 // A positive offset indicates a suspended generator. The special
6913 // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
6914 // cannot be resumed.
6915 inline int continuation() const;
6916 inline void set_continuation(int continuation);
6917 inline bool is_closed();
6918 inline bool is_executing();
6919 inline bool is_suspended();
6921 // [operand_stack]: Saved operand stack.
6922 DECL_ACCESSORS(operand_stack, FixedArray)
6924 DECLARE_CAST(JSGeneratorObject)
6926 // Dispatched behavior.
6927 DECLARE_PRINTER(JSGeneratorObject)
6928 DECLARE_VERIFIER(JSGeneratorObject)
6930 // Magic sentinel values for the continuation.
6931 static const int kGeneratorExecuting = -1;
6932 static const int kGeneratorClosed = 0;
6934 // Layout description.
6935 static const int kFunctionOffset = JSObject::kHeaderSize;
6936 static const int kContextOffset = kFunctionOffset + kPointerSize;
6937 static const int kReceiverOffset = kContextOffset + kPointerSize;
6938 static const int kContinuationOffset = kReceiverOffset + kPointerSize;
6939 static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
6940 static const int kSize = kOperandStackOffset + kPointerSize;
6942 // Resume mode, for use by runtime functions.
6943 enum ResumeMode { NEXT, THROW };
6945 // Yielding from a generator returns an object with the following inobject
6946 // properties. See Context::iterator_result_map() for the map.
6947 static const int kResultValuePropertyIndex = 0;
6948 static const int kResultDonePropertyIndex = 1;
6949 static const int kResultPropertyCount = 2;
6951 static const int kResultValuePropertyOffset = JSObject::kHeaderSize;
6952 static const int kResultDonePropertyOffset =
6953 kResultValuePropertyOffset + kPointerSize;
6954 static const int kResultSize = kResultDonePropertyOffset + kPointerSize;
6957 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
6961 // Representation for module instance objects.
6962 class JSModule: public JSObject {
6964 // [context]: the context holding the module's locals, or undefined if none.
6965 DECL_ACCESSORS(context, Object)
6967 // [scope_info]: Scope info.
6968 DECL_ACCESSORS(scope_info, ScopeInfo)
6970 DECLARE_CAST(JSModule)
6972 // Dispatched behavior.
6973 DECLARE_PRINTER(JSModule)
6974 DECLARE_VERIFIER(JSModule)
6976 // Layout description.
6977 static const int kContextOffset = JSObject::kHeaderSize;
6978 static const int kScopeInfoOffset = kContextOffset + kPointerSize;
6979 static const int kSize = kScopeInfoOffset + kPointerSize;
6982 DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
6986 // JSFunction describes JavaScript functions.
6987 class JSFunction: public JSObject {
6989 // [prototype_or_initial_map]:
6990 DECL_ACCESSORS(prototype_or_initial_map, Object)
6992 // [shared]: The information about the function that
6993 // can be shared by instances.
6994 DECL_ACCESSORS(shared, SharedFunctionInfo)
6996 // [context]: The context for this function.
6997 inline Context* context();
6998 inline void set_context(Object* context);
6999 inline JSObject* global_proxy();
7001 // [code]: The generated code object for this function. Executed
7002 // when the function is invoked, e.g. foo() or new foo(). See
7003 // [[Call]] and [[Construct]] description in ECMA-262, section
7005 inline Code* code();
7006 inline void set_code(Code* code);
7007 inline void set_code_no_write_barrier(Code* code);
7008 inline void ReplaceCode(Code* code);
7010 // Tells whether this function is builtin.
7011 inline bool IsBuiltin();
7013 // Tells whether this function inlines the given shared function info.
7014 bool Inlines(SharedFunctionInfo* candidate);
7016 // Tells whether this function should be subject to debugging.
7017 inline bool IsSubjectToDebugging();
7019 // Tells whether or not the function needs arguments adaption.
7020 inline bool NeedsArgumentsAdaption();
7022 // Tells whether or not this function has been optimized.
7023 inline bool IsOptimized();
7025 // Mark this function for lazy recompilation. The function will be
7026 // recompiled the next time it is executed.
7027 void MarkForOptimization();
7028 void AttemptConcurrentOptimization();
7030 // Tells whether or not the function is already marked for lazy
7032 inline bool IsMarkedForOptimization();
7033 inline bool IsMarkedForConcurrentOptimization();
7035 // Tells whether or not the function is on the concurrent recompilation queue.
7036 inline bool IsInOptimizationQueue();
7038 // Inobject slack tracking is the way to reclaim unused inobject space.
7040 // The instance size is initially determined by adding some slack to
7041 // expected_nof_properties (to allow for a few extra properties added
7042 // after the constructor). There is no guarantee that the extra space
7043 // will not be wasted.
7045 // Here is the algorithm to reclaim the unused inobject space:
7046 // - Detect the first constructor call for this JSFunction.
7047 // When it happens enter the "in progress" state: initialize construction
7048 // counter in the initial_map.
7049 // - While the tracking is in progress create objects filled with
7050 // one_pointer_filler_map instead of undefined_value. This way they can be
7051 // resized quickly and safely.
7052 // - Once enough objects have been created compute the 'slack'
7053 // (traverse the map transition tree starting from the
7054 // initial_map and find the lowest value of unused_property_fields).
7055 // - Traverse the transition tree again and decrease the instance size
7056 // of every map. Existing objects will resize automatically (they are
7057 // filled with one_pointer_filler_map). All further allocations will
7058 // use the adjusted instance size.
7059 // - SharedFunctionInfo's expected_nof_properties left unmodified since
7060 // allocations made using different closures could actually create different
7061 // kind of objects (see prototype inheritance pattern).
7063 // Important: inobject slack tracking is not attempted during the snapshot
7066 // True if the initial_map is set and the object constructions countdown
7067 // counter is not zero.
7068 static const int kGenerousAllocationCount =
7069 Map::kSlackTrackingCounterStart - Map::kSlackTrackingCounterEnd + 1;
7070 inline bool IsInobjectSlackTrackingInProgress();
7072 // Starts the tracking.
7073 // Initializes object constructions countdown counter in the initial map.
7074 void StartInobjectSlackTracking();
7076 // Completes the tracking.
7077 void CompleteInobjectSlackTracking();
7079 // [literals_or_bindings]: Fixed array holding either
7080 // the materialized literals or the bindings of a bound function.
7082 // If the function contains object, regexp or array literals, the
7083 // literals array prefix contains the object, regexp, and array
7084 // function to be used when creating these literals. This is
7085 // necessary so that we do not dynamically lookup the object, regexp
7086 // or array functions. Performing a dynamic lookup, we might end up
7087 // using the functions from a new context that we should not have
7090 // On bound functions, the array is a (copy-on-write) fixed-array containing
7091 // the function that was bound, bound this-value and any bound
7092 // arguments. Bound functions never contain literals.
7093 DECL_ACCESSORS(literals_or_bindings, FixedArray)
7095 inline FixedArray* literals();
7096 inline void set_literals(FixedArray* literals);
7098 inline FixedArray* function_bindings();
7099 inline void set_function_bindings(FixedArray* bindings);
7101 // The initial map for an object created by this constructor.
7102 inline Map* initial_map();
7103 static void SetInitialMap(Handle<JSFunction> function, Handle<Map> map,
7104 Handle<Object> prototype);
7105 inline bool has_initial_map();
7106 static void EnsureHasInitialMap(Handle<JSFunction> function);
7108 // Get and set the prototype property on a JSFunction. If the
7109 // function has an initial map the prototype is set on the initial
7110 // map. Otherwise, the prototype is put in the initial map field
7111 // until an initial map is needed.
7112 inline bool has_prototype();
7113 inline bool has_instance_prototype();
7114 inline Object* prototype();
7115 inline Object* instance_prototype();
7116 static void SetPrototype(Handle<JSFunction> function,
7117 Handle<Object> value);
7118 static void SetInstancePrototype(Handle<JSFunction> function,
7119 Handle<Object> value);
7121 // Creates a new closure for the fucntion with the same bindings,
7122 // bound values, and prototype. An equivalent of spec operations
7123 // ``CloneMethod`` and ``CloneBoundFunction``.
7124 static Handle<JSFunction> CloneClosure(Handle<JSFunction> function);
7126 // After prototype is removed, it will not be created when accessed, and
7127 // [[Construct]] from this function will not be allowed.
7128 bool RemovePrototype();
7129 inline bool should_have_prototype();
7131 // Accessor for this function's initial map's [[class]]
7132 // property. This is primarily used by ECMA native functions. This
7133 // method sets the class_name field of this function's initial map
7134 // to a given value. It creates an initial map if this function does
7135 // not have one. Note that this method does not copy the initial map
7136 // if it has one already, but simply replaces it with the new value.
7137 // Instances created afterwards will have a map whose [[class]] is
7138 // set to 'value', but there is no guarantees on instances created
7140 void SetInstanceClassName(String* name);
7142 // Returns if this function has been compiled to native code yet.
7143 inline bool is_compiled();
7145 // Returns `false` if formal parameters include rest parameters, optional
7146 // parameters, or destructuring parameters.
7147 // TODO(caitp): make this a flag set during parsing
7148 inline bool has_simple_parameters();
7150 // [next_function_link]: Links functions into various lists, e.g. the list
7151 // of optimized functions hanging off the native_context. The CodeFlusher
7152 // uses this link to chain together flushing candidates. Treated weakly
7153 // by the garbage collector.
7154 DECL_ACCESSORS(next_function_link, Object)
7156 // Prints the name of the function using PrintF.
7157 void PrintName(FILE* out = stdout);
7159 DECLARE_CAST(JSFunction)
7161 // Iterates the objects, including code objects indirectly referenced
7162 // through pointers to the first instruction in the code object.
7163 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
7165 // Dispatched behavior.
7166 DECLARE_PRINTER(JSFunction)
7167 DECLARE_VERIFIER(JSFunction)
7169 // Returns the number of allocated literals.
7170 inline int NumberOfLiterals();
7172 // Used for flags such as --hydrogen-filter.
7173 bool PassesFilter(const char* raw_filter);
7175 // The function's name if it is configured, otherwise shared function info
7177 static Handle<String> GetDebugName(Handle<JSFunction> function);
7179 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
7180 // kSize) is weak and has special handling during garbage collection.
7181 static const int kCodeEntryOffset = JSObject::kHeaderSize;
7182 static const int kPrototypeOrInitialMapOffset =
7183 kCodeEntryOffset + kPointerSize;
7184 static const int kSharedFunctionInfoOffset =
7185 kPrototypeOrInitialMapOffset + kPointerSize;
7186 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
7187 static const int kLiteralsOffset = kContextOffset + kPointerSize;
7188 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
7189 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
7190 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
7192 // Layout of the bound-function binding array.
7193 static const int kBoundFunctionIndex = 0;
7194 static const int kBoundThisIndex = 1;
7195 static const int kBoundArgumentsStartIndex = 2;
7198 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7202 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7203 // and the prototype is hidden. JSGlobalProxy always delegates
7204 // property accesses to its prototype if the prototype is not null.
7206 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7208 // Accessing a JSGlobalProxy requires security check.
7210 class JSGlobalProxy : public JSObject {
7212 // [native_context]: the owner native context of this global proxy object.
7213 // It is null value if this object is not used by any context.
7214 DECL_ACCESSORS(native_context, Object)
7216 // [hash]: The hash code property (undefined if not initialized yet).
7217 DECL_ACCESSORS(hash, Object)
7219 DECLARE_CAST(JSGlobalProxy)
7221 inline bool IsDetachedFrom(GlobalObject* global) const;
7223 // Dispatched behavior.
7224 DECLARE_PRINTER(JSGlobalProxy)
7225 DECLARE_VERIFIER(JSGlobalProxy)
7227 // Layout description.
7228 static const int kNativeContextOffset = JSObject::kHeaderSize;
7229 static const int kHashOffset = kNativeContextOffset + kPointerSize;
7230 static const int kSize = kHashOffset + kPointerSize;
7233 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7237 // Common super class for JavaScript global objects and the special
7238 // builtins global objects.
7239 class GlobalObject: public JSObject {
7241 // [builtins]: the object holding the runtime routines written in JS.
7242 DECL_ACCESSORS(builtins, JSBuiltinsObject)
7244 // [native context]: the natives corresponding to this global object.
7245 DECL_ACCESSORS(native_context, Context)
7247 // [global proxy]: the global proxy object of the context
7248 DECL_ACCESSORS(global_proxy, JSObject)
7250 DECLARE_CAST(GlobalObject)
7252 static void InvalidatePropertyCell(Handle<GlobalObject> object,
7254 // Ensure that the global object has a cell for the given property name.
7255 static Handle<PropertyCell> EnsurePropertyCell(Handle<GlobalObject> global,
7258 // Layout description.
7259 static const int kBuiltinsOffset = JSObject::kHeaderSize;
7260 static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7261 static const int kGlobalProxyOffset = kNativeContextOffset + kPointerSize;
7262 static const int kHeaderSize = kGlobalProxyOffset + kPointerSize;
7265 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7269 // JavaScript global object.
7270 class JSGlobalObject: public GlobalObject {
7272 DECLARE_CAST(JSGlobalObject)
7274 inline bool IsDetached();
7276 // Dispatched behavior.
7277 DECLARE_PRINTER(JSGlobalObject)
7278 DECLARE_VERIFIER(JSGlobalObject)
7280 // Layout description.
7281 static const int kSize = GlobalObject::kHeaderSize;
7284 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7288 // Builtins global object which holds the runtime routines written in
7290 class JSBuiltinsObject: public GlobalObject {
7292 // Accessors for the runtime routines written in JavaScript.
7293 inline Object* javascript_builtin(Builtins::JavaScript id);
7294 inline void set_javascript_builtin(Builtins::JavaScript id, Object* value);
7296 DECLARE_CAST(JSBuiltinsObject)
7298 // Dispatched behavior.
7299 DECLARE_PRINTER(JSBuiltinsObject)
7300 DECLARE_VERIFIER(JSBuiltinsObject)
7302 // Layout description. The size of the builtins object includes
7303 // room for two pointers per runtime routine written in javascript
7304 // (function and code object).
7305 static const int kJSBuiltinsCount = Builtins::id_count;
7306 static const int kJSBuiltinsOffset = GlobalObject::kHeaderSize;
7307 static const int kSize =
7308 GlobalObject::kHeaderSize + (kJSBuiltinsCount * kPointerSize);
7310 static int OffsetOfFunctionWithId(Builtins::JavaScript id) {
7311 return kJSBuiltinsOffset + id * kPointerSize;
7315 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7319 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
7320 class JSValue: public JSObject {
7322 // [value]: the object being wrapped.
7323 DECL_ACCESSORS(value, Object)
7325 DECLARE_CAST(JSValue)
7327 // Dispatched behavior.
7328 DECLARE_PRINTER(JSValue)
7329 DECLARE_VERIFIER(JSValue)
7331 // Layout description.
7332 static const int kValueOffset = JSObject::kHeaderSize;
7333 static const int kSize = kValueOffset + kPointerSize;
7336 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
7342 // Representation for JS date objects.
7343 class JSDate: public JSObject {
7345 // If one component is NaN, all of them are, indicating a NaN time value.
7346 // [value]: the time value.
7347 DECL_ACCESSORS(value, Object)
7348 // [year]: caches year. Either undefined, smi, or NaN.
7349 DECL_ACCESSORS(year, Object)
7350 // [month]: caches month. Either undefined, smi, or NaN.
7351 DECL_ACCESSORS(month, Object)
7352 // [day]: caches day. Either undefined, smi, or NaN.
7353 DECL_ACCESSORS(day, Object)
7354 // [weekday]: caches day of week. Either undefined, smi, or NaN.
7355 DECL_ACCESSORS(weekday, Object)
7356 // [hour]: caches hours. Either undefined, smi, or NaN.
7357 DECL_ACCESSORS(hour, Object)
7358 // [min]: caches minutes. Either undefined, smi, or NaN.
7359 DECL_ACCESSORS(min, Object)
7360 // [sec]: caches seconds. Either undefined, smi, or NaN.
7361 DECL_ACCESSORS(sec, Object)
7362 // [cache stamp]: sample of the date cache stamp at the
7363 // moment when chached fields were cached.
7364 DECL_ACCESSORS(cache_stamp, Object)
7366 DECLARE_CAST(JSDate)
7368 // Returns the date field with the specified index.
7369 // See FieldIndex for the list of date fields.
7370 static Object* GetField(Object* date, Smi* index);
7372 void SetValue(Object* value, bool is_value_nan);
7375 // Dispatched behavior.
7376 DECLARE_PRINTER(JSDate)
7377 DECLARE_VERIFIER(JSDate)
7379 // The order is important. It must be kept in sync with date macros
7390 kFirstUncachedField,
7391 kMillisecond = kFirstUncachedField,
7395 kYearUTC = kFirstUTCField,
7408 // Layout description.
7409 static const int kValueOffset = JSObject::kHeaderSize;
7410 static const int kYearOffset = kValueOffset + kPointerSize;
7411 static const int kMonthOffset = kYearOffset + kPointerSize;
7412 static const int kDayOffset = kMonthOffset + kPointerSize;
7413 static const int kWeekdayOffset = kDayOffset + kPointerSize;
7414 static const int kHourOffset = kWeekdayOffset + kPointerSize;
7415 static const int kMinOffset = kHourOffset + kPointerSize;
7416 static const int kSecOffset = kMinOffset + kPointerSize;
7417 static const int kCacheStampOffset = kSecOffset + kPointerSize;
7418 static const int kSize = kCacheStampOffset + kPointerSize;
7421 inline Object* DoGetField(FieldIndex index);
7423 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
7425 // Computes and caches the cacheable fields of the date.
7426 inline void SetCachedFields(int64_t local_time_ms, DateCache* date_cache);
7429 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
7433 // Representation of message objects used for error reporting through
7434 // the API. The messages are formatted in JavaScript so this object is
7435 // a real JavaScript object. The information used for formatting the
7436 // error messages are not directly accessible from JavaScript to
7437 // prevent leaking information to user code called during error
7439 class JSMessageObject: public JSObject {
7441 // [type]: the type of error message.
7442 inline int type() const;
7443 inline void set_type(int value);
7445 // [arguments]: the arguments for formatting the error message.
7446 DECL_ACCESSORS(argument, Object)
7448 // [script]: the script from which the error message originated.
7449 DECL_ACCESSORS(script, Object)
7451 // [stack_frames]: an array of stack frames for this error object.
7452 DECL_ACCESSORS(stack_frames, Object)
7454 // [start_position]: the start position in the script for the error message.
7455 inline int start_position() const;
7456 inline void set_start_position(int value);
7458 // [end_position]: the end position in the script for the error message.
7459 inline int end_position() const;
7460 inline void set_end_position(int value);
7462 DECLARE_CAST(JSMessageObject)
7464 // Dispatched behavior.
7465 DECLARE_PRINTER(JSMessageObject)
7466 DECLARE_VERIFIER(JSMessageObject)
7468 // Layout description.
7469 static const int kTypeOffset = JSObject::kHeaderSize;
7470 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
7471 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
7472 static const int kStackFramesOffset = kScriptOffset + kPointerSize;
7473 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
7474 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
7475 static const int kSize = kEndPositionOffset + kPointerSize;
7477 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
7478 kStackFramesOffset + kPointerSize,
7479 kSize> BodyDescriptor;
7483 // Regular expressions
7484 // The regular expression holds a single reference to a FixedArray in
7485 // the kDataOffset field.
7486 // The FixedArray contains the following data:
7487 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
7488 // - reference to the original source string
7489 // - reference to the original flag string
7490 // If it is an atom regexp
7491 // - a reference to a literal string to search for
7492 // If it is an irregexp regexp:
7493 // - a reference to code for Latin1 inputs (bytecode or compiled), or a smi
7494 // used for tracking the last usage (used for code flushing).
7495 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
7496 // used for tracking the last usage (used for code flushing)..
7497 // - max number of registers used by irregexp implementations.
7498 // - number of capture registers (output values) of the regexp.
7499 class JSRegExp: public JSObject {
7502 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
7503 // ATOM: A simple string to match against using an indexOf operation.
7504 // IRREGEXP: Compiled with Irregexp.
7505 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
7506 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
7513 UNICODE_ESCAPES = 16
7518 explicit Flags(uint32_t value) : value_(value) { }
7519 bool is_global() { return (value_ & GLOBAL) != 0; }
7520 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
7521 bool is_multiline() { return (value_ & MULTILINE) != 0; }
7522 bool is_sticky() { return (value_ & STICKY) != 0; }
7523 bool is_unicode() { return (value_ & UNICODE_ESCAPES) != 0; }
7524 uint32_t value() { return value_; }
7529 DECL_ACCESSORS(data, Object)
7531 inline Type TypeTag();
7532 inline int CaptureCount();
7533 inline Flags GetFlags();
7534 inline String* Pattern();
7535 inline Object* DataAt(int index);
7536 // Set implementation data after the object has been prepared.
7537 inline void SetDataAt(int index, Object* value);
7539 static int code_index(bool is_latin1) {
7541 return kIrregexpLatin1CodeIndex;
7543 return kIrregexpUC16CodeIndex;
7547 static int saved_code_index(bool is_latin1) {
7549 return kIrregexpLatin1CodeSavedIndex;
7551 return kIrregexpUC16CodeSavedIndex;
7555 DECLARE_CAST(JSRegExp)
7557 // Dispatched behavior.
7558 DECLARE_VERIFIER(JSRegExp)
7560 static const int kDataOffset = JSObject::kHeaderSize;
7561 static const int kSize = kDataOffset + kPointerSize;
7563 // Indices in the data array.
7564 static const int kTagIndex = 0;
7565 static const int kSourceIndex = kTagIndex + 1;
7566 static const int kFlagsIndex = kSourceIndex + 1;
7567 static const int kDataIndex = kFlagsIndex + 1;
7568 // The data fields are used in different ways depending on the
7569 // value of the tag.
7570 // Atom regexps (literal strings).
7571 static const int kAtomPatternIndex = kDataIndex;
7573 static const int kAtomDataSize = kAtomPatternIndex + 1;
7575 // Irregexp compiled code or bytecode for Latin1. If compilation
7576 // fails, this fields hold an exception object that should be
7577 // thrown if the regexp is used again.
7578 static const int kIrregexpLatin1CodeIndex = kDataIndex;
7579 // Irregexp compiled code or bytecode for UC16. If compilation
7580 // fails, this fields hold an exception object that should be
7581 // thrown if the regexp is used again.
7582 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
7584 // Saved instance of Irregexp compiled code or bytecode for Latin1 that
7585 // is a potential candidate for flushing.
7586 static const int kIrregexpLatin1CodeSavedIndex = kDataIndex + 2;
7587 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
7588 // a potential candidate for flushing.
7589 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
7591 // Maximal number of registers used by either Latin1 or UC16.
7592 // Only used to check that there is enough stack space
7593 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
7594 // Number of captures in the compiled regexp.
7595 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
7597 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
7599 // Offsets directly into the data fixed array.
7600 static const int kDataTagOffset =
7601 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
7602 static const int kDataOneByteCodeOffset =
7603 FixedArray::kHeaderSize + kIrregexpLatin1CodeIndex * kPointerSize;
7604 static const int kDataUC16CodeOffset =
7605 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
7606 static const int kIrregexpCaptureCountOffset =
7607 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
7609 // In-object fields.
7610 static const int kSourceFieldIndex = 0;
7611 static const int kGlobalFieldIndex = 1;
7612 static const int kIgnoreCaseFieldIndex = 2;
7613 static const int kMultilineFieldIndex = 3;
7614 static const int kLastIndexFieldIndex = 4;
7615 static const int kInObjectFieldCount = 5;
7617 // The uninitialized value for a regexp code object.
7618 static const int kUninitializedValue = -1;
7620 // The compilation error value for the regexp code object. The real error
7621 // object is in the saved code field.
7622 static const int kCompilationErrorValue = -2;
7624 // When we store the sweep generation at which we moved the code from the
7625 // code index to the saved code index we mask it of to be in the [0:255]
7627 static const int kCodeAgeMask = 0xff;
7631 class CompilationCacheShape : public BaseShape<HashTableKey*> {
7633 static inline bool IsMatch(HashTableKey* key, Object* value) {
7634 return key->IsMatch(value);
7637 static inline uint32_t Hash(HashTableKey* key) {
7641 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7642 return key->HashForObject(object);
7645 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7647 static const int kPrefixSize = 0;
7648 static const int kEntrySize = 2;
7652 // This cache is used in two different variants. For regexp caching, it simply
7653 // maps identifying info of the regexp to the cached regexp object. Scripts and
7654 // eval code only gets cached after a second probe for the code object. To do
7655 // so, on first "put" only a hash identifying the source is entered into the
7656 // cache, mapping it to a lifetime count of the hash. On each call to Age all
7657 // such lifetimes get reduced, and removed once they reach zero. If a second put
7658 // is called while such a hash is live in the cache, the hash gets replaced by
7659 // an actual cache entry. Age also removes stale live entries from the cache.
7660 // Such entries are identified by SharedFunctionInfos pointing to either the
7661 // recompilation stub, or to "old" code. This avoids memory leaks due to
7662 // premature caching of scripts and eval strings that are never needed later.
7663 class CompilationCacheTable: public HashTable<CompilationCacheTable,
7664 CompilationCacheShape,
7667 // Find cached value for a string key, otherwise return null.
7668 Handle<Object> Lookup(
7669 Handle<String> src, Handle<Context> context, LanguageMode language_mode);
7670 Handle<Object> LookupEval(
7671 Handle<String> src, Handle<SharedFunctionInfo> shared,
7672 LanguageMode language_mode, int scope_position);
7673 Handle<Object> LookupRegExp(Handle<String> source, JSRegExp::Flags flags);
7674 static Handle<CompilationCacheTable> Put(
7675 Handle<CompilationCacheTable> cache, Handle<String> src,
7676 Handle<Context> context, LanguageMode language_mode,
7677 Handle<Object> value);
7678 static Handle<CompilationCacheTable> PutEval(
7679 Handle<CompilationCacheTable> cache, Handle<String> src,
7680 Handle<SharedFunctionInfo> context, Handle<SharedFunctionInfo> value,
7681 int scope_position);
7682 static Handle<CompilationCacheTable> PutRegExp(
7683 Handle<CompilationCacheTable> cache, Handle<String> src,
7684 JSRegExp::Flags flags, Handle<FixedArray> value);
7685 void Remove(Object* value);
7687 static const int kHashGenerations = 10;
7689 DECLARE_CAST(CompilationCacheTable)
7692 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
7696 class CodeCache: public Struct {
7698 DECL_ACCESSORS(default_cache, FixedArray)
7699 DECL_ACCESSORS(normal_type_cache, Object)
7701 // Add the code object to the cache.
7703 Handle<CodeCache> cache, Handle<Name> name, Handle<Code> code);
7705 // Lookup code object in the cache. Returns code object if found and undefined
7707 Object* Lookup(Name* name, Code::Flags flags);
7709 // Get the internal index of a code object in the cache. Returns -1 if the
7710 // code object is not in that cache. This index can be used to later call
7711 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
7713 int GetIndex(Object* name, Code* code);
7715 // Remove an object from the cache with the provided internal index.
7716 void RemoveByIndex(Object* name, Code* code, int index);
7718 DECLARE_CAST(CodeCache)
7720 // Dispatched behavior.
7721 DECLARE_PRINTER(CodeCache)
7722 DECLARE_VERIFIER(CodeCache)
7724 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
7725 static const int kNormalTypeCacheOffset =
7726 kDefaultCacheOffset + kPointerSize;
7727 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
7730 static void UpdateDefaultCache(
7731 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7732 static void UpdateNormalTypeCache(
7733 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7734 Object* LookupDefaultCache(Name* name, Code::Flags flags);
7735 Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
7737 // Code cache layout of the default cache. Elements are alternating name and
7738 // code objects for non normal load/store/call IC's.
7739 static const int kCodeCacheEntrySize = 2;
7740 static const int kCodeCacheEntryNameOffset = 0;
7741 static const int kCodeCacheEntryCodeOffset = 1;
7743 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
7747 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
7749 static inline bool IsMatch(HashTableKey* key, Object* value) {
7750 return key->IsMatch(value);
7753 static inline uint32_t Hash(HashTableKey* key) {
7757 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7758 return key->HashForObject(object);
7761 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7763 static const int kPrefixSize = 0;
7764 static const int kEntrySize = 2;
7768 class CodeCacheHashTable: public HashTable<CodeCacheHashTable,
7769 CodeCacheHashTableShape,
7772 Object* Lookup(Name* name, Code::Flags flags);
7773 static Handle<CodeCacheHashTable> Put(
7774 Handle<CodeCacheHashTable> table,
7778 int GetIndex(Name* name, Code::Flags flags);
7779 void RemoveByIndex(int index);
7781 DECLARE_CAST(CodeCacheHashTable)
7783 // Initial size of the fixed array backing the hash table.
7784 static const int kInitialSize = 64;
7787 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
7791 class PolymorphicCodeCache: public Struct {
7793 DECL_ACCESSORS(cache, Object)
7795 static void Update(Handle<PolymorphicCodeCache> cache,
7796 MapHandleList* maps,
7801 // Returns an undefined value if the entry is not found.
7802 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
7804 DECLARE_CAST(PolymorphicCodeCache)
7806 // Dispatched behavior.
7807 DECLARE_PRINTER(PolymorphicCodeCache)
7808 DECLARE_VERIFIER(PolymorphicCodeCache)
7810 static const int kCacheOffset = HeapObject::kHeaderSize;
7811 static const int kSize = kCacheOffset + kPointerSize;
7814 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
7818 class PolymorphicCodeCacheHashTable
7819 : public HashTable<PolymorphicCodeCacheHashTable,
7820 CodeCacheHashTableShape,
7823 Object* Lookup(MapHandleList* maps, int code_kind);
7825 static Handle<PolymorphicCodeCacheHashTable> Put(
7826 Handle<PolymorphicCodeCacheHashTable> hash_table,
7827 MapHandleList* maps,
7831 DECLARE_CAST(PolymorphicCodeCacheHashTable)
7833 static const int kInitialSize = 64;
7835 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
7839 class TypeFeedbackInfo: public Struct {
7841 inline int ic_total_count();
7842 inline void set_ic_total_count(int count);
7844 inline int ic_with_type_info_count();
7845 inline void change_ic_with_type_info_count(int delta);
7847 inline int ic_generic_count();
7848 inline void change_ic_generic_count(int delta);
7850 inline void initialize_storage();
7852 inline void change_own_type_change_checksum();
7853 inline int own_type_change_checksum();
7855 inline void set_inlined_type_change_checksum(int checksum);
7856 inline bool matches_inlined_type_change_checksum(int checksum);
7858 DECLARE_CAST(TypeFeedbackInfo)
7860 // Dispatched behavior.
7861 DECLARE_PRINTER(TypeFeedbackInfo)
7862 DECLARE_VERIFIER(TypeFeedbackInfo)
7864 static const int kStorage1Offset = HeapObject::kHeaderSize;
7865 static const int kStorage2Offset = kStorage1Offset + kPointerSize;
7866 static const int kStorage3Offset = kStorage2Offset + kPointerSize;
7867 static const int kSize = kStorage3Offset + kPointerSize;
7870 static const int kTypeChangeChecksumBits = 7;
7872 class ICTotalCountField: public BitField<int, 0,
7873 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7874 class OwnTypeChangeChecksum: public BitField<int,
7875 kSmiValueSize - kTypeChangeChecksumBits,
7876 kTypeChangeChecksumBits> {}; // NOLINT
7877 class ICsWithTypeInfoCountField: public BitField<int, 0,
7878 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7879 class InlinedTypeChangeChecksum: public BitField<int,
7880 kSmiValueSize - kTypeChangeChecksumBits,
7881 kTypeChangeChecksumBits> {}; // NOLINT
7883 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
7887 enum AllocationSiteMode {
7888 DONT_TRACK_ALLOCATION_SITE,
7889 TRACK_ALLOCATION_SITE,
7890 LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
7894 class AllocationSite: public Struct {
7896 static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
7897 static const double kPretenureRatio;
7898 static const int kPretenureMinimumCreated = 100;
7900 // Values for pretenure decision field.
7901 enum PretenureDecision {
7907 kLastPretenureDecisionValue = kZombie
7910 const char* PretenureDecisionName(PretenureDecision decision);
7912 DECL_ACCESSORS(transition_info, Object)
7913 // nested_site threads a list of sites that represent nested literals
7914 // walked in a particular order. So [[1, 2], 1, 2] will have one
7915 // nested_site, but [[1, 2], 3, [4]] will have a list of two.
7916 DECL_ACCESSORS(nested_site, Object)
7917 DECL_ACCESSORS(pretenure_data, Smi)
7918 DECL_ACCESSORS(pretenure_create_count, Smi)
7919 DECL_ACCESSORS(dependent_code, DependentCode)
7920 DECL_ACCESSORS(weak_next, Object)
7922 inline void Initialize();
7924 // This method is expensive, it should only be called for reporting.
7925 bool IsNestedSite();
7927 // transition_info bitfields, for constructed array transition info.
7928 class ElementsKindBits: public BitField<ElementsKind, 0, 15> {};
7929 class UnusedBits: public BitField<int, 15, 14> {};
7930 class DoNotInlineBit: public BitField<bool, 29, 1> {};
7932 // Bitfields for pretenure_data
7933 class MementoFoundCountBits: public BitField<int, 0, 26> {};
7934 class PretenureDecisionBits: public BitField<PretenureDecision, 26, 3> {};
7935 class DeoptDependentCodeBit: public BitField<bool, 29, 1> {};
7936 STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
7938 // Increments the mementos found counter and returns true when the first
7939 // memento was found for a given allocation site.
7940 inline bool IncrementMementoFoundCount();
7942 inline void IncrementMementoCreateCount();
7944 PretenureFlag GetPretenureMode();
7946 void ResetPretenureDecision();
7948 PretenureDecision pretenure_decision() {
7949 int value = pretenure_data()->value();
7950 return PretenureDecisionBits::decode(value);
7953 void set_pretenure_decision(PretenureDecision decision) {
7954 int value = pretenure_data()->value();
7956 Smi::FromInt(PretenureDecisionBits::update(value, decision)),
7957 SKIP_WRITE_BARRIER);
7960 bool deopt_dependent_code() {
7961 int value = pretenure_data()->value();
7962 return DeoptDependentCodeBit::decode(value);
7965 void set_deopt_dependent_code(bool deopt) {
7966 int value = pretenure_data()->value();
7968 Smi::FromInt(DeoptDependentCodeBit::update(value, deopt)),
7969 SKIP_WRITE_BARRIER);
7972 int memento_found_count() {
7973 int value = pretenure_data()->value();
7974 return MementoFoundCountBits::decode(value);
7977 inline void set_memento_found_count(int count);
7979 int memento_create_count() {
7980 return pretenure_create_count()->value();
7983 void set_memento_create_count(int count) {
7984 set_pretenure_create_count(Smi::FromInt(count), SKIP_WRITE_BARRIER);
7987 // The pretenuring decision is made during gc, and the zombie state allows
7988 // us to recognize when an allocation site is just being kept alive because
7989 // a later traversal of new space may discover AllocationMementos that point
7990 // to this AllocationSite.
7992 return pretenure_decision() == kZombie;
7995 bool IsMaybeTenure() {
7996 return pretenure_decision() == kMaybeTenure;
7999 inline void MarkZombie();
8001 inline bool MakePretenureDecision(PretenureDecision current_decision,
8003 bool maximum_size_scavenge);
8005 inline bool DigestPretenuringFeedback(bool maximum_size_scavenge);
8007 ElementsKind GetElementsKind() {
8008 DCHECK(!SitePointsToLiteral());
8009 int value = Smi::cast(transition_info())->value();
8010 return ElementsKindBits::decode(value);
8013 void SetElementsKind(ElementsKind kind) {
8014 int value = Smi::cast(transition_info())->value();
8015 set_transition_info(Smi::FromInt(ElementsKindBits::update(value, kind)),
8016 SKIP_WRITE_BARRIER);
8019 bool CanInlineCall() {
8020 int value = Smi::cast(transition_info())->value();
8021 return DoNotInlineBit::decode(value) == 0;
8024 void SetDoNotInlineCall() {
8025 int value = Smi::cast(transition_info())->value();
8026 set_transition_info(Smi::FromInt(DoNotInlineBit::update(value, true)),
8027 SKIP_WRITE_BARRIER);
8030 bool SitePointsToLiteral() {
8031 // If transition_info is a smi, then it represents an ElementsKind
8032 // for a constructed array. Otherwise, it must be a boilerplate
8033 // for an object or array literal.
8034 return transition_info()->IsJSArray() || transition_info()->IsJSObject();
8037 static void DigestTransitionFeedback(Handle<AllocationSite> site,
8038 ElementsKind to_kind);
8040 DECLARE_PRINTER(AllocationSite)
8041 DECLARE_VERIFIER(AllocationSite)
8043 DECLARE_CAST(AllocationSite)
8044 static inline AllocationSiteMode GetMode(
8045 ElementsKind boilerplate_elements_kind);
8046 static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
8047 static inline bool CanTrack(InstanceType type);
8049 static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
8050 static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
8051 static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
8052 static const int kPretenureCreateCountOffset =
8053 kPretenureDataOffset + kPointerSize;
8054 static const int kDependentCodeOffset =
8055 kPretenureCreateCountOffset + kPointerSize;
8056 static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
8057 static const int kSize = kWeakNextOffset + kPointerSize;
8059 // During mark compact we need to take special care for the dependent code
8061 static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
8062 static const int kPointerFieldsEndOffset = kWeakNextOffset;
8064 // For other visitors, use the fixed body descriptor below.
8065 typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
8066 kDependentCodeOffset + kPointerSize,
8067 kSize> BodyDescriptor;
8070 bool PretenuringDecisionMade() {
8071 return pretenure_decision() != kUndecided;
8074 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
8078 class AllocationMemento: public Struct {
8080 static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
8081 static const int kSize = kAllocationSiteOffset + kPointerSize;
8083 DECL_ACCESSORS(allocation_site, Object)
8086 return allocation_site()->IsAllocationSite() &&
8087 !AllocationSite::cast(allocation_site())->IsZombie();
8089 AllocationSite* GetAllocationSite() {
8091 return AllocationSite::cast(allocation_site());
8094 DECLARE_PRINTER(AllocationMemento)
8095 DECLARE_VERIFIER(AllocationMemento)
8097 DECLARE_CAST(AllocationMemento)
8100 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
8104 // Representation of a slow alias as part of a sloppy arguments objects.
8105 // For fast aliases (if HasSloppyArgumentsElements()):
8106 // - the parameter map contains an index into the context
8107 // - all attributes of the element have default values
8108 // For slow aliases (if HasDictionaryArgumentsElements()):
8109 // - the parameter map contains no fast alias mapping (i.e. the hole)
8110 // - this struct (in the slow backing store) contains an index into the context
8111 // - all attributes are available as part if the property details
8112 class AliasedArgumentsEntry: public Struct {
8114 inline int aliased_context_slot() const;
8115 inline void set_aliased_context_slot(int count);
8117 DECLARE_CAST(AliasedArgumentsEntry)
8119 // Dispatched behavior.
8120 DECLARE_PRINTER(AliasedArgumentsEntry)
8121 DECLARE_VERIFIER(AliasedArgumentsEntry)
8123 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
8124 static const int kSize = kAliasedContextSlot + kPointerSize;
8127 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
8131 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
8132 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
8135 class StringHasher {
8137 explicit inline StringHasher(int length, uint32_t seed);
8139 template <typename schar>
8140 static inline uint32_t HashSequentialString(const schar* chars,
8144 // Reads all the data, even for long strings and computes the utf16 length.
8145 static uint32_t ComputeUtf8Hash(Vector<const char> chars,
8147 int* utf16_length_out);
8149 // Calculated hash value for a string consisting of 1 to
8150 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
8151 // value is represented decimal value.
8152 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
8154 // No string is allowed to have a hash of zero. That value is reserved
8155 // for internal properties. If the hash calculation yields zero then we
8157 static const int kZeroHash = 27;
8159 // Reusable parts of the hashing algorithm.
8160 INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
8161 INLINE(static uint32_t GetHashCore(uint32_t running_hash));
8162 INLINE(static uint32_t ComputeRunningHash(uint32_t running_hash,
8163 const uc16* chars, int length));
8164 INLINE(static uint32_t ComputeRunningHashOneByte(uint32_t running_hash,
8169 // Returns the value to store in the hash field of a string with
8170 // the given length and contents.
8171 uint32_t GetHashField();
8172 // Returns true if the hash of this string can be computed without
8173 // looking at the contents.
8174 inline bool has_trivial_hash();
8175 // Adds a block of characters to the hash.
8176 template<typename Char>
8177 inline void AddCharacters(const Char* chars, int len);
8180 // Add a character to the hash.
8181 inline void AddCharacter(uint16_t c);
8182 // Update index. Returns true if string is still an index.
8183 inline bool UpdateIndex(uint16_t c);
8186 uint32_t raw_running_hash_;
8187 uint32_t array_index_;
8188 bool is_array_index_;
8189 bool is_first_char_;
8190 DISALLOW_COPY_AND_ASSIGN(StringHasher);
8194 class IteratingStringHasher : public StringHasher {
8196 static inline uint32_t Hash(String* string, uint32_t seed);
8197 inline void VisitOneByteString(const uint8_t* chars, int length);
8198 inline void VisitTwoByteString(const uint16_t* chars, int length);
8201 inline IteratingStringHasher(int len, uint32_t seed)
8202 : StringHasher(len, seed) {}
8203 void VisitConsString(ConsString* cons_string);
8204 DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher);
8208 // The characteristics of a string are stored in its map. Retrieving these
8209 // few bits of information is moderately expensive, involving two memory
8210 // loads where the second is dependent on the first. To improve efficiency
8211 // the shape of the string is given its own class so that it can be retrieved
8212 // once and used for several string operations. A StringShape is small enough
8213 // to be passed by value and is immutable, but be aware that flattening a
8214 // string can potentially alter its shape. Also be aware that a GC caused by
8215 // something else can alter the shape of a string due to ConsString
8216 // shortcutting. Keeping these restrictions in mind has proven to be error-
8217 // prone and so we no longer put StringShapes in variables unless there is a
8218 // concrete performance benefit at that particular point in the code.
8219 class StringShape BASE_EMBEDDED {
8221 inline explicit StringShape(const String* s);
8222 inline explicit StringShape(Map* s);
8223 inline explicit StringShape(InstanceType t);
8224 inline bool IsSequential();
8225 inline bool IsExternal();
8226 inline bool IsCons();
8227 inline bool IsSliced();
8228 inline bool IsIndirect();
8229 inline bool IsExternalOneByte();
8230 inline bool IsExternalTwoByte();
8231 inline bool IsSequentialOneByte();
8232 inline bool IsSequentialTwoByte();
8233 inline bool IsInternalized();
8234 inline StringRepresentationTag representation_tag();
8235 inline uint32_t encoding_tag();
8236 inline uint32_t full_representation_tag();
8237 inline uint32_t size_tag();
8239 inline uint32_t type() { return type_; }
8240 inline void invalidate() { valid_ = false; }
8241 inline bool valid() { return valid_; }
8243 inline void invalidate() { }
8249 inline void set_valid() { valid_ = true; }
8252 inline void set_valid() { }
8257 // The Name abstract class captures anything that can be used as a property
8258 // name, i.e., strings and symbols. All names store a hash value.
8259 class Name: public HeapObject {
8261 // Get and set the hash field of the name.
8262 inline uint32_t hash_field();
8263 inline void set_hash_field(uint32_t value);
8265 // Tells whether the hash code has been computed.
8266 inline bool HasHashCode();
8268 // Returns a hash value used for the property table
8269 inline uint32_t Hash();
8271 // Equality operations.
8272 inline bool Equals(Name* other);
8273 inline static bool Equals(Handle<Name> one, Handle<Name> two);
8276 inline bool AsArrayIndex(uint32_t* index);
8278 // If the name is private, it can only name own properties.
8279 inline bool IsPrivate();
8281 // If the name is a non-flat string, this method returns a flat version of the
8282 // string. Otherwise it'll just return the input.
8283 static inline Handle<Name> Flatten(Handle<Name> name,
8284 PretenureFlag pretenure = NOT_TENURED);
8288 DECLARE_PRINTER(Name)
8290 void NameShortPrint();
8291 int NameShortPrint(Vector<char> str);
8294 // Layout description.
8295 static const int kHashFieldSlot = HeapObject::kHeaderSize;
8296 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
8297 static const int kHashFieldOffset = kHashFieldSlot;
8299 static const int kHashFieldOffset = kHashFieldSlot + kIntSize;
8301 static const int kSize = kHashFieldSlot + kPointerSize;
8303 // Mask constant for checking if a name has a computed hash code
8304 // and if it is a string that is an array index. The least significant bit
8305 // indicates whether a hash code has been computed. If the hash code has
8306 // been computed the 2nd bit tells whether the string can be used as an
8308 static const int kHashNotComputedMask = 1;
8309 static const int kIsNotArrayIndexMask = 1 << 1;
8310 static const int kNofHashBitFields = 2;
8312 // Shift constant retrieving hash code from hash field.
8313 static const int kHashShift = kNofHashBitFields;
8315 // Only these bits are relevant in the hash, since the top two are shifted
8317 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8319 // Array index strings this short can keep their index in the hash field.
8320 static const int kMaxCachedArrayIndexLength = 7;
8322 // For strings which are array indexes the hash value has the string length
8323 // mixed into the hash, mainly to avoid a hash value of zero which would be
8324 // the case for the string '0'. 24 bits are used for the array index value.
8325 static const int kArrayIndexValueBits = 24;
8326 static const int kArrayIndexLengthBits =
8327 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8329 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8331 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8332 kArrayIndexValueBits> {}; // NOLINT
8333 class ArrayIndexLengthBits : public BitField<unsigned int,
8334 kNofHashBitFields + kArrayIndexValueBits,
8335 kArrayIndexLengthBits> {}; // NOLINT
8337 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8338 // could use a mask to test if the length of string is less than or equal to
8339 // kMaxCachedArrayIndexLength.
8340 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8342 static const unsigned int kContainsCachedArrayIndexMask =
8343 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8344 << ArrayIndexLengthBits::kShift) |
8345 kIsNotArrayIndexMask;
8347 // Value of empty hash field indicating that the hash is not computed.
8348 static const int kEmptyHashField =
8349 kIsNotArrayIndexMask | kHashNotComputedMask;
8352 static inline bool IsHashFieldComputed(uint32_t field);
8355 DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8360 class Symbol: public Name {
8362 // [name]: The print name of a symbol, or undefined if none.
8363 DECL_ACCESSORS(name, Object)
8365 DECL_ACCESSORS(flags, Smi)
8367 // [is_private]: Whether this is a private symbol. Private symbols can only
8368 // be used to designate own properties of objects.
8369 DECL_BOOLEAN_ACCESSORS(is_private)
8371 DECLARE_CAST(Symbol)
8373 // Dispatched behavior.
8374 DECLARE_PRINTER(Symbol)
8375 DECLARE_VERIFIER(Symbol)
8377 // Layout description.
8378 static const int kNameOffset = Name::kSize;
8379 static const int kFlagsOffset = kNameOffset + kPointerSize;
8380 static const int kSize = kFlagsOffset + kPointerSize;
8382 typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
8384 void SymbolShortPrint(std::ostream& os);
8387 static const int kPrivateBit = 0;
8389 const char* PrivateSymbolToName() const;
8392 friend class Name; // For PrivateSymbolToName.
8395 DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
8401 // The String abstract class captures JavaScript string values:
8404 // 4.3.16 String Value
8405 // A string value is a member of the type String and is a finite
8406 // ordered sequence of zero or more 16-bit unsigned integer values.
8408 // All string values have a length field.
8409 class String: public Name {
8411 enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
8413 // Array index strings this short can keep their index in the hash field.
8414 static const int kMaxCachedArrayIndexLength = 7;
8416 // For strings which are array indexes the hash value has the string length
8417 // mixed into the hash, mainly to avoid a hash value of zero which would be
8418 // the case for the string '0'. 24 bits are used for the array index value.
8419 static const int kArrayIndexValueBits = 24;
8420 static const int kArrayIndexLengthBits =
8421 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8423 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8425 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8426 kArrayIndexValueBits> {}; // NOLINT
8427 class ArrayIndexLengthBits : public BitField<unsigned int,
8428 kNofHashBitFields + kArrayIndexValueBits,
8429 kArrayIndexLengthBits> {}; // NOLINT
8431 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8432 // could use a mask to test if the length of string is less than or equal to
8433 // kMaxCachedArrayIndexLength.
8434 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8436 static const unsigned int kContainsCachedArrayIndexMask =
8437 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8438 << ArrayIndexLengthBits::kShift) |
8439 kIsNotArrayIndexMask;
8441 class SubStringRange {
8443 explicit SubStringRange(String* string, int first = 0, int length = -1)
8446 length_(length == -1 ? string->length() : length) {}
8448 inline iterator begin();
8449 inline iterator end();
8457 // Representation of the flat content of a String.
8458 // A non-flat string doesn't have flat content.
8459 // A flat string has content that's encoded as a sequence of either
8460 // one-byte chars or two-byte UC16.
8461 // Returned by String::GetFlatContent().
8464 // Returns true if the string is flat and this structure contains content.
8465 bool IsFlat() { return state_ != NON_FLAT; }
8466 // Returns true if the structure contains one-byte content.
8467 bool IsOneByte() { return state_ == ONE_BYTE; }
8468 // Returns true if the structure contains two-byte content.
8469 bool IsTwoByte() { return state_ == TWO_BYTE; }
8471 // Return the one byte content of the string. Only use if IsOneByte()
8473 Vector<const uint8_t> ToOneByteVector() {
8474 DCHECK_EQ(ONE_BYTE, state_);
8475 return Vector<const uint8_t>(onebyte_start, length_);
8477 // Return the two-byte content of the string. Only use if IsTwoByte()
8479 Vector<const uc16> ToUC16Vector() {
8480 DCHECK_EQ(TWO_BYTE, state_);
8481 return Vector<const uc16>(twobyte_start, length_);
8485 DCHECK(i < length_);
8486 DCHECK(state_ != NON_FLAT);
8487 if (state_ == ONE_BYTE) return onebyte_start[i];
8488 return twobyte_start[i];
8491 bool UsesSameString(const FlatContent& other) const {
8492 return onebyte_start == other.onebyte_start;
8496 enum State { NON_FLAT, ONE_BYTE, TWO_BYTE };
8498 // Constructors only used by String::GetFlatContent().
8499 explicit FlatContent(const uint8_t* start, int length)
8500 : onebyte_start(start), length_(length), state_(ONE_BYTE) {}
8501 explicit FlatContent(const uc16* start, int length)
8502 : twobyte_start(start), length_(length), state_(TWO_BYTE) { }
8503 FlatContent() : onebyte_start(NULL), length_(0), state_(NON_FLAT) { }
8506 const uint8_t* onebyte_start;
8507 const uc16* twobyte_start;
8512 friend class String;
8513 friend class IterableSubString;
8516 template <typename Char>
8517 INLINE(Vector<const Char> GetCharVector());
8519 // Get and set the length of the string.
8520 inline int length() const;
8521 inline void set_length(int value);
8523 // Get and set the length of the string using acquire loads and release
8525 inline int synchronized_length() const;
8526 inline void synchronized_set_length(int value);
8528 // Returns whether this string has only one-byte chars, i.e. all of them can
8529 // be one-byte encoded. This might be the case even if the string is
8530 // two-byte. Such strings may appear when the embedder prefers
8531 // two-byte external representations even for one-byte data.
8532 inline bool IsOneByteRepresentation() const;
8533 inline bool IsTwoByteRepresentation() const;
8535 // Cons and slices have an encoding flag that may not represent the actual
8536 // encoding of the underlying string. This is taken into account here.
8537 // Requires: this->IsFlat()
8538 inline bool IsOneByteRepresentationUnderneath();
8539 inline bool IsTwoByteRepresentationUnderneath();
8541 // NOTE: this should be considered only a hint. False negatives are
8543 inline bool HasOnlyOneByteChars();
8545 // Get and set individual two byte chars in the string.
8546 inline void Set(int index, uint16_t value);
8547 // Get individual two byte char in the string. Repeated calls
8548 // to this method are not efficient unless the string is flat.
8549 INLINE(uint16_t Get(int index));
8551 // Flattens the string. Checks first inline to see if it is
8552 // necessary. Does nothing if the string is not a cons string.
8553 // Flattening allocates a sequential string with the same data as
8554 // the given string and mutates the cons string to a degenerate
8555 // form, where the first component is the new sequential string and
8556 // the second component is the empty string. If allocation fails,
8557 // this function returns a failure. If flattening succeeds, this
8558 // function returns the sequential string that is now the first
8559 // component of the cons string.
8561 // Degenerate cons strings are handled specially by the garbage
8562 // collector (see IsShortcutCandidate).
8564 static inline Handle<String> Flatten(Handle<String> string,
8565 PretenureFlag pretenure = NOT_TENURED);
8567 // Tries to return the content of a flat string as a structure holding either
8568 // a flat vector of char or of uc16.
8569 // If the string isn't flat, and therefore doesn't have flat content, the
8570 // returned structure will report so, and can't provide a vector of either
8572 FlatContent GetFlatContent();
8574 // Returns the parent of a sliced string or first part of a flat cons string.
8575 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
8576 inline String* GetUnderlying();
8578 // String equality operations.
8579 inline bool Equals(String* other);
8580 inline static bool Equals(Handle<String> one, Handle<String> two);
8581 bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
8582 bool IsOneByteEqualTo(Vector<const uint8_t> str);
8583 bool IsTwoByteEqualTo(Vector<const uc16> str);
8585 // Return a UTF8 representation of the string. The string is null
8586 // terminated but may optionally contain nulls. Length is returned
8587 // in length_output if length_output is not a null pointer The string
8588 // should be nearly flat, otherwise the performance of this method may
8589 // be very slow (quadratic in the length). Setting robustness_flag to
8590 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8591 // handles unexpected data without causing assert failures and it does not
8592 // do any heap allocations. This is useful when printing stack traces.
8593 base::SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
8594 RobustnessFlag robustness_flag,
8595 int offset, int length,
8596 int* length_output = 0);
8597 base::SmartArrayPointer<char> ToCString(
8598 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
8599 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
8600 int* length_output = 0);
8602 // Return a 16 bit Unicode representation of the string.
8603 // The string should be nearly flat, otherwise the performance of
8604 // of this method may be very bad. Setting robustness_flag to
8605 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8606 // handles unexpected data without causing assert failures and it does not
8607 // do any heap allocations. This is useful when printing stack traces.
8608 base::SmartArrayPointer<uc16> ToWideCString(
8609 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
8611 bool ComputeArrayIndex(uint32_t* index);
8614 bool MakeExternal(v8::String::ExternalStringResource* resource);
8615 bool MakeExternal(v8::String::ExternalOneByteStringResource* resource);
8618 inline bool AsArrayIndex(uint32_t* index);
8620 DECLARE_CAST(String)
8622 void PrintOn(FILE* out);
8624 // For use during stack traces. Performs rudimentary sanity check.
8627 // Dispatched behavior.
8628 void StringShortPrint(StringStream* accumulator);
8629 void PrintUC16(std::ostream& os, int start = 0, int end = -1); // NOLINT
8630 #if defined(DEBUG) || defined(OBJECT_PRINT)
8631 char* ToAsciiArray();
8633 DECLARE_PRINTER(String)
8634 DECLARE_VERIFIER(String)
8636 inline bool IsFlat();
8638 // Layout description.
8639 static const int kLengthOffset = Name::kSize;
8640 static const int kSize = kLengthOffset + kPointerSize;
8642 // Maximum number of characters to consider when trying to convert a string
8643 // value into an array index.
8644 static const int kMaxArrayIndexSize = 10;
8645 STATIC_ASSERT(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
8648 static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
8649 static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
8650 static const int kMaxUtf16CodeUnit = 0xffff;
8651 static const uint32_t kMaxUtf16CodeUnitU = kMaxUtf16CodeUnit;
8653 // Value of hash field containing computed hash equal to zero.
8654 static const int kEmptyStringHash = kIsNotArrayIndexMask;
8656 // Maximal string length.
8657 static const int kMaxLength = (1 << 28) - 16;
8659 // Max length for computing hash. For strings longer than this limit the
8660 // string length is used as the hash value.
8661 static const int kMaxHashCalcLength = 16383;
8663 // Limit for truncation in short printing.
8664 static const int kMaxShortPrintLength = 1024;
8666 // Support for regular expressions.
8667 const uc16* GetTwoByteData(unsigned start);
8669 // Helper function for flattening strings.
8670 template <typename sinkchar>
8671 static void WriteToFlat(String* source,
8676 // The return value may point to the first aligned word containing the first
8677 // non-one-byte character, rather than directly to the non-one-byte character.
8678 // If the return value is >= the passed length, the entire string was
8680 static inline int NonAsciiStart(const char* chars, int length) {
8681 const char* start = chars;
8682 const char* limit = chars + length;
8684 if (length >= kIntptrSize) {
8685 // Check unaligned bytes.
8686 while (!IsAligned(reinterpret_cast<intptr_t>(chars), sizeof(uintptr_t))) {
8687 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8688 return static_cast<int>(chars - start);
8692 // Check aligned words.
8693 DCHECK(unibrow::Utf8::kMaxOneByteChar == 0x7F);
8694 const uintptr_t non_one_byte_mask = kUintptrAllBitsSet / 0xFF * 0x80;
8695 while (chars + sizeof(uintptr_t) <= limit) {
8696 if (*reinterpret_cast<const uintptr_t*>(chars) & non_one_byte_mask) {
8697 return static_cast<int>(chars - start);
8699 chars += sizeof(uintptr_t);
8702 // Check remaining unaligned bytes.
8703 while (chars < limit) {
8704 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8705 return static_cast<int>(chars - start);
8710 return static_cast<int>(chars - start);
8713 static inline bool IsAscii(const char* chars, int length) {
8714 return NonAsciiStart(chars, length) >= length;
8717 static inline bool IsAscii(const uint8_t* chars, int length) {
8719 NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
8722 static inline int NonOneByteStart(const uc16* chars, int length) {
8723 const uc16* limit = chars + length;
8724 const uc16* start = chars;
8725 while (chars < limit) {
8726 if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
8729 return static_cast<int>(chars - start);
8732 static inline bool IsOneByte(const uc16* chars, int length) {
8733 return NonOneByteStart(chars, length) >= length;
8736 template<class Visitor>
8737 static inline ConsString* VisitFlat(Visitor* visitor,
8741 static Handle<FixedArray> CalculateLineEnds(Handle<String> string,
8742 bool include_ending_line);
8744 // Use the hash field to forward to the canonical internalized string
8745 // when deserializing an internalized string.
8746 inline void SetForwardedInternalizedString(String* string);
8747 inline String* GetForwardedInternalizedString();
8751 friend class StringTableInsertionKey;
8753 static Handle<String> SlowFlatten(Handle<ConsString> cons,
8754 PretenureFlag tenure);
8756 // Slow case of String::Equals. This implementation works on any strings
8757 // but it is most efficient on strings that are almost flat.
8758 bool SlowEquals(String* other);
8760 static bool SlowEquals(Handle<String> one, Handle<String> two);
8762 // Slow case of AsArrayIndex.
8763 bool SlowAsArrayIndex(uint32_t* index);
8765 // Compute and set the hash code.
8766 uint32_t ComputeAndSetHash();
8768 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
8772 // The SeqString abstract class captures sequential string values.
8773 class SeqString: public String {
8775 DECLARE_CAST(SeqString)
8777 // Layout description.
8778 static const int kHeaderSize = String::kSize;
8780 // Truncate the string in-place if possible and return the result.
8781 // In case of new_length == 0, the empty string is returned without
8782 // truncating the original string.
8783 MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
8786 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
8790 // The OneByteString class captures sequential one-byte string objects.
8791 // Each character in the OneByteString is an one-byte character.
8792 class SeqOneByteString: public SeqString {
8794 static const bool kHasOneByteEncoding = true;
8796 // Dispatched behavior.
8797 inline uint16_t SeqOneByteStringGet(int index);
8798 inline void SeqOneByteStringSet(int index, uint16_t value);
8800 // Get the address of the characters in this string.
8801 inline Address GetCharsAddress();
8803 inline uint8_t* GetChars();
8805 DECLARE_CAST(SeqOneByteString)
8807 // Garbage collection support. This method is called by the
8808 // garbage collector to compute the actual size of an OneByteString
8810 inline int SeqOneByteStringSize(InstanceType instance_type);
8812 // Computes the size for an OneByteString instance of a given length.
8813 static int SizeFor(int length) {
8814 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
8817 // Maximal memory usage for a single sequential one-byte string.
8818 static const int kMaxSize = 512 * MB - 1;
8819 STATIC_ASSERT((kMaxSize - kHeaderSize) >= String::kMaxLength);
8822 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
8826 // The TwoByteString class captures sequential unicode string objects.
8827 // Each character in the TwoByteString is a two-byte uint16_t.
8828 class SeqTwoByteString: public SeqString {
8830 static const bool kHasOneByteEncoding = false;
8832 // Dispatched behavior.
8833 inline uint16_t SeqTwoByteStringGet(int index);
8834 inline void SeqTwoByteStringSet(int index, uint16_t value);
8836 // Get the address of the characters in this string.
8837 inline Address GetCharsAddress();
8839 inline uc16* GetChars();
8842 const uint16_t* SeqTwoByteStringGetData(unsigned start);
8844 DECLARE_CAST(SeqTwoByteString)
8846 // Garbage collection support. This method is called by the
8847 // garbage collector to compute the actual size of a TwoByteString
8849 inline int SeqTwoByteStringSize(InstanceType instance_type);
8851 // Computes the size for a TwoByteString instance of a given length.
8852 static int SizeFor(int length) {
8853 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
8856 // Maximal memory usage for a single sequential two-byte string.
8857 static const int kMaxSize = 512 * MB - 1;
8858 STATIC_ASSERT(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
8859 String::kMaxLength);
8862 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
8866 // The ConsString class describes string values built by using the
8867 // addition operator on strings. A ConsString is a pair where the
8868 // first and second components are pointers to other string values.
8869 // One or both components of a ConsString can be pointers to other
8870 // ConsStrings, creating a binary tree of ConsStrings where the leaves
8871 // are non-ConsString string values. The string value represented by
8872 // a ConsString can be obtained by concatenating the leaf string
8873 // values in a left-to-right depth-first traversal of the tree.
8874 class ConsString: public String {
8876 // First string of the cons cell.
8877 inline String* first();
8878 // Doesn't check that the result is a string, even in debug mode. This is
8879 // useful during GC where the mark bits confuse the checks.
8880 inline Object* unchecked_first();
8881 inline void set_first(String* first,
8882 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8884 // Second string of the cons cell.
8885 inline String* second();
8886 // Doesn't check that the result is a string, even in debug mode. This is
8887 // useful during GC where the mark bits confuse the checks.
8888 inline Object* unchecked_second();
8889 inline void set_second(String* second,
8890 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8892 // Dispatched behavior.
8893 uint16_t ConsStringGet(int index);
8895 DECLARE_CAST(ConsString)
8897 // Layout description.
8898 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
8899 static const int kSecondOffset = kFirstOffset + kPointerSize;
8900 static const int kSize = kSecondOffset + kPointerSize;
8902 // Minimum length for a cons string.
8903 static const int kMinLength = 13;
8905 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
8908 DECLARE_VERIFIER(ConsString)
8911 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
8915 // The Sliced String class describes strings that are substrings of another
8916 // sequential string. The motivation is to save time and memory when creating
8917 // a substring. A Sliced String is described as a pointer to the parent,
8918 // the offset from the start of the parent string and the length. Using
8919 // a Sliced String therefore requires unpacking of the parent string and
8920 // adding the offset to the start address. A substring of a Sliced String
8921 // are not nested since the double indirection is simplified when creating
8922 // such a substring.
8923 // Currently missing features are:
8924 // - handling externalized parent strings
8925 // - external strings as parent
8926 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
8927 class SlicedString: public String {
8929 inline String* parent();
8930 inline void set_parent(String* parent,
8931 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8932 inline int offset() const;
8933 inline void set_offset(int offset);
8935 // Dispatched behavior.
8936 uint16_t SlicedStringGet(int index);
8938 DECLARE_CAST(SlicedString)
8940 // Layout description.
8941 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
8942 static const int kOffsetOffset = kParentOffset + kPointerSize;
8943 static const int kSize = kOffsetOffset + kPointerSize;
8945 // Minimum length for a sliced string.
8946 static const int kMinLength = 13;
8948 typedef FixedBodyDescriptor<kParentOffset,
8949 kOffsetOffset + kPointerSize, kSize>
8952 DECLARE_VERIFIER(SlicedString)
8955 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
8959 // The ExternalString class describes string values that are backed by
8960 // a string resource that lies outside the V8 heap. ExternalStrings
8961 // consist of the length field common to all strings, a pointer to the
8962 // external resource. It is important to ensure (externally) that the
8963 // resource is not deallocated while the ExternalString is live in the
8966 // The API expects that all ExternalStrings are created through the
8967 // API. Therefore, ExternalStrings should not be used internally.
8968 class ExternalString: public String {
8970 DECLARE_CAST(ExternalString)
8972 // Layout description.
8973 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
8974 static const int kShortSize = kResourceOffset + kPointerSize;
8975 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
8976 static const int kSize = kResourceDataOffset + kPointerSize;
8978 static const int kMaxShortLength =
8979 (kShortSize - SeqString::kHeaderSize) / kCharSize;
8981 // Return whether external string is short (data pointer is not cached).
8982 inline bool is_short();
8984 STATIC_ASSERT(kResourceOffset == Internals::kStringResourceOffset);
8987 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
8991 // The ExternalOneByteString class is an external string backed by an
8993 class ExternalOneByteString : public ExternalString {
8995 static const bool kHasOneByteEncoding = true;
8997 typedef v8::String::ExternalOneByteStringResource Resource;
8999 // The underlying resource.
9000 inline const Resource* resource();
9001 inline void set_resource(const Resource* buffer);
9003 // Update the pointer cache to the external character array.
9004 // The cached pointer is always valid, as the external character array does =
9005 // not move during lifetime. Deserialization is the only exception, after
9006 // which the pointer cache has to be refreshed.
9007 inline void update_data_cache();
9009 inline const uint8_t* GetChars();
9011 // Dispatched behavior.
9012 inline uint16_t ExternalOneByteStringGet(int index);
9014 DECLARE_CAST(ExternalOneByteString)
9016 // Garbage collection support.
9017 inline void ExternalOneByteStringIterateBody(ObjectVisitor* v);
9019 template <typename StaticVisitor>
9020 inline void ExternalOneByteStringIterateBody();
9023 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalOneByteString);
9027 // The ExternalTwoByteString class is an external string backed by a UTF-16
9029 class ExternalTwoByteString: public ExternalString {
9031 static const bool kHasOneByteEncoding = false;
9033 typedef v8::String::ExternalStringResource Resource;
9035 // The underlying string resource.
9036 inline const Resource* resource();
9037 inline void set_resource(const Resource* buffer);
9039 // Update the pointer cache to the external character array.
9040 // The cached pointer is always valid, as the external character array does =
9041 // not move during lifetime. Deserialization is the only exception, after
9042 // which the pointer cache has to be refreshed.
9043 inline void update_data_cache();
9045 inline const uint16_t* GetChars();
9047 // Dispatched behavior.
9048 inline uint16_t ExternalTwoByteStringGet(int index);
9051 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
9053 DECLARE_CAST(ExternalTwoByteString)
9055 // Garbage collection support.
9056 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
9058 template<typename StaticVisitor>
9059 inline void ExternalTwoByteStringIterateBody();
9062 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
9066 // Utility superclass for stack-allocated objects that must be updated
9067 // on gc. It provides two ways for the gc to update instances, either
9068 // iterating or updating after gc.
9069 class Relocatable BASE_EMBEDDED {
9071 explicit inline Relocatable(Isolate* isolate);
9072 inline virtual ~Relocatable();
9073 virtual void IterateInstance(ObjectVisitor* v) { }
9074 virtual void PostGarbageCollection() { }
9076 static void PostGarbageCollectionProcessing(Isolate* isolate);
9077 static int ArchiveSpacePerThread();
9078 static char* ArchiveState(Isolate* isolate, char* to);
9079 static char* RestoreState(Isolate* isolate, char* from);
9080 static void Iterate(Isolate* isolate, ObjectVisitor* v);
9081 static void Iterate(ObjectVisitor* v, Relocatable* top);
9082 static char* Iterate(ObjectVisitor* v, char* t);
9090 // A flat string reader provides random access to the contents of a
9091 // string independent of the character width of the string. The handle
9092 // must be valid as long as the reader is being used.
9093 class FlatStringReader : public Relocatable {
9095 FlatStringReader(Isolate* isolate, Handle<String> str);
9096 FlatStringReader(Isolate* isolate, Vector<const char> input);
9097 void PostGarbageCollection();
9098 inline uc32 Get(int index);
9099 template <typename Char>
9100 inline Char Get(int index);
9101 int length() { return length_; }
9110 // This maintains an off-stack representation of the stack frames required
9111 // to traverse a ConsString, allowing an entirely iterative and restartable
9112 // traversal of the entire string
9113 class ConsStringIterator {
9115 inline ConsStringIterator() {}
9116 inline explicit ConsStringIterator(ConsString* cons_string, int offset = 0) {
9117 Reset(cons_string, offset);
9119 inline void Reset(ConsString* cons_string, int offset = 0) {
9121 // Next will always return NULL.
9122 if (cons_string == NULL) return;
9123 Initialize(cons_string, offset);
9125 // Returns NULL when complete.
9126 inline String* Next(int* offset_out) {
9128 if (depth_ == 0) return NULL;
9129 return Continue(offset_out);
9133 static const int kStackSize = 32;
9134 // Use a mask instead of doing modulo operations for stack wrapping.
9135 static const int kDepthMask = kStackSize-1;
9136 STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
9137 static inline int OffsetForDepth(int depth);
9139 inline void PushLeft(ConsString* string);
9140 inline void PushRight(ConsString* string);
9141 inline void AdjustMaximumDepth();
9143 inline bool StackBlown() { return maximum_depth_ - depth_ == kStackSize; }
9144 void Initialize(ConsString* cons_string, int offset);
9145 String* Continue(int* offset_out);
9146 String* NextLeaf(bool* blew_stack);
9147 String* Search(int* offset_out);
9149 // Stack must always contain only frames for which right traversal
9150 // has not yet been performed.
9151 ConsString* frames_[kStackSize];
9156 DISALLOW_COPY_AND_ASSIGN(ConsStringIterator);
9160 class StringCharacterStream {
9162 inline StringCharacterStream(String* string,
9164 inline uint16_t GetNext();
9165 inline bool HasMore();
9166 inline void Reset(String* string, int offset = 0);
9167 inline void VisitOneByteString(const uint8_t* chars, int length);
9168 inline void VisitTwoByteString(const uint16_t* chars, int length);
9171 ConsStringIterator iter_;
9174 const uint8_t* buffer8_;
9175 const uint16_t* buffer16_;
9177 const uint8_t* end_;
9178 DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
9182 template <typename T>
9183 class VectorIterator {
9185 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
9186 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
9187 T GetNext() { return data_[index_++]; }
9188 bool has_more() { return index_ < data_.length(); }
9190 Vector<const T> data_;
9195 // The Oddball describes objects null, undefined, true, and false.
9196 class Oddball: public HeapObject {
9198 // [to_string]: Cached to_string computed at startup.
9199 DECL_ACCESSORS(to_string, String)
9201 // [to_number]: Cached to_number computed at startup.
9202 DECL_ACCESSORS(to_number, Object)
9204 inline byte kind() const;
9205 inline void set_kind(byte kind);
9207 DECLARE_CAST(Oddball)
9209 // Dispatched behavior.
9210 DECLARE_VERIFIER(Oddball)
9212 // Initialize the fields.
9213 static void Initialize(Isolate* isolate,
9214 Handle<Oddball> oddball,
9215 const char* to_string,
9216 Handle<Object> to_number,
9219 // Layout description.
9220 static const int kToStringOffset = HeapObject::kHeaderSize;
9221 static const int kToNumberOffset = kToStringOffset + kPointerSize;
9222 static const int kKindOffset = kToNumberOffset + kPointerSize;
9223 static const int kSize = kKindOffset + kPointerSize;
9225 static const byte kFalse = 0;
9226 static const byte kTrue = 1;
9227 static const byte kNotBooleanMask = ~1;
9228 static const byte kTheHole = 2;
9229 static const byte kNull = 3;
9230 static const byte kArgumentMarker = 4;
9231 static const byte kUndefined = 5;
9232 static const byte kUninitialized = 6;
9233 static const byte kOther = 7;
9234 static const byte kException = 8;
9236 typedef FixedBodyDescriptor<kToStringOffset,
9237 kToNumberOffset + kPointerSize,
9238 kSize> BodyDescriptor;
9240 STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset);
9241 STATIC_ASSERT(kNull == Internals::kNullOddballKind);
9242 STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind);
9245 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
9249 class Cell: public HeapObject {
9251 // [value]: value of the cell.
9252 DECL_ACCESSORS(value, Object)
9256 static inline Cell* FromValueAddress(Address value) {
9257 Object* result = FromAddress(value - kValueOffset);
9258 return static_cast<Cell*>(result);
9261 inline Address ValueAddress() {
9262 return address() + kValueOffset;
9265 // Dispatched behavior.
9266 DECLARE_PRINTER(Cell)
9267 DECLARE_VERIFIER(Cell)
9269 // Layout description.
9270 static const int kValueOffset = HeapObject::kHeaderSize;
9271 static const int kSize = kValueOffset + kPointerSize;
9273 typedef FixedBodyDescriptor<kValueOffset,
9274 kValueOffset + kPointerSize,
9275 kSize> BodyDescriptor;
9278 DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9282 class PropertyCell : public HeapObject {
9284 // [property_details]: details of the global property.
9285 DECL_ACCESSORS(property_details_raw, Object)
9286 // [value]: value of the global property.
9287 DECL_ACCESSORS(value, Object)
9288 // [dependent_code]: dependent code that depends on the type of the global
9290 DECL_ACCESSORS(dependent_code, DependentCode)
9292 PropertyDetails property_details() {
9293 return PropertyDetails(Smi::cast(property_details_raw()));
9296 void set_property_details(PropertyDetails details) {
9297 set_property_details_raw(details.AsSmi());
9300 PropertyCellConstantType GetConstantType();
9302 // Computes the new type of the cell's contents for the given value, but
9303 // without actually modifying the details.
9304 static PropertyCellType UpdatedType(Handle<PropertyCell> cell,
9305 Handle<Object> value,
9306 PropertyDetails details);
9307 static void UpdateCell(Handle<GlobalDictionary> dictionary, int entry,
9308 Handle<Object> value, PropertyDetails details);
9310 static Handle<PropertyCell> InvalidateEntry(
9311 Handle<GlobalDictionary> dictionary, int entry);
9313 static void SetValueWithInvalidation(Handle<PropertyCell> cell,
9314 Handle<Object> new_value);
9316 DECLARE_CAST(PropertyCell)
9318 // Dispatched behavior.
9319 DECLARE_PRINTER(PropertyCell)
9320 DECLARE_VERIFIER(PropertyCell)
9322 // Layout description.
9323 static const int kDetailsOffset = HeapObject::kHeaderSize;
9324 static const int kValueOffset = kDetailsOffset + kPointerSize;
9325 static const int kDependentCodeOffset = kValueOffset + kPointerSize;
9326 static const int kSize = kDependentCodeOffset + kPointerSize;
9328 static const int kPointerFieldsBeginOffset = kValueOffset;
9329 static const int kPointerFieldsEndOffset = kSize;
9331 typedef FixedBodyDescriptor<kValueOffset,
9333 kSize> BodyDescriptor;
9336 DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9340 class WeakCell : public HeapObject {
9342 inline Object* value() const;
9344 // This should not be called by anyone except GC.
9345 inline void clear();
9347 // This should not be called by anyone except allocator.
9348 inline void initialize(HeapObject* value);
9350 inline bool cleared() const;
9352 DECL_ACCESSORS(next, Object)
9354 inline void clear_next(Heap* heap);
9356 inline bool next_cleared();
9358 DECLARE_CAST(WeakCell)
9360 DECLARE_PRINTER(WeakCell)
9361 DECLARE_VERIFIER(WeakCell)
9363 // Layout description.
9364 static const int kValueOffset = HeapObject::kHeaderSize;
9365 static const int kNextOffset = kValueOffset + kPointerSize;
9366 static const int kSize = kNextOffset + kPointerSize;
9368 typedef FixedBodyDescriptor<kValueOffset, kSize, kSize> BodyDescriptor;
9371 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakCell);
9375 // The JSProxy describes EcmaScript Harmony proxies
9376 class JSProxy: public JSReceiver {
9378 // [handler]: The handler property.
9379 DECL_ACCESSORS(handler, Object)
9381 // [hash]: The hash code property (undefined if not initialized yet).
9382 DECL_ACCESSORS(hash, Object)
9384 DECLARE_CAST(JSProxy)
9386 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithHandler(
9387 Handle<JSProxy> proxy,
9388 Handle<Object> receiver,
9391 // If the handler defines an accessor property with a setter, invoke it.
9392 // If it defines an accessor property without a setter, or a data property
9393 // that is read-only, throw. In all these cases set '*done' to true,
9394 // otherwise set it to false.
9396 static MaybeHandle<Object> SetPropertyViaPrototypesWithHandler(
9397 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9398 Handle<Object> value, LanguageMode language_mode, bool* done);
9400 MUST_USE_RESULT static Maybe<PropertyAttributes>
9401 GetPropertyAttributesWithHandler(Handle<JSProxy> proxy,
9402 Handle<Object> receiver,
9404 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithHandler(
9405 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9406 Handle<Object> value, LanguageMode language_mode);
9408 // Turn the proxy into an (empty) JSObject.
9409 static void Fix(Handle<JSProxy> proxy);
9411 // Initializes the body after the handler slot.
9412 inline void InitializeBody(int object_size, Object* value);
9414 // Invoke a trap by name. If the trap does not exist on this's handler,
9415 // but derived_trap is non-NULL, invoke that instead. May cause GC.
9416 MUST_USE_RESULT static MaybeHandle<Object> CallTrap(
9417 Handle<JSProxy> proxy,
9419 Handle<Object> derived_trap,
9421 Handle<Object> args[]);
9423 // Dispatched behavior.
9424 DECLARE_PRINTER(JSProxy)
9425 DECLARE_VERIFIER(JSProxy)
9427 // Layout description. We add padding so that a proxy has the same
9428 // size as a virgin JSObject. This is essential for becoming a JSObject
9430 static const int kHandlerOffset = HeapObject::kHeaderSize;
9431 static const int kHashOffset = kHandlerOffset + kPointerSize;
9432 static const int kPaddingOffset = kHashOffset + kPointerSize;
9433 static const int kSize = JSObject::kHeaderSize;
9434 static const int kHeaderSize = kPaddingOffset;
9435 static const int kPaddingSize = kSize - kPaddingOffset;
9437 STATIC_ASSERT(kPaddingSize >= 0);
9439 typedef FixedBodyDescriptor<kHandlerOffset,
9441 kSize> BodyDescriptor;
9444 friend class JSReceiver;
9446 MUST_USE_RESULT static Maybe<bool> HasPropertyWithHandler(
9447 Handle<JSProxy> proxy, Handle<Name> name);
9449 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithHandler(
9450 Handle<JSProxy> proxy, Handle<Name> name, LanguageMode language_mode);
9452 MUST_USE_RESULT Object* GetIdentityHash();
9454 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
9456 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
9460 class JSFunctionProxy: public JSProxy {
9462 // [call_trap]: The call trap.
9463 DECL_ACCESSORS(call_trap, Object)
9465 // [construct_trap]: The construct trap.
9466 DECL_ACCESSORS(construct_trap, Object)
9468 DECLARE_CAST(JSFunctionProxy)
9470 // Dispatched behavior.
9471 DECLARE_PRINTER(JSFunctionProxy)
9472 DECLARE_VERIFIER(JSFunctionProxy)
9474 // Layout description.
9475 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
9476 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
9477 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
9478 static const int kSize = JSFunction::kSize;
9479 static const int kPaddingSize = kSize - kPaddingOffset;
9481 STATIC_ASSERT(kPaddingSize >= 0);
9483 typedef FixedBodyDescriptor<kHandlerOffset,
9484 kConstructTrapOffset + kPointerSize,
9485 kSize> BodyDescriptor;
9488 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
9492 class JSCollection : public JSObject {
9494 // [table]: the backing hash table
9495 DECL_ACCESSORS(table, Object)
9497 static const int kTableOffset = JSObject::kHeaderSize;
9498 static const int kSize = kTableOffset + kPointerSize;
9501 DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollection);
9505 // The JSSet describes EcmaScript Harmony sets
9506 class JSSet : public JSCollection {
9510 // Dispatched behavior.
9511 DECLARE_PRINTER(JSSet)
9512 DECLARE_VERIFIER(JSSet)
9515 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
9519 // The JSMap describes EcmaScript Harmony maps
9520 class JSMap : public JSCollection {
9524 // Dispatched behavior.
9525 DECLARE_PRINTER(JSMap)
9526 DECLARE_VERIFIER(JSMap)
9529 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
9533 // OrderedHashTableIterator is an iterator that iterates over the keys and
9534 // values of an OrderedHashTable.
9536 // The iterator has a reference to the underlying OrderedHashTable data,
9537 // [table], as well as the current [index] the iterator is at.
9539 // When the OrderedHashTable is rehashed it adds a reference from the old table
9540 // to the new table as well as storing enough data about the changes so that the
9541 // iterator [index] can be adjusted accordingly.
9543 // When the [Next] result from the iterator is requested, the iterator checks if
9544 // there is a newer table that it needs to transition to.
9545 template<class Derived, class TableType>
9546 class OrderedHashTableIterator: public JSObject {
9548 // [table]: the backing hash table mapping keys to values.
9549 DECL_ACCESSORS(table, Object)
9551 // [index]: The index into the data table.
9552 DECL_ACCESSORS(index, Object)
9554 // [kind]: The kind of iteration this is. One of the [Kind] enum values.
9555 DECL_ACCESSORS(kind, Object)
9558 void OrderedHashTableIteratorPrint(std::ostream& os); // NOLINT
9561 static const int kTableOffset = JSObject::kHeaderSize;
9562 static const int kIndexOffset = kTableOffset + kPointerSize;
9563 static const int kKindOffset = kIndexOffset + kPointerSize;
9564 static const int kSize = kKindOffset + kPointerSize;
9572 // Whether the iterator has more elements. This needs to be called before
9573 // calling |CurrentKey| and/or |CurrentValue|.
9576 // Move the index forward one.
9578 set_index(Smi::FromInt(Smi::cast(index())->value() + 1));
9581 // Populates the array with the next key and value and then moves the iterator
9583 // This returns the |kind| or 0 if the iterator is already at the end.
9584 Smi* Next(JSArray* value_array);
9586 // Returns the current key of the iterator. This should only be called when
9587 // |HasMore| returns true.
9588 inline Object* CurrentKey();
9591 // Transitions the iterator to the non obsolete backing store. This is a NOP
9592 // if the [table] is not obsolete.
9595 DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
9599 class JSSetIterator: public OrderedHashTableIterator<JSSetIterator,
9602 // Dispatched behavior.
9603 DECLARE_PRINTER(JSSetIterator)
9604 DECLARE_VERIFIER(JSSetIterator)
9606 DECLARE_CAST(JSSetIterator)
9608 // Called by |Next| to populate the array. This allows the subclasses to
9609 // populate the array differently.
9610 inline void PopulateValueArray(FixedArray* array);
9613 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSetIterator);
9617 class JSMapIterator: public OrderedHashTableIterator<JSMapIterator,
9620 // Dispatched behavior.
9621 DECLARE_PRINTER(JSMapIterator)
9622 DECLARE_VERIFIER(JSMapIterator)
9624 DECLARE_CAST(JSMapIterator)
9626 // Called by |Next| to populate the array. This allows the subclasses to
9627 // populate the array differently.
9628 inline void PopulateValueArray(FixedArray* array);
9631 // Returns the current value of the iterator. This should only be called when
9632 // |HasMore| returns true.
9633 inline Object* CurrentValue();
9635 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMapIterator);
9639 // Base class for both JSWeakMap and JSWeakSet
9640 class JSWeakCollection: public JSObject {
9642 // [table]: the backing hash table mapping keys to values.
9643 DECL_ACCESSORS(table, Object)
9645 // [next]: linked list of encountered weak maps during GC.
9646 DECL_ACCESSORS(next, Object)
9648 static const int kTableOffset = JSObject::kHeaderSize;
9649 static const int kNextOffset = kTableOffset + kPointerSize;
9650 static const int kSize = kNextOffset + kPointerSize;
9653 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
9657 // The JSWeakMap describes EcmaScript Harmony weak maps
9658 class JSWeakMap: public JSWeakCollection {
9660 DECLARE_CAST(JSWeakMap)
9662 // Dispatched behavior.
9663 DECLARE_PRINTER(JSWeakMap)
9664 DECLARE_VERIFIER(JSWeakMap)
9667 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
9671 // The JSWeakSet describes EcmaScript Harmony weak sets
9672 class JSWeakSet: public JSWeakCollection {
9674 DECLARE_CAST(JSWeakSet)
9676 // Dispatched behavior.
9677 DECLARE_PRINTER(JSWeakSet)
9678 DECLARE_VERIFIER(JSWeakSet)
9681 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
9685 // Whether a JSArrayBuffer is a SharedArrayBuffer or not.
9686 enum class SharedFlag { kNotShared, kShared };
9689 class JSArrayBuffer: public JSObject {
9691 // [backing_store]: backing memory for this array
9692 DECL_ACCESSORS(backing_store, void)
9694 // [byte_length]: length in bytes
9695 DECL_ACCESSORS(byte_length, Object)
9697 inline uint32_t bit_field() const;
9698 inline void set_bit_field(uint32_t bits);
9700 inline bool is_external();
9701 inline void set_is_external(bool value);
9703 inline bool is_neuterable();
9704 inline void set_is_neuterable(bool value);
9706 inline bool was_neutered();
9707 inline void set_was_neutered(bool value);
9709 inline bool is_shared();
9710 inline void set_is_shared(bool value);
9712 DECLARE_CAST(JSArrayBuffer)
9716 // Dispatched behavior.
9717 DECLARE_PRINTER(JSArrayBuffer)
9718 DECLARE_VERIFIER(JSArrayBuffer)
9720 static const int kBackingStoreOffset = JSObject::kHeaderSize;
9721 static const int kByteLengthOffset = kBackingStoreOffset + kPointerSize;
9722 static const int kBitFieldSlot = kByteLengthOffset + kPointerSize;
9723 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
9724 static const int kBitFieldOffset = kBitFieldSlot;
9726 static const int kBitFieldOffset = kBitFieldSlot + kIntSize;
9728 static const int kSize = kBitFieldSlot + kPointerSize;
9730 static const int kSizeWithInternalFields =
9731 kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
9733 class IsExternal : public BitField<bool, 1, 1> {};
9734 class IsNeuterable : public BitField<bool, 2, 1> {};
9735 class WasNeutered : public BitField<bool, 3, 1> {};
9736 class IsShared : public BitField<bool, 4, 1> {};
9739 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
9743 class JSArrayBufferView: public JSObject {
9745 // [buffer]: ArrayBuffer that this typed array views.
9746 DECL_ACCESSORS(buffer, Object)
9748 // [byte_offset]: offset of typed array in bytes.
9749 DECL_ACCESSORS(byte_offset, Object)
9751 // [byte_length]: length of typed array in bytes.
9752 DECL_ACCESSORS(byte_length, Object)
9754 DECLARE_CAST(JSArrayBufferView)
9756 DECLARE_VERIFIER(JSArrayBufferView)
9758 inline bool WasNeutered() const;
9760 static const int kBufferOffset = JSObject::kHeaderSize;
9761 static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
9762 static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
9763 static const int kViewSize = kByteLengthOffset + kPointerSize;
9767 DECL_ACCESSORS(raw_byte_offset, Object)
9768 DECL_ACCESSORS(raw_byte_length, Object)
9771 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
9775 class JSTypedArray: public JSArrayBufferView {
9777 // [length]: length of typed array in elements.
9778 DECL_ACCESSORS(length, Object)
9779 inline uint32_t length_value() const;
9781 DECLARE_CAST(JSTypedArray)
9783 ExternalArrayType type();
9784 size_t element_size();
9786 Handle<JSArrayBuffer> GetBuffer();
9788 // Dispatched behavior.
9789 DECLARE_PRINTER(JSTypedArray)
9790 DECLARE_VERIFIER(JSTypedArray)
9792 static const int kLengthOffset = kViewSize + kPointerSize;
9793 static const int kSize = kLengthOffset + kPointerSize;
9795 static const int kSizeWithInternalFields =
9796 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9799 static Handle<JSArrayBuffer> MaterializeArrayBuffer(
9800 Handle<JSTypedArray> typed_array);
9802 DECL_ACCESSORS(raw_length, Object)
9805 DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
9809 class JSDataView: public JSArrayBufferView {
9811 DECLARE_CAST(JSDataView)
9813 // Dispatched behavior.
9814 DECLARE_PRINTER(JSDataView)
9815 DECLARE_VERIFIER(JSDataView)
9817 static const int kSize = kViewSize;
9819 static const int kSizeWithInternalFields =
9820 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9823 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
9827 // Foreign describes objects pointing from JavaScript to C structures.
9828 class Foreign: public HeapObject {
9830 // [address]: field containing the address.
9831 inline Address foreign_address();
9832 inline void set_foreign_address(Address value);
9834 DECLARE_CAST(Foreign)
9836 // Dispatched behavior.
9837 inline void ForeignIterateBody(ObjectVisitor* v);
9839 template<typename StaticVisitor>
9840 inline void ForeignIterateBody();
9842 // Dispatched behavior.
9843 DECLARE_PRINTER(Foreign)
9844 DECLARE_VERIFIER(Foreign)
9846 // Layout description.
9848 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
9849 static const int kSize = kForeignAddressOffset + kPointerSize;
9851 STATIC_ASSERT(kForeignAddressOffset == Internals::kForeignAddressOffset);
9854 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
9858 // The JSArray describes JavaScript Arrays
9859 // Such an array can be in one of two modes:
9860 // - fast, backing storage is a FixedArray and length <= elements.length();
9861 // Please note: push and pop can be used to grow and shrink the array.
9862 // - slow, backing storage is a HashTable with numbers as keys.
9863 class JSArray: public JSObject {
9865 // [length]: The length property.
9866 DECL_ACCESSORS(length, Object)
9868 // Overload the length setter to skip write barrier when the length
9869 // is set to a smi. This matches the set function on FixedArray.
9870 inline void set_length(Smi* length);
9872 static bool HasReadOnlyLength(Handle<JSArray> array);
9873 static bool WouldChangeReadOnlyLength(Handle<JSArray> array, uint32_t index);
9874 static MaybeHandle<Object> ReadOnlyLengthError(Handle<JSArray> array);
9876 // Initialize the array with the given capacity. The function may
9877 // fail due to out-of-memory situations, but only if the requested
9878 // capacity is non-zero.
9879 static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
9881 // If the JSArray has fast elements, and new_length would result in
9882 // normalization, returns true.
9883 bool SetLengthWouldNormalize(uint32_t new_length);
9884 static inline bool SetLengthWouldNormalize(Heap* heap, uint32_t new_length);
9886 // Initializes the array to a certain length.
9887 inline bool AllowsSetLength();
9889 static void SetLength(Handle<JSArray> array, uint32_t length);
9890 // Same as above but will also queue splice records if |array| is observed.
9891 static MaybeHandle<Object> ObservableSetLength(Handle<JSArray> array,
9894 // Set the content of the array to the content of storage.
9895 static inline void SetContent(Handle<JSArray> array,
9896 Handle<FixedArrayBase> storage);
9898 DECLARE_CAST(JSArray)
9900 // Dispatched behavior.
9901 DECLARE_PRINTER(JSArray)
9902 DECLARE_VERIFIER(JSArray)
9904 // Number of element slots to pre-allocate for an empty array.
9905 static const int kPreallocatedArrayElements = 4;
9907 // Layout description.
9908 static const int kLengthOffset = JSObject::kHeaderSize;
9909 static const int kSize = kLengthOffset + kPointerSize;
9912 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
9916 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
9917 Handle<Map> initial_map);
9920 // JSRegExpResult is just a JSArray with a specific initial map.
9921 // This initial map adds in-object properties for "index" and "input"
9922 // properties, as assigned by RegExp.prototype.exec, which allows
9923 // faster creation of RegExp exec results.
9924 // This class just holds constants used when creating the result.
9925 // After creation the result must be treated as a JSArray in all regards.
9926 class JSRegExpResult: public JSArray {
9928 // Offsets of object fields.
9929 static const int kIndexOffset = JSArray::kSize;
9930 static const int kInputOffset = kIndexOffset + kPointerSize;
9931 static const int kSize = kInputOffset + kPointerSize;
9932 // Indices of in-object properties.
9933 static const int kIndexIndex = 0;
9934 static const int kInputIndex = 1;
9936 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
9940 class AccessorInfo: public Struct {
9942 DECL_ACCESSORS(name, Object)
9943 DECL_ACCESSORS(flag, Smi)
9944 DECL_ACCESSORS(expected_receiver_type, Object)
9946 inline bool all_can_read();
9947 inline void set_all_can_read(bool value);
9949 inline bool all_can_write();
9950 inline void set_all_can_write(bool value);
9952 inline bool is_special_data_property();
9953 inline void set_is_special_data_property(bool value);
9955 inline PropertyAttributes property_attributes();
9956 inline void set_property_attributes(PropertyAttributes attributes);
9958 // Checks whether the given receiver is compatible with this accessor.
9959 static bool IsCompatibleReceiverMap(Isolate* isolate,
9960 Handle<AccessorInfo> info,
9962 inline bool IsCompatibleReceiver(Object* receiver);
9964 DECLARE_CAST(AccessorInfo)
9966 // Dispatched behavior.
9967 DECLARE_VERIFIER(AccessorInfo)
9969 // Append all descriptors to the array that are not already there.
9970 // Return number added.
9971 static int AppendUnique(Handle<Object> descriptors,
9972 Handle<FixedArray> array,
9973 int valid_descriptors);
9975 static const int kNameOffset = HeapObject::kHeaderSize;
9976 static const int kFlagOffset = kNameOffset + kPointerSize;
9977 static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
9978 static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
9981 inline bool HasExpectedReceiverType() {
9982 return expected_receiver_type()->IsFunctionTemplateInfo();
9984 // Bit positions in flag.
9985 static const int kAllCanReadBit = 0;
9986 static const int kAllCanWriteBit = 1;
9987 static const int kSpecialDataProperty = 2;
9988 class AttributesField : public BitField<PropertyAttributes, 3, 3> {};
9990 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
9994 // An accessor must have a getter, but can have no setter.
9996 // When setting a property, V8 searches accessors in prototypes.
9997 // If an accessor was found and it does not have a setter,
9998 // the request is ignored.
10000 // If the accessor in the prototype has the READ_ONLY property attribute, then
10001 // a new value is added to the derived object when the property is set.
10002 // This shadows the accessor in the prototype.
10003 class ExecutableAccessorInfo: public AccessorInfo {
10005 DECL_ACCESSORS(getter, Object)
10006 DECL_ACCESSORS(setter, Object)
10007 DECL_ACCESSORS(data, Object)
10009 DECLARE_CAST(ExecutableAccessorInfo)
10011 // Dispatched behavior.
10012 DECLARE_PRINTER(ExecutableAccessorInfo)
10013 DECLARE_VERIFIER(ExecutableAccessorInfo)
10015 static const int kGetterOffset = AccessorInfo::kSize;
10016 static const int kSetterOffset = kGetterOffset + kPointerSize;
10017 static const int kDataOffset = kSetterOffset + kPointerSize;
10018 static const int kSize = kDataOffset + kPointerSize;
10020 static void ClearSetter(Handle<ExecutableAccessorInfo> info);
10023 DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
10027 // Support for JavaScript accessors: A pair of a getter and a setter. Each
10028 // accessor can either be
10029 // * a pointer to a JavaScript function or proxy: a real accessor
10030 // * undefined: considered an accessor by the spec, too, strangely enough
10031 // * the hole: an accessor which has not been set
10032 // * a pointer to a map: a transition used to ensure map sharing
10033 class AccessorPair: public Struct {
10035 DECL_ACCESSORS(getter, Object)
10036 DECL_ACCESSORS(setter, Object)
10038 DECLARE_CAST(AccessorPair)
10040 static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
10042 Object* get(AccessorComponent component) {
10043 return component == ACCESSOR_GETTER ? getter() : setter();
10046 void set(AccessorComponent component, Object* value) {
10047 if (component == ACCESSOR_GETTER) {
10054 // Note: Returns undefined instead in case of a hole.
10055 Object* GetComponent(AccessorComponent component);
10057 // Set both components, skipping arguments which are a JavaScript null.
10058 void SetComponents(Object* getter, Object* setter) {
10059 if (!getter->IsNull()) set_getter(getter);
10060 if (!setter->IsNull()) set_setter(setter);
10063 bool Equals(AccessorPair* pair) {
10064 return (this == pair) || pair->Equals(getter(), setter());
10067 bool Equals(Object* getter_value, Object* setter_value) {
10068 return (getter() == getter_value) && (setter() == setter_value);
10071 bool ContainsAccessor() {
10072 return IsJSAccessor(getter()) || IsJSAccessor(setter());
10075 // Dispatched behavior.
10076 DECLARE_PRINTER(AccessorPair)
10077 DECLARE_VERIFIER(AccessorPair)
10079 static const int kGetterOffset = HeapObject::kHeaderSize;
10080 static const int kSetterOffset = kGetterOffset + kPointerSize;
10081 static const int kSize = kSetterOffset + kPointerSize;
10084 // Strangely enough, in addition to functions and harmony proxies, the spec
10085 // requires us to consider undefined as a kind of accessor, too:
10087 // Object.defineProperty(obj, "foo", {get: undefined});
10088 // assertTrue("foo" in obj);
10089 bool IsJSAccessor(Object* obj) {
10090 return obj->IsSpecFunction() || obj->IsUndefined();
10093 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
10097 class AccessCheckInfo: public Struct {
10099 DECL_ACCESSORS(named_callback, Object)
10100 DECL_ACCESSORS(indexed_callback, Object)
10101 DECL_ACCESSORS(data, Object)
10103 DECLARE_CAST(AccessCheckInfo)
10105 // Dispatched behavior.
10106 DECLARE_PRINTER(AccessCheckInfo)
10107 DECLARE_VERIFIER(AccessCheckInfo)
10109 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
10110 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
10111 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
10112 static const int kSize = kDataOffset + kPointerSize;
10115 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
10119 class InterceptorInfo: public Struct {
10121 DECL_ACCESSORS(getter, Object)
10122 DECL_ACCESSORS(setter, Object)
10123 DECL_ACCESSORS(query, Object)
10124 DECL_ACCESSORS(deleter, Object)
10125 DECL_ACCESSORS(enumerator, Object)
10126 DECL_ACCESSORS(data, Object)
10127 DECL_BOOLEAN_ACCESSORS(can_intercept_symbols)
10128 DECL_BOOLEAN_ACCESSORS(all_can_read)
10129 DECL_BOOLEAN_ACCESSORS(non_masking)
10131 inline int flags() const;
10132 inline void set_flags(int flags);
10134 DECLARE_CAST(InterceptorInfo)
10136 // Dispatched behavior.
10137 DECLARE_PRINTER(InterceptorInfo)
10138 DECLARE_VERIFIER(InterceptorInfo)
10140 static const int kGetterOffset = HeapObject::kHeaderSize;
10141 static const int kSetterOffset = kGetterOffset + kPointerSize;
10142 static const int kQueryOffset = kSetterOffset + kPointerSize;
10143 static const int kDeleterOffset = kQueryOffset + kPointerSize;
10144 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
10145 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
10146 static const int kFlagsOffset = kDataOffset + kPointerSize;
10147 static const int kSize = kFlagsOffset + kPointerSize;
10149 static const int kCanInterceptSymbolsBit = 0;
10150 static const int kAllCanReadBit = 1;
10151 static const int kNonMasking = 2;
10154 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
10158 class CallHandlerInfo: public Struct {
10160 DECL_ACCESSORS(callback, Object)
10161 DECL_ACCESSORS(data, Object)
10163 DECLARE_CAST(CallHandlerInfo)
10165 // Dispatched behavior.
10166 DECLARE_PRINTER(CallHandlerInfo)
10167 DECLARE_VERIFIER(CallHandlerInfo)
10169 static const int kCallbackOffset = HeapObject::kHeaderSize;
10170 static const int kDataOffset = kCallbackOffset + kPointerSize;
10171 static const int kSize = kDataOffset + kPointerSize;
10174 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
10178 class TemplateInfo: public Struct {
10180 DECL_ACCESSORS(tag, Object)
10181 inline int number_of_properties() const;
10182 inline void set_number_of_properties(int value);
10183 DECL_ACCESSORS(property_list, Object)
10184 DECL_ACCESSORS(property_accessors, Object)
10186 DECLARE_VERIFIER(TemplateInfo)
10188 static const int kTagOffset = HeapObject::kHeaderSize;
10189 static const int kNumberOfProperties = kTagOffset + kPointerSize;
10190 static const int kPropertyListOffset = kNumberOfProperties + kPointerSize;
10191 static const int kPropertyAccessorsOffset =
10192 kPropertyListOffset + kPointerSize;
10193 static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
10196 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
10200 class FunctionTemplateInfo: public TemplateInfo {
10202 DECL_ACCESSORS(serial_number, Object)
10203 DECL_ACCESSORS(call_code, Object)
10204 DECL_ACCESSORS(prototype_template, Object)
10205 DECL_ACCESSORS(parent_template, Object)
10206 DECL_ACCESSORS(named_property_handler, Object)
10207 DECL_ACCESSORS(indexed_property_handler, Object)
10208 DECL_ACCESSORS(instance_template, Object)
10209 DECL_ACCESSORS(class_name, Object)
10210 DECL_ACCESSORS(signature, Object)
10211 DECL_ACCESSORS(instance_call_handler, Object)
10212 DECL_ACCESSORS(access_check_info, Object)
10213 DECL_ACCESSORS(flag, Smi)
10215 inline int length() const;
10216 inline void set_length(int value);
10218 // Following properties use flag bits.
10219 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
10220 DECL_BOOLEAN_ACCESSORS(undetectable)
10221 // If the bit is set, object instances created by this function
10222 // requires access check.
10223 DECL_BOOLEAN_ACCESSORS(needs_access_check)
10224 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
10225 DECL_BOOLEAN_ACCESSORS(remove_prototype)
10226 DECL_BOOLEAN_ACCESSORS(do_not_cache)
10227 DECL_BOOLEAN_ACCESSORS(instantiated)
10228 DECL_BOOLEAN_ACCESSORS(accept_any_receiver)
10230 DECLARE_CAST(FunctionTemplateInfo)
10232 // Dispatched behavior.
10233 DECLARE_PRINTER(FunctionTemplateInfo)
10234 DECLARE_VERIFIER(FunctionTemplateInfo)
10236 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
10237 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
10238 static const int kPrototypeTemplateOffset =
10239 kCallCodeOffset + kPointerSize;
10240 static const int kParentTemplateOffset =
10241 kPrototypeTemplateOffset + kPointerSize;
10242 static const int kNamedPropertyHandlerOffset =
10243 kParentTemplateOffset + kPointerSize;
10244 static const int kIndexedPropertyHandlerOffset =
10245 kNamedPropertyHandlerOffset + kPointerSize;
10246 static const int kInstanceTemplateOffset =
10247 kIndexedPropertyHandlerOffset + kPointerSize;
10248 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
10249 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
10250 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
10251 static const int kAccessCheckInfoOffset =
10252 kInstanceCallHandlerOffset + kPointerSize;
10253 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
10254 static const int kLengthOffset = kFlagOffset + kPointerSize;
10255 static const int kSize = kLengthOffset + kPointerSize;
10257 // Returns true if |object| is an instance of this function template.
10258 bool IsTemplateFor(Object* object);
10259 bool IsTemplateFor(Map* map);
10261 // Returns the holder JSObject if the function can legally be called with this
10262 // receiver. Returns Heap::null_value() if the call is illegal.
10263 Object* GetCompatibleReceiver(Isolate* isolate, Object* receiver);
10266 // Bit position in the flag, from least significant bit position.
10267 static const int kHiddenPrototypeBit = 0;
10268 static const int kUndetectableBit = 1;
10269 static const int kNeedsAccessCheckBit = 2;
10270 static const int kReadOnlyPrototypeBit = 3;
10271 static const int kRemovePrototypeBit = 4;
10272 static const int kDoNotCacheBit = 5;
10273 static const int kInstantiatedBit = 6;
10274 static const int kAcceptAnyReceiver = 7;
10276 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
10280 class ObjectTemplateInfo: public TemplateInfo {
10282 DECL_ACCESSORS(constructor, Object)
10283 DECL_ACCESSORS(internal_field_count, Object)
10285 DECLARE_CAST(ObjectTemplateInfo)
10287 // Dispatched behavior.
10288 DECLARE_PRINTER(ObjectTemplateInfo)
10289 DECLARE_VERIFIER(ObjectTemplateInfo)
10291 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10292 static const int kInternalFieldCountOffset =
10293 kConstructorOffset + kPointerSize;
10294 static const int kSize = kInternalFieldCountOffset + kPointerSize;
10298 class TypeSwitchInfo: public Struct {
10300 DECL_ACCESSORS(types, Object)
10302 DECLARE_CAST(TypeSwitchInfo)
10304 // Dispatched behavior.
10305 DECLARE_PRINTER(TypeSwitchInfo)
10306 DECLARE_VERIFIER(TypeSwitchInfo)
10308 static const int kTypesOffset = Struct::kHeaderSize;
10309 static const int kSize = kTypesOffset + kPointerSize;
10313 // The DebugInfo class holds additional information for a function being
10315 class DebugInfo: public Struct {
10317 // The shared function info for the source being debugged.
10318 DECL_ACCESSORS(shared, SharedFunctionInfo)
10319 // Code object for the patched code. This code object is the code object
10320 // currently active for the function.
10321 DECL_ACCESSORS(code, Code)
10322 // Fixed array holding status information for each active break point.
10323 DECL_ACCESSORS(break_points, FixedArray)
10325 // Check if there is a break point at a code position.
10326 bool HasBreakPoint(int code_position);
10327 // Get the break point info object for a code position.
10328 Object* GetBreakPointInfo(int code_position);
10329 // Clear a break point.
10330 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
10332 Handle<Object> break_point_object);
10333 // Set a break point.
10334 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
10335 int source_position, int statement_position,
10336 Handle<Object> break_point_object);
10337 // Get the break point objects for a code position.
10338 Handle<Object> GetBreakPointObjects(int code_position);
10339 // Find the break point info holding this break point object.
10340 static Handle<Object> FindBreakPointInfo(Handle<DebugInfo> debug_info,
10341 Handle<Object> break_point_object);
10342 // Get the number of break points for this function.
10343 int GetBreakPointCount();
10345 DECLARE_CAST(DebugInfo)
10347 // Dispatched behavior.
10348 DECLARE_PRINTER(DebugInfo)
10349 DECLARE_VERIFIER(DebugInfo)
10351 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
10352 static const int kCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
10353 static const int kBreakPointsStateIndex = kCodeIndex + kPointerSize;
10354 static const int kSize = kBreakPointsStateIndex + kPointerSize;
10356 static const int kEstimatedNofBreakPointsInFunction = 16;
10359 static const int kNoBreakPointInfo = -1;
10361 // Lookup the index in the break_points array for a code position.
10362 int GetBreakPointInfoIndex(int code_position);
10364 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
10368 // The BreakPointInfo class holds information for break points set in a
10369 // function. The DebugInfo object holds a BreakPointInfo object for each code
10370 // position with one or more break points.
10371 class BreakPointInfo: public Struct {
10373 // The position in the code for the break point.
10374 DECL_ACCESSORS(code_position, Smi)
10375 // The position in the source for the break position.
10376 DECL_ACCESSORS(source_position, Smi)
10377 // The position in the source for the last statement before this break
10379 DECL_ACCESSORS(statement_position, Smi)
10380 // List of related JavaScript break points.
10381 DECL_ACCESSORS(break_point_objects, Object)
10383 // Removes a break point.
10384 static void ClearBreakPoint(Handle<BreakPointInfo> info,
10385 Handle<Object> break_point_object);
10386 // Set a break point.
10387 static void SetBreakPoint(Handle<BreakPointInfo> info,
10388 Handle<Object> break_point_object);
10389 // Check if break point info has this break point object.
10390 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
10391 Handle<Object> break_point_object);
10392 // Get the number of break points for this code position.
10393 int GetBreakPointCount();
10395 DECLARE_CAST(BreakPointInfo)
10397 // Dispatched behavior.
10398 DECLARE_PRINTER(BreakPointInfo)
10399 DECLARE_VERIFIER(BreakPointInfo)
10401 static const int kCodePositionIndex = Struct::kHeaderSize;
10402 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
10403 static const int kStatementPositionIndex =
10404 kSourcePositionIndex + kPointerSize;
10405 static const int kBreakPointObjectsIndex =
10406 kStatementPositionIndex + kPointerSize;
10407 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
10410 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
10414 #undef DECL_BOOLEAN_ACCESSORS
10415 #undef DECL_ACCESSORS
10416 #undef DECLARE_CAST
10417 #undef DECLARE_VERIFIER
10419 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
10420 V(kStringTable, "string_table", "(Internalized strings)") \
10421 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
10422 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
10423 V(kSmiRootList, "smi_root_list", "(Smi roots)") \
10424 V(kInternalizedString, "internalized_string", "(Internal string)") \
10425 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
10426 V(kTop, "top", "(Isolate)") \
10427 V(kRelocatable, "relocatable", "(Relocatable)") \
10428 V(kDebug, "debug", "(Debugger)") \
10429 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
10430 V(kHandleScope, "handlescope", "(Handle scope)") \
10431 V(kBuiltins, "builtins", "(Builtins)") \
10432 V(kGlobalHandles, "globalhandles", "(Global handles)") \
10433 V(kEternalHandles, "eternalhandles", "(Eternal handles)") \
10434 V(kThreadManager, "threadmanager", "(Thread manager)") \
10435 V(kStrongRoots, "strong roots", "(Strong roots)") \
10436 V(kExtensions, "Extensions", "(Extensions)")
10438 class VisitorSynchronization : public AllStatic {
10440 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
10442 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
10445 #undef DECLARE_ENUM
10447 static const char* const kTags[kNumberOfSyncTags];
10448 static const char* const kTagNames[kNumberOfSyncTags];
10451 // Abstract base class for visiting, and optionally modifying, the
10452 // pointers contained in Objects. Used in GC and serialization/deserialization.
10453 class ObjectVisitor BASE_EMBEDDED {
10455 virtual ~ObjectVisitor() {}
10457 // Visits a contiguous arrays of pointers in the half-open range
10458 // [start, end). Any or all of the values may be modified on return.
10459 virtual void VisitPointers(Object** start, Object** end) = 0;
10461 // Handy shorthand for visiting a single pointer.
10462 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
10464 // Visit weak next_code_link in Code object.
10465 virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
10467 // To allow lazy clearing of inline caches the visitor has
10468 // a rich interface for iterating over Code objects..
10470 // Visits a code target in the instruction stream.
10471 virtual void VisitCodeTarget(RelocInfo* rinfo);
10473 // Visits a code entry in a JS function.
10474 virtual void VisitCodeEntry(Address entry_address);
10476 // Visits a global property cell reference in the instruction stream.
10477 virtual void VisitCell(RelocInfo* rinfo);
10479 // Visits a runtime entry in the instruction stream.
10480 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
10482 // Visits the resource of an one-byte or two-byte string.
10483 virtual void VisitExternalOneByteString(
10484 v8::String::ExternalOneByteStringResource** resource) {}
10485 virtual void VisitExternalTwoByteString(
10486 v8::String::ExternalStringResource** resource) {}
10488 // Visits a debug call target in the instruction stream.
10489 virtual void VisitDebugTarget(RelocInfo* rinfo);
10491 // Visits the byte sequence in a function's prologue that contains information
10492 // about the code's age.
10493 virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
10495 // Visit pointer embedded into a code object.
10496 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
10498 // Visits an external reference embedded into a code object.
10499 virtual void VisitExternalReference(RelocInfo* rinfo);
10501 // Visits an external reference.
10502 virtual void VisitExternalReference(Address* p) {}
10504 // Visits an (encoded) internal reference.
10505 virtual void VisitInternalReference(RelocInfo* rinfo) {}
10507 // Visits a handle that has an embedder-assigned class ID.
10508 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
10510 // Intended for serialization/deserialization checking: insert, or
10511 // check for the presence of, a tag at this position in the stream.
10512 // Also used for marking up GC roots in heap snapshots.
10513 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
10517 class StructBodyDescriptor : public
10518 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
10520 static inline int SizeOf(Map* map, HeapObject* object) {
10521 return map->instance_size();
10526 // BooleanBit is a helper class for setting and getting a bit in an
10528 class BooleanBit : public AllStatic {
10530 static inline bool get(Smi* smi, int bit_position) {
10531 return get(smi->value(), bit_position);
10534 static inline bool get(int value, int bit_position) {
10535 return (value & (1 << bit_position)) != 0;
10538 static inline Smi* set(Smi* smi, int bit_position, bool v) {
10539 return Smi::FromInt(set(smi->value(), bit_position, v));
10542 static inline int set(int value, int bit_position, bool v) {
10544 value |= (1 << bit_position);
10546 value &= ~(1 << bit_position);
10552 } } // namespace v8::internal
10554 #endif // V8_OBJECTS_H_