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;
1615 // Layout description.
1616 static const int kValueOffset = HeapObject::kHeaderSize;
1617 static const int kSize = kValueOffset + kSimd128Size;
1620 DISALLOW_IMPLICIT_CONSTRUCTORS(Simd128Value);
1624 #define SIMD128_TYPES(V) \
1625 V(Float32x4, float32x4, 4, float) \
1626 V(Int32x4, int32x4, 4, int32_t) \
1627 V(Bool32x4, bool32x4, 4, bool) \
1628 V(Int16x8, int16x8, 8, int16_t) \
1629 V(Bool16x8, bool16x8, 8, bool) \
1630 V(Int8x16, int8x16, 16, int8_t) \
1631 V(Bool8x16, bool8x16, 16, bool)
1633 #define SIMD128_VALUE_CLASS(name, type, lane_count, lane_type) \
1634 class name : public Simd128Value { \
1636 inline lane_type get_lane(int lane) const; \
1637 inline void set_lane(int lane, lane_type value); \
1639 DECLARE_CAST(name) \
1641 DECLARE_PRINTER(name) \
1642 DECLARE_VERIFIER(name) \
1645 DISALLOW_IMPLICIT_CONSTRUCTORS(name); \
1648 SIMD128_TYPES(SIMD128_VALUE_CLASS)
1651 enum EnsureElementsMode {
1652 DONT_ALLOW_DOUBLE_ELEMENTS,
1653 ALLOW_COPIED_DOUBLE_ELEMENTS,
1654 ALLOW_CONVERTED_DOUBLE_ELEMENTS
1658 // Indicator for one component of an AccessorPair.
1659 enum AccessorComponent {
1665 // JSReceiver includes types on which properties can be defined, i.e.,
1666 // JSObject and JSProxy.
1667 class JSReceiver: public HeapObject {
1669 DECLARE_CAST(JSReceiver)
1671 // Implementation of [[HasProperty]], ECMA-262 5th edition, section 8.12.6.
1672 MUST_USE_RESULT static inline Maybe<bool> HasProperty(
1673 Handle<JSReceiver> object, Handle<Name> name);
1674 MUST_USE_RESULT static inline Maybe<bool> HasOwnProperty(Handle<JSReceiver>,
1676 MUST_USE_RESULT static inline Maybe<bool> HasElement(
1677 Handle<JSReceiver> object, uint32_t index);
1678 MUST_USE_RESULT static inline Maybe<bool> HasOwnElement(
1679 Handle<JSReceiver> object, uint32_t index);
1681 // Implementation of [[Delete]], ECMA-262 5th edition, section 8.12.7.
1682 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyOrElement(
1683 Handle<JSReceiver> object, Handle<Name> name,
1684 LanguageMode language_mode = SLOPPY);
1685 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1686 Handle<JSReceiver> object, Handle<Name> name,
1687 LanguageMode language_mode = SLOPPY);
1688 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1689 LookupIterator* it, LanguageMode language_mode);
1690 MUST_USE_RESULT static MaybeHandle<Object> DeleteElement(
1691 Handle<JSReceiver> object, uint32_t index,
1692 LanguageMode language_mode = SLOPPY);
1694 // Tests for the fast common case for property enumeration.
1695 bool IsSimpleEnum();
1697 // Returns the class name ([[Class]] property in the specification).
1698 String* class_name();
1700 // Returns the constructor name (the name (possibly, inferred name) of the
1701 // function that was used to instantiate the object).
1702 String* constructor_name();
1704 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetPropertyAttributes(
1705 Handle<JSReceiver> object, Handle<Name> name);
1706 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1707 GetOwnPropertyAttributes(Handle<JSReceiver> object, Handle<Name> name);
1709 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetElementAttributes(
1710 Handle<JSReceiver> object, uint32_t index);
1711 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1712 GetOwnElementAttributes(Handle<JSReceiver> object, uint32_t index);
1714 MUST_USE_RESULT static Maybe<PropertyAttributes> GetPropertyAttributes(
1715 LookupIterator* it);
1718 static Handle<Object> GetDataProperty(Handle<JSReceiver> object,
1720 static Handle<Object> GetDataProperty(LookupIterator* it);
1723 // Retrieves a permanent object identity hash code. The undefined value might
1724 // be returned in case no hash was created yet.
1725 inline Object* GetIdentityHash();
1727 // Retrieves a permanent object identity hash code. May create and store a
1728 // hash code if needed and none exists.
1729 inline static Handle<Smi> GetOrCreateIdentityHash(
1730 Handle<JSReceiver> object);
1732 enum KeyCollectionType { OWN_ONLY, INCLUDE_PROTOS };
1734 // Computes the enumerable keys for a JSObject. Used for implementing
1735 // "for (n in object) { }".
1736 MUST_USE_RESULT static MaybeHandle<FixedArray> GetKeys(
1737 Handle<JSReceiver> object,
1738 KeyCollectionType type);
1741 DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
1745 // The JSObject describes real heap allocated JavaScript objects with
1747 // Note that the map of JSObject changes during execution to enable inline
1749 class JSObject: public JSReceiver {
1751 // [properties]: Backing storage for properties.
1752 // properties is a FixedArray in the fast case and a Dictionary in the
1754 DECL_ACCESSORS(properties, FixedArray) // Get and set fast properties.
1755 inline void initialize_properties();
1756 inline bool HasFastProperties();
1757 // Gets slow properties for non-global objects.
1758 inline NameDictionary* property_dictionary();
1759 // Gets global object properties.
1760 inline GlobalDictionary* global_dictionary();
1762 // [elements]: The elements (properties with names that are integers).
1764 // Elements can be in two general modes: fast and slow. Each mode
1765 // corrensponds to a set of object representations of elements that
1766 // have something in common.
1768 // In the fast mode elements is a FixedArray and so each element can
1769 // be quickly accessed. This fact is used in the generated code. The
1770 // elements array can have one of three maps in this mode:
1771 // fixed_array_map, sloppy_arguments_elements_map or
1772 // fixed_cow_array_map (for copy-on-write arrays). In the latter case
1773 // the elements array may be shared by a few objects and so before
1774 // writing to any element the array must be copied. Use
1775 // EnsureWritableFastElements in this case.
1777 // In the slow mode the elements is either a NumberDictionary, a
1778 // FixedArray parameter map for a (sloppy) arguments object.
1779 DECL_ACCESSORS(elements, FixedArrayBase)
1780 inline void initialize_elements();
1781 static void ResetElements(Handle<JSObject> object);
1782 static inline void SetMapAndElements(Handle<JSObject> object,
1784 Handle<FixedArrayBase> elements);
1785 inline ElementsKind GetElementsKind();
1786 ElementsAccessor* GetElementsAccessor();
1787 // Returns true if an object has elements of FAST_SMI_ELEMENTS ElementsKind.
1788 inline bool HasFastSmiElements();
1789 // Returns true if an object has elements of FAST_ELEMENTS ElementsKind.
1790 inline bool HasFastObjectElements();
1791 // Returns true if an object has elements of FAST_ELEMENTS or
1792 // FAST_SMI_ONLY_ELEMENTS.
1793 inline bool HasFastSmiOrObjectElements();
1794 // Returns true if an object has any of the fast elements kinds.
1795 inline bool HasFastElements();
1796 // Returns true if an object has elements of FAST_DOUBLE_ELEMENTS
1798 inline bool HasFastDoubleElements();
1799 // Returns true if an object has elements of FAST_HOLEY_*_ELEMENTS
1801 inline bool HasFastHoleyElements();
1802 inline bool HasSloppyArgumentsElements();
1803 inline bool HasDictionaryElements();
1805 inline bool HasFixedTypedArrayElements();
1807 inline bool HasFixedUint8ClampedElements();
1808 inline bool HasFixedArrayElements();
1809 inline bool HasFixedInt8Elements();
1810 inline bool HasFixedUint8Elements();
1811 inline bool HasFixedInt16Elements();
1812 inline bool HasFixedUint16Elements();
1813 inline bool HasFixedInt32Elements();
1814 inline bool HasFixedUint32Elements();
1815 inline bool HasFixedFloat32Elements();
1816 inline bool HasFixedFloat64Elements();
1818 inline bool HasFastArgumentsElements();
1819 inline bool HasSlowArgumentsElements();
1820 inline SeededNumberDictionary* element_dictionary(); // Gets slow elements.
1822 // Requires: HasFastElements().
1823 static Handle<FixedArray> EnsureWritableFastElements(
1824 Handle<JSObject> object);
1826 // Collects elements starting at index 0.
1827 // Undefined values are placed after non-undefined values.
1828 // Returns the number of non-undefined values.
1829 static Handle<Object> PrepareElementsForSort(Handle<JSObject> object,
1831 // As PrepareElementsForSort, but only on objects where elements is
1832 // a dictionary, and it will stay a dictionary. Collates undefined and
1833 // unexisting elements below limit from position zero of the elements.
1834 static Handle<Object> PrepareSlowElementsForSort(Handle<JSObject> object,
1837 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithInterceptor(
1838 LookupIterator* it, Handle<Object> value);
1840 // SetLocalPropertyIgnoreAttributes converts callbacks to fields. We need to
1841 // grant an exemption to ExecutableAccessor callbacks in some cases.
1842 enum ExecutableAccessorInfoHandling { DEFAULT_HANDLING, DONT_FORCE_FIELD };
1844 MUST_USE_RESULT static MaybeHandle<Object> DefineOwnPropertyIgnoreAttributes(
1845 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1846 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1848 MUST_USE_RESULT static MaybeHandle<Object> SetOwnPropertyIgnoreAttributes(
1849 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1850 PropertyAttributes attributes,
1851 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1853 MUST_USE_RESULT static MaybeHandle<Object> SetOwnElementIgnoreAttributes(
1854 Handle<JSObject> object, uint32_t index, Handle<Object> value,
1855 PropertyAttributes attributes,
1856 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1858 // Equivalent to one of the above depending on whether |name| can be converted
1859 // to an array index.
1860 MUST_USE_RESULT static MaybeHandle<Object>
1861 DefinePropertyOrElementIgnoreAttributes(
1862 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1863 PropertyAttributes attributes = NONE,
1864 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1866 // Adds or reconfigures a property to attributes NONE. It will fail when it
1868 MUST_USE_RESULT static Maybe<bool> CreateDataProperty(LookupIterator* it,
1869 Handle<Object> value);
1871 static void AddProperty(Handle<JSObject> object, Handle<Name> name,
1872 Handle<Object> value, PropertyAttributes attributes);
1874 MUST_USE_RESULT static MaybeHandle<Object> AddDataElement(
1875 Handle<JSObject> receiver, uint32_t index, Handle<Object> value,
1876 PropertyAttributes attributes);
1878 // Extend the receiver with a single fast property appeared first in the
1879 // passed map. This also extends the property backing store if necessary.
1880 static void AllocateStorageForMap(Handle<JSObject> object, Handle<Map> map);
1882 // Migrates the given object to a map whose field representations are the
1883 // lowest upper bound of all known representations for that field.
1884 static void MigrateInstance(Handle<JSObject> instance);
1886 // Migrates the given object only if the target map is already available,
1887 // or returns false if such a map is not yet available.
1888 static bool TryMigrateInstance(Handle<JSObject> instance);
1890 // Sets the property value in a normalized object given (key, value, details).
1891 // Handles the special representation of JS global objects.
1892 static void SetNormalizedProperty(Handle<JSObject> object, Handle<Name> name,
1893 Handle<Object> value,
1894 PropertyDetails details);
1895 static void SetDictionaryElement(Handle<JSObject> object, uint32_t index,
1896 Handle<Object> value,
1897 PropertyAttributes attributes);
1898 static void SetDictionaryArgumentsElement(Handle<JSObject> object,
1900 Handle<Object> value,
1901 PropertyAttributes attributes);
1903 static void OptimizeAsPrototype(Handle<JSObject> object,
1904 PrototypeOptimizationMode mode);
1905 static void ReoptimizeIfPrototype(Handle<JSObject> object);
1906 static void LazyRegisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1907 static bool RegisterPrototypeUserIfNotRegistered(Handle<JSObject> prototype,
1908 Handle<HeapObject> user,
1910 static bool UnregisterPrototypeUser(Handle<JSObject> prototype,
1911 Handle<HeapObject> user);
1912 static void InvalidatePrototypeChains(Map* map);
1914 // Retrieve interceptors.
1915 InterceptorInfo* GetNamedInterceptor();
1916 InterceptorInfo* GetIndexedInterceptor();
1918 // Used from JSReceiver.
1919 MUST_USE_RESULT static Maybe<PropertyAttributes>
1920 GetPropertyAttributesWithInterceptor(LookupIterator* it);
1921 MUST_USE_RESULT static Maybe<PropertyAttributes>
1922 GetPropertyAttributesWithFailedAccessCheck(LookupIterator* it);
1924 // Retrieves an AccessorPair property from the given object. Might return
1925 // undefined if the property doesn't exist or is of a different kind.
1926 MUST_USE_RESULT static MaybeHandle<Object> GetAccessor(
1927 Handle<JSObject> object,
1929 AccessorComponent component);
1931 // Defines an AccessorPair property on the given object.
1932 // TODO(mstarzinger): Rename to SetAccessor().
1933 static MaybeHandle<Object> DefineAccessor(Handle<JSObject> object,
1935 Handle<Object> getter,
1936 Handle<Object> setter,
1937 PropertyAttributes attributes);
1939 // Defines an AccessorInfo property on the given object.
1940 MUST_USE_RESULT static MaybeHandle<Object> SetAccessor(
1941 Handle<JSObject> object,
1942 Handle<AccessorInfo> info);
1944 // The result must be checked first for exceptions. If there's no exception,
1945 // the output parameter |done| indicates whether the interceptor has a result
1947 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithInterceptor(
1948 LookupIterator* it, bool* done);
1950 // Accessors for hidden properties object.
1952 // Hidden properties are not own properties of the object itself.
1953 // Instead they are stored in an auxiliary structure kept as an own
1954 // property with a special name Heap::hidden_string(). But if the
1955 // receiver is a JSGlobalProxy then the auxiliary object is a property
1956 // of its prototype, and if it's a detached proxy, then you can't have
1957 // hidden properties.
1959 // Sets a hidden property on this object. Returns this object if successful,
1960 // undefined if called on a detached proxy.
1961 static Handle<Object> SetHiddenProperty(Handle<JSObject> object,
1963 Handle<Object> value);
1964 // Gets the value of a hidden property with the given key. Returns the hole
1965 // if the property doesn't exist (or if called on a detached proxy),
1966 // otherwise returns the value set for the key.
1967 Object* GetHiddenProperty(Handle<Name> key);
1968 // Deletes a hidden property. Deleting a non-existing property is
1969 // considered successful.
1970 static void DeleteHiddenProperty(Handle<JSObject> object,
1972 // Returns true if the object has a property with the hidden string as name.
1973 static bool HasHiddenProperties(Handle<JSObject> object);
1975 static void SetIdentityHash(Handle<JSObject> object, Handle<Smi> hash);
1977 static void ValidateElements(Handle<JSObject> object);
1979 // Makes sure that this object can contain HeapObject as elements.
1980 static inline void EnsureCanContainHeapObjectElements(Handle<JSObject> obj);
1982 // Makes sure that this object can contain the specified elements.
1983 static inline void EnsureCanContainElements(
1984 Handle<JSObject> object,
1987 EnsureElementsMode mode);
1988 static inline void EnsureCanContainElements(
1989 Handle<JSObject> object,
1990 Handle<FixedArrayBase> elements,
1992 EnsureElementsMode mode);
1993 static void EnsureCanContainElements(
1994 Handle<JSObject> object,
1995 Arguments* arguments,
1998 EnsureElementsMode mode);
2000 // Would we convert a fast elements array to dictionary mode given
2001 // an access at key?
2002 bool WouldConvertToSlowElements(uint32_t index);
2004 // Computes the new capacity when expanding the elements of a JSObject.
2005 static uint32_t NewElementsCapacity(uint32_t old_capacity) {
2006 // (old_capacity + 50%) + 16
2007 return old_capacity + (old_capacity >> 1) + 16;
2010 // These methods do not perform access checks!
2011 static void UpdateAllocationSite(Handle<JSObject> object,
2012 ElementsKind to_kind);
2014 // Lookup interceptors are used for handling properties controlled by host
2016 inline bool HasNamedInterceptor();
2017 inline bool HasIndexedInterceptor();
2019 // Computes the enumerable keys from interceptors. Used for debug mirrors and
2020 // by JSReceiver::GetKeys.
2021 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForNamedInterceptor(
2022 Handle<JSObject> object,
2023 Handle<JSReceiver> receiver);
2024 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForIndexedInterceptor(
2025 Handle<JSObject> object,
2026 Handle<JSReceiver> receiver);
2028 // Support functions for v8 api (needed for correct interceptor behavior).
2029 MUST_USE_RESULT static Maybe<bool> HasRealNamedProperty(
2030 Handle<JSObject> object, Handle<Name> name);
2031 MUST_USE_RESULT static Maybe<bool> HasRealElementProperty(
2032 Handle<JSObject> object, uint32_t index);
2033 MUST_USE_RESULT static Maybe<bool> HasRealNamedCallbackProperty(
2034 Handle<JSObject> object, Handle<Name> name);
2036 // Get the header size for a JSObject. Used to compute the index of
2037 // internal fields as well as the number of internal fields.
2038 inline int GetHeaderSize();
2040 inline int GetInternalFieldCount();
2041 inline int GetInternalFieldOffset(int index);
2042 inline Object* GetInternalField(int index);
2043 inline void SetInternalField(int index, Object* value);
2044 inline void SetInternalField(int index, Smi* value);
2046 // Returns the number of properties on this object filtering out properties
2047 // with the specified attributes (ignoring interceptors).
2048 int NumberOfOwnProperties(PropertyAttributes filter = NONE);
2049 // Fill in details for properties into storage starting at the specified
2050 // index. Returns the number of properties added.
2051 int GetOwnPropertyNames(FixedArray* storage, int index,
2052 PropertyAttributes filter = NONE);
2054 // Returns the number of properties on this object filtering out properties
2055 // with the specified attributes (ignoring interceptors).
2056 int NumberOfOwnElements(PropertyAttributes filter);
2057 // Returns the number of enumerable elements (ignoring interceptors).
2058 int NumberOfEnumElements();
2059 // Returns the number of elements on this object filtering out elements
2060 // with the specified attributes (ignoring interceptors).
2061 int GetOwnElementKeys(FixedArray* storage, PropertyAttributes filter);
2062 // Count and fill in the enumerable elements into storage.
2063 // (storage->length() == NumberOfEnumElements()).
2064 // If storage is NULL, will count the elements without adding
2065 // them to any storage.
2066 // Returns the number of enumerable elements.
2067 int GetEnumElementKeys(FixedArray* storage);
2069 static Handle<FixedArray> GetEnumPropertyKeys(Handle<JSObject> object,
2072 // Returns a new map with all transitions dropped from the object's current
2073 // map and the ElementsKind set.
2074 static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
2075 ElementsKind to_kind);
2076 static void TransitionElementsKind(Handle<JSObject> object,
2077 ElementsKind to_kind);
2079 // Always use this to migrate an object to a new map.
2080 // |expected_additional_properties| is only used for fast-to-slow transitions
2081 // and ignored otherwise.
2082 static void MigrateToMap(Handle<JSObject> object, Handle<Map> new_map,
2083 int expected_additional_properties = 0);
2085 // Convert the object to use the canonical dictionary
2086 // representation. If the object is expected to have additional properties
2087 // added this number can be indicated to have the backing store allocated to
2088 // an initial capacity for holding these properties.
2089 static void NormalizeProperties(Handle<JSObject> object,
2090 PropertyNormalizationMode mode,
2091 int expected_additional_properties,
2092 const char* reason);
2094 // Convert and update the elements backing store to be a
2095 // SeededNumberDictionary dictionary. Returns the backing after conversion.
2096 static Handle<SeededNumberDictionary> NormalizeElements(
2097 Handle<JSObject> object);
2099 void RequireSlowElements(SeededNumberDictionary* dictionary);
2101 // Transform slow named properties to fast variants.
2102 static void MigrateSlowToFast(Handle<JSObject> object,
2103 int unused_property_fields, const char* reason);
2105 inline bool IsUnboxedDoubleField(FieldIndex index);
2107 // Access fast-case object properties at index.
2108 static Handle<Object> FastPropertyAt(Handle<JSObject> object,
2109 Representation representation,
2111 inline Object* RawFastPropertyAt(FieldIndex index);
2112 inline double RawFastDoublePropertyAt(FieldIndex index);
2114 inline void FastPropertyAtPut(FieldIndex index, Object* value);
2115 inline void RawFastPropertyAtPut(FieldIndex index, Object* value);
2116 inline void RawFastDoublePropertyAtPut(FieldIndex index, double value);
2117 inline void WriteToField(int descriptor, Object* value);
2119 // Access to in object properties.
2120 inline int GetInObjectPropertyOffset(int index);
2121 inline Object* InObjectPropertyAt(int index);
2122 inline Object* InObjectPropertyAtPut(int index,
2124 WriteBarrierMode mode
2125 = UPDATE_WRITE_BARRIER);
2127 // Set the object's prototype (only JSReceiver and null are allowed values).
2128 MUST_USE_RESULT static MaybeHandle<Object> SetPrototype(
2129 Handle<JSObject> object, Handle<Object> value, bool from_javascript);
2131 // Initializes the body after properties slot, properties slot is
2132 // initialized by set_properties. Fill the pre-allocated fields with
2133 // pre_allocated_value and the rest with filler_value.
2134 // Note: this call does not update write barrier, the caller is responsible
2135 // to ensure that |filler_value| can be collected without WB here.
2136 inline void InitializeBody(Map* map,
2137 Object* pre_allocated_value,
2138 Object* filler_value);
2140 // Check whether this object references another object
2141 bool ReferencesObject(Object* obj);
2143 // Disalow further properties to be added to the oject.
2144 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensions(
2145 Handle<JSObject> object);
2147 bool IsExtensible();
2150 MUST_USE_RESULT static MaybeHandle<Object> Seal(Handle<JSObject> object);
2152 // ES5 Object.freeze
2153 MUST_USE_RESULT static MaybeHandle<Object> Freeze(Handle<JSObject> object);
2155 // Called the first time an object is observed with ES7 Object.observe.
2156 static void SetObserved(Handle<JSObject> object);
2159 enum DeepCopyHints { kNoHints = 0, kObjectIsShallow = 1 };
2161 MUST_USE_RESULT static MaybeHandle<JSObject> DeepCopy(
2162 Handle<JSObject> object,
2163 AllocationSiteUsageContext* site_context,
2164 DeepCopyHints hints = kNoHints);
2165 MUST_USE_RESULT static MaybeHandle<JSObject> DeepWalk(
2166 Handle<JSObject> object,
2167 AllocationSiteCreationContext* site_context);
2169 DECLARE_CAST(JSObject)
2171 // Dispatched behavior.
2172 void JSObjectShortPrint(StringStream* accumulator);
2173 DECLARE_PRINTER(JSObject)
2174 DECLARE_VERIFIER(JSObject)
2176 void PrintProperties(std::ostream& os); // NOLINT
2177 void PrintElements(std::ostream& os); // NOLINT
2179 #if defined(DEBUG) || defined(OBJECT_PRINT)
2180 void PrintTransitions(std::ostream& os); // NOLINT
2183 static void PrintElementsTransition(
2184 FILE* file, Handle<JSObject> object,
2185 ElementsKind from_kind, Handle<FixedArrayBase> from_elements,
2186 ElementsKind to_kind, Handle<FixedArrayBase> to_elements);
2188 void PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map);
2191 // Structure for collecting spill information about JSObjects.
2192 class SpillInformation {
2196 int number_of_objects_;
2197 int number_of_objects_with_fast_properties_;
2198 int number_of_objects_with_fast_elements_;
2199 int number_of_fast_used_fields_;
2200 int number_of_fast_unused_fields_;
2201 int number_of_slow_used_properties_;
2202 int number_of_slow_unused_properties_;
2203 int number_of_fast_used_elements_;
2204 int number_of_fast_unused_elements_;
2205 int number_of_slow_used_elements_;
2206 int number_of_slow_unused_elements_;
2209 void IncrementSpillStatistics(SpillInformation* info);
2213 // If a GC was caused while constructing this object, the elements pointer
2214 // may point to a one pointer filler map. The object won't be rooted, but
2215 // our heap verification code could stumble across it.
2216 bool ElementsAreSafeToExamine();
2219 Object* SlowReverseLookup(Object* value);
2221 // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2222 // Also maximal value of JSArray's length property.
2223 static const uint32_t kMaxElementCount = 0xffffffffu;
2225 // Constants for heuristics controlling conversion of fast elements
2226 // to slow elements.
2228 // Maximal gap that can be introduced by adding an element beyond
2229 // the current elements length.
2230 static const uint32_t kMaxGap = 1024;
2232 // Maximal length of fast elements array that won't be checked for
2233 // being dense enough on expansion.
2234 static const int kMaxUncheckedFastElementsLength = 5000;
2236 // Same as above but for old arrays. This limit is more strict. We
2237 // don't want to be wasteful with long lived objects.
2238 static const int kMaxUncheckedOldFastElementsLength = 500;
2240 // Note that Page::kMaxRegularHeapObjectSize puts a limit on
2241 // permissible values (see the DCHECK in heap.cc).
2242 static const int kInitialMaxFastElementArray = 100000;
2244 // This constant applies only to the initial map of "global.Object" and
2245 // not to arbitrary other JSObject maps.
2246 static const int kInitialGlobalObjectUnusedPropertiesCount = 4;
2248 static const int kMaxInstanceSize = 255 * kPointerSize;
2249 // When extending the backing storage for property values, we increase
2250 // its size by more than the 1 entry necessary, so sequentially adding fields
2251 // to the same object requires fewer allocations and copies.
2252 static const int kFieldsAdded = 3;
2254 // Layout description.
2255 static const int kPropertiesOffset = HeapObject::kHeaderSize;
2256 static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2257 static const int kHeaderSize = kElementsOffset + kPointerSize;
2259 STATIC_ASSERT(kHeaderSize == Internals::kJSObjectHeaderSize);
2261 class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2263 static inline int SizeOf(Map* map, HeapObject* object);
2266 Context* GetCreationContext();
2268 // Enqueue change record for Object.observe. May cause GC.
2269 MUST_USE_RESULT static MaybeHandle<Object> EnqueueChangeRecord(
2270 Handle<JSObject> object, const char* type, Handle<Name> name,
2271 Handle<Object> old_value);
2273 // Gets the number of currently used elements.
2274 int GetFastElementsUsage();
2276 // Deletes an existing named property in a normalized object.
2277 static void DeleteNormalizedProperty(Handle<JSObject> object,
2278 Handle<Name> name, int entry);
2280 static bool AllCanRead(LookupIterator* it);
2281 static bool AllCanWrite(LookupIterator* it);
2284 friend class JSReceiver;
2285 friend class Object;
2287 static void MigrateFastToFast(Handle<JSObject> object, Handle<Map> new_map);
2288 static void MigrateFastToSlow(Handle<JSObject> object,
2289 Handle<Map> new_map,
2290 int expected_additional_properties);
2292 // Used from Object::GetProperty().
2293 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithFailedAccessCheck(
2294 LookupIterator* it);
2296 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithFailedAccessCheck(
2297 LookupIterator* it, Handle<Object> value);
2299 // Add a property to a slow-case object.
2300 static void AddSlowProperty(Handle<JSObject> object,
2302 Handle<Object> value,
2303 PropertyAttributes attributes);
2305 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithInterceptor(
2306 LookupIterator* it);
2308 bool ReferencesObjectFromElements(FixedArray* elements,
2312 // Return the hash table backing store or the inline stored identity hash,
2313 // whatever is found.
2314 MUST_USE_RESULT Object* GetHiddenPropertiesHashTable();
2316 // Return the hash table backing store for hidden properties. If there is no
2317 // backing store, allocate one.
2318 static Handle<ObjectHashTable> GetOrCreateHiddenPropertiesHashtable(
2319 Handle<JSObject> object);
2321 // Set the hidden property backing store to either a hash table or
2322 // the inline-stored identity hash.
2323 static Handle<Object> SetHiddenPropertiesHashTable(
2324 Handle<JSObject> object,
2325 Handle<Object> value);
2327 MUST_USE_RESULT Object* GetIdentityHash();
2329 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSObject> object);
2331 static Handle<SeededNumberDictionary> GetNormalizedElementDictionary(
2332 Handle<JSObject> object, Handle<FixedArrayBase> elements);
2334 // Helper for fast versions of preventExtensions, seal, and freeze.
2335 // attrs is one of NONE, SEALED, or FROZEN (depending on the operation).
2336 template <PropertyAttributes attrs>
2337 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensionsWithTransition(
2338 Handle<JSObject> object);
2340 DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
2344 // Common superclass for FixedArrays that allow implementations to share
2345 // common accessors and some code paths.
2346 class FixedArrayBase: public HeapObject {
2348 // [length]: length of the array.
2349 inline int length() const;
2350 inline void set_length(int value);
2352 // Get and set the length using acquire loads and release stores.
2353 inline int synchronized_length() const;
2354 inline void synchronized_set_length(int value);
2356 DECLARE_CAST(FixedArrayBase)
2358 // Layout description.
2359 // Length is smi tagged when it is stored.
2360 static const int kLengthOffset = HeapObject::kHeaderSize;
2361 static const int kHeaderSize = kLengthOffset + kPointerSize;
2365 class FixedDoubleArray;
2366 class IncrementalMarking;
2369 // FixedArray describes fixed-sized arrays with element type Object*.
2370 class FixedArray: public FixedArrayBase {
2372 // Setter and getter for elements.
2373 inline Object* get(int index) const;
2374 void SetValue(uint32_t index, Object* value);
2375 static inline Handle<Object> get(Handle<FixedArray> array, int index);
2376 // Setter that uses write barrier.
2377 inline void set(int index, Object* value);
2378 inline bool is_the_hole(int index);
2380 // Setter that doesn't need write barrier.
2381 inline void set(int index, Smi* value);
2382 // Setter with explicit barrier mode.
2383 inline void set(int index, Object* value, WriteBarrierMode mode);
2385 // Setters for frequently used oddballs located in old space.
2386 inline void set_undefined(int index);
2387 inline void set_null(int index);
2388 inline void set_the_hole(int index);
2390 inline Object** GetFirstElementAddress();
2391 inline bool ContainsOnlySmisOrHoles();
2393 // Gives access to raw memory which stores the array's data.
2394 inline Object** data_start();
2396 inline void FillWithHoles(int from, int to);
2398 // Shrink length and insert filler objects.
2399 void Shrink(int length);
2402 static Handle<FixedArray> CopySize(Handle<FixedArray> array,
2404 PretenureFlag pretenure = NOT_TENURED);
2406 enum KeyFilter { ALL_KEYS, NON_SYMBOL_KEYS };
2408 // Add the elements of a JSArray to this FixedArray.
2409 MUST_USE_RESULT static MaybeHandle<FixedArray> AddKeysFromArrayLike(
2410 Handle<FixedArray> content, Handle<JSObject> array,
2411 KeyFilter filter = ALL_KEYS);
2413 // Computes the union of keys and return the result.
2414 // Used for implementing "for (n in object) { }"
2415 MUST_USE_RESULT static MaybeHandle<FixedArray> UnionOfKeys(
2416 Handle<FixedArray> first,
2417 Handle<FixedArray> second);
2419 // Copy a sub array from the receiver to dest.
2420 void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
2422 // Garbage collection support.
2423 static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
2425 // Code Generation support.
2426 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2428 // Garbage collection support.
2429 Object** RawFieldOfElementAt(int index) {
2430 return HeapObject::RawField(this, OffsetOfElementAt(index));
2433 DECLARE_CAST(FixedArray)
2435 // Maximal allowed size, in bytes, of a single FixedArray.
2436 // Prevents overflowing size computations, as well as extreme memory
2438 static const int kMaxSize = 128 * MB * kPointerSize;
2439 // Maximally allowed length of a FixedArray.
2440 static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
2442 // Dispatched behavior.
2443 DECLARE_PRINTER(FixedArray)
2444 DECLARE_VERIFIER(FixedArray)
2446 // Checks if two FixedArrays have identical contents.
2447 bool IsEqualTo(FixedArray* other);
2450 // Swap two elements in a pair of arrays. If this array and the
2451 // numbers array are the same object, the elements are only swapped
2453 void SwapPairs(FixedArray* numbers, int i, int j);
2455 // Sort prefix of this array and the numbers array as pairs wrt. the
2456 // numbers. If the numbers array and the this array are the same
2457 // object, the prefix of this array is sorted.
2458 void SortPairs(FixedArray* numbers, uint32_t len);
2460 class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
2462 static inline int SizeOf(Map* map, HeapObject* object) {
2464 reinterpret_cast<FixedArray*>(object)->synchronized_length());
2469 // Set operation on FixedArray without using write barriers. Can
2470 // only be used for storing old space objects or smis.
2471 static inline void NoWriteBarrierSet(FixedArray* array,
2475 // Set operation on FixedArray without incremental write barrier. Can
2476 // only be used if the object is guaranteed to be white (whiteness witness
2478 static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
2483 STATIC_ASSERT(kHeaderSize == Internals::kFixedArrayHeaderSize);
2485 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
2489 // FixedDoubleArray describes fixed-sized arrays with element type double.
2490 class FixedDoubleArray: public FixedArrayBase {
2492 // Setter and getter for elements.
2493 inline double get_scalar(int index);
2494 inline uint64_t get_representation(int index);
2495 static inline Handle<Object> get(Handle<FixedDoubleArray> array, int index);
2496 // This accessor has to get a Number as |value|.
2497 void SetValue(uint32_t index, Object* value);
2498 inline void set(int index, double value);
2499 inline void set_the_hole(int index);
2501 // Checking for the hole.
2502 inline bool is_the_hole(int index);
2504 // Garbage collection support.
2505 inline static int SizeFor(int length) {
2506 return kHeaderSize + length * kDoubleSize;
2509 // Gives access to raw memory which stores the array's data.
2510 inline double* data_start();
2512 inline void FillWithHoles(int from, int to);
2514 // Code Generation support.
2515 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2517 DECLARE_CAST(FixedDoubleArray)
2519 // Maximal allowed size, in bytes, of a single FixedDoubleArray.
2520 // Prevents overflowing size computations, as well as extreme memory
2522 static const int kMaxSize = 512 * MB;
2523 // Maximally allowed length of a FixedArray.
2524 static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
2526 // Dispatched behavior.
2527 DECLARE_PRINTER(FixedDoubleArray)
2528 DECLARE_VERIFIER(FixedDoubleArray)
2531 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
2535 class WeakFixedArray : public FixedArray {
2537 enum SearchForDuplicates { kAlwaysAdd, kAddIfNotFound };
2539 // If |maybe_array| is not a WeakFixedArray, a fresh one will be allocated.
2540 static Handle<WeakFixedArray> Add(
2541 Handle<Object> maybe_array, Handle<HeapObject> value,
2542 SearchForDuplicates search_for_duplicates = kAlwaysAdd,
2543 bool* was_present = NULL);
2545 // Returns true if an entry was found and removed.
2546 bool Remove(Handle<HeapObject> value);
2550 inline Object* Get(int index) const;
2551 inline void Clear(int index);
2552 inline int Length() const;
2554 inline bool IsEmptySlot(int index) const;
2555 static Object* Empty() { return Smi::FromInt(0); }
2557 DECLARE_CAST(WeakFixedArray)
2560 static const int kLastUsedIndexIndex = 0;
2561 static const int kFirstIndex = 1;
2563 static Handle<WeakFixedArray> Allocate(
2564 Isolate* isolate, int size, Handle<WeakFixedArray> initialize_from);
2566 static void Set(Handle<WeakFixedArray> array, int index,
2567 Handle<HeapObject> value);
2568 inline void clear(int index);
2570 inline int last_used_index() const;
2571 inline void set_last_used_index(int index);
2573 // Disallow inherited setters.
2574 void set(int index, Smi* value);
2575 void set(int index, Object* value);
2576 void set(int index, Object* value, WriteBarrierMode mode);
2577 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakFixedArray);
2581 // Generic array grows dynamically with O(1) amortized insertion.
2582 class ArrayList : public FixedArray {
2586 // Use this if GC can delete elements from the array.
2587 kReloadLengthAfterAllocation,
2589 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj,
2590 AddMode mode = kNone);
2591 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj1,
2592 Handle<Object> obj2, AddMode = kNone);
2593 inline int Length();
2594 inline void SetLength(int length);
2595 inline Object* Get(int index);
2596 inline Object** Slot(int index);
2597 inline void Set(int index, Object* obj);
2598 inline void Clear(int index, Object* undefined);
2599 DECLARE_CAST(ArrayList)
2602 static Handle<ArrayList> EnsureSpace(Handle<ArrayList> array, int length);
2603 static const int kLengthIndex = 0;
2604 static const int kFirstIndex = 1;
2605 DISALLOW_IMPLICIT_CONSTRUCTORS(ArrayList);
2609 // DescriptorArrays are fixed arrays used to hold instance descriptors.
2610 // The format of the these objects is:
2611 // [0]: Number of descriptors
2612 // [1]: Either Smi(0) if uninitialized, or a pointer to small fixed array:
2613 // [0]: pointer to fixed array with enum cache
2614 // [1]: either Smi(0) or pointer to fixed array with indices
2616 // [2 + number of descriptors * kDescriptorSize]: start of slack
2617 class DescriptorArray: public FixedArray {
2619 // Returns true for both shared empty_descriptor_array and for smis, which the
2620 // map uses to encode additional bit fields when the descriptor array is not
2622 inline bool IsEmpty();
2624 // Returns the number of descriptors in the array.
2625 int number_of_descriptors() {
2626 DCHECK(length() >= kFirstIndex || IsEmpty());
2628 return len == 0 ? 0 : Smi::cast(get(kDescriptorLengthIndex))->value();
2631 int number_of_descriptors_storage() {
2633 return len == 0 ? 0 : (len - kFirstIndex) / kDescriptorSize;
2636 int NumberOfSlackDescriptors() {
2637 return number_of_descriptors_storage() - number_of_descriptors();
2640 inline void SetNumberOfDescriptors(int number_of_descriptors);
2641 inline int number_of_entries() { return number_of_descriptors(); }
2643 bool HasEnumCache() {
2644 return !IsEmpty() && !get(kEnumCacheIndex)->IsSmi();
2647 void CopyEnumCacheFrom(DescriptorArray* array) {
2648 set(kEnumCacheIndex, array->get(kEnumCacheIndex));
2651 FixedArray* GetEnumCache() {
2652 DCHECK(HasEnumCache());
2653 FixedArray* bridge = FixedArray::cast(get(kEnumCacheIndex));
2654 return FixedArray::cast(bridge->get(kEnumCacheBridgeCacheIndex));
2657 bool HasEnumIndicesCache() {
2658 if (IsEmpty()) return false;
2659 Object* object = get(kEnumCacheIndex);
2660 if (object->IsSmi()) return false;
2661 FixedArray* bridge = FixedArray::cast(object);
2662 return !bridge->get(kEnumCacheBridgeIndicesCacheIndex)->IsSmi();
2665 FixedArray* GetEnumIndicesCache() {
2666 DCHECK(HasEnumIndicesCache());
2667 FixedArray* bridge = FixedArray::cast(get(kEnumCacheIndex));
2668 return FixedArray::cast(bridge->get(kEnumCacheBridgeIndicesCacheIndex));
2671 Object** GetEnumCacheSlot() {
2672 DCHECK(HasEnumCache());
2673 return HeapObject::RawField(reinterpret_cast<HeapObject*>(this),
2677 void ClearEnumCache();
2679 // Initialize or change the enum cache,
2680 // using the supplied storage for the small "bridge".
2681 void SetEnumCache(FixedArray* bridge_storage,
2682 FixedArray* new_cache,
2683 Object* new_index_cache);
2685 bool CanHoldValue(int descriptor, Object* value);
2687 // Accessors for fetching instance descriptor at descriptor number.
2688 inline Name* GetKey(int descriptor_number);
2689 inline Object** GetKeySlot(int descriptor_number);
2690 inline Object* GetValue(int descriptor_number);
2691 inline void SetValue(int descriptor_number, Object* value);
2692 inline Object** GetValueSlot(int descriptor_number);
2693 static inline int GetValueOffset(int descriptor_number);
2694 inline Object** GetDescriptorStartSlot(int descriptor_number);
2695 inline Object** GetDescriptorEndSlot(int descriptor_number);
2696 inline PropertyDetails GetDetails(int descriptor_number);
2697 inline PropertyType GetType(int descriptor_number);
2698 inline int GetFieldIndex(int descriptor_number);
2699 inline HeapType* GetFieldType(int descriptor_number);
2700 inline Object* GetConstant(int descriptor_number);
2701 inline Object* GetCallbacksObject(int descriptor_number);
2702 inline AccessorDescriptor* GetCallbacks(int descriptor_number);
2704 inline Name* GetSortedKey(int descriptor_number);
2705 inline int GetSortedKeyIndex(int descriptor_number);
2706 inline void SetSortedKey(int pointer, int descriptor_number);
2707 inline void SetRepresentation(int descriptor_number,
2708 Representation representation);
2710 // Accessor for complete descriptor.
2711 inline void Get(int descriptor_number, Descriptor* desc);
2712 inline void Set(int descriptor_number, Descriptor* desc);
2713 void Replace(int descriptor_number, Descriptor* descriptor);
2715 // Append automatically sets the enumeration index. This should only be used
2716 // to add descriptors in bulk at the end, followed by sorting the descriptor
2718 inline void Append(Descriptor* desc);
2720 static Handle<DescriptorArray> CopyUpTo(Handle<DescriptorArray> desc,
2721 int enumeration_index,
2724 static Handle<DescriptorArray> CopyUpToAddAttributes(
2725 Handle<DescriptorArray> desc,
2726 int enumeration_index,
2727 PropertyAttributes attributes,
2730 // Sort the instance descriptors by the hash codes of their keys.
2733 // Search the instance descriptors for given name.
2734 INLINE(int Search(Name* name, int number_of_own_descriptors));
2736 // As the above, but uses DescriptorLookupCache and updates it when
2738 INLINE(int SearchWithCache(Name* name, Map* map));
2740 // Allocates a DescriptorArray, but returns the singleton
2741 // empty descriptor array object if number_of_descriptors is 0.
2742 static Handle<DescriptorArray> Allocate(Isolate* isolate,
2743 int number_of_descriptors,
2746 DECLARE_CAST(DescriptorArray)
2748 // Constant for denoting key was not found.
2749 static const int kNotFound = -1;
2751 static const int kDescriptorLengthIndex = 0;
2752 static const int kEnumCacheIndex = 1;
2753 static const int kFirstIndex = 2;
2755 // The length of the "bridge" to the enum cache.
2756 static const int kEnumCacheBridgeLength = 2;
2757 static const int kEnumCacheBridgeCacheIndex = 0;
2758 static const int kEnumCacheBridgeIndicesCacheIndex = 1;
2760 // Layout description.
2761 static const int kDescriptorLengthOffset = FixedArray::kHeaderSize;
2762 static const int kEnumCacheOffset = kDescriptorLengthOffset + kPointerSize;
2763 static const int kFirstOffset = kEnumCacheOffset + kPointerSize;
2765 // Layout description for the bridge array.
2766 static const int kEnumCacheBridgeCacheOffset = FixedArray::kHeaderSize;
2768 // Layout of descriptor.
2769 static const int kDescriptorKey = 0;
2770 static const int kDescriptorDetails = 1;
2771 static const int kDescriptorValue = 2;
2772 static const int kDescriptorSize = 3;
2774 #if defined(DEBUG) || defined(OBJECT_PRINT)
2775 // For our gdb macros, we should perhaps change these in the future.
2778 // Print all the descriptors.
2779 void PrintDescriptors(std::ostream& os); // NOLINT
2783 // Is the descriptor array sorted and without duplicates?
2784 bool IsSortedNoDuplicates(int valid_descriptors = -1);
2786 // Is the descriptor array consistent with the back pointers in targets?
2787 bool IsConsistentWithBackPointers(Map* current_map);
2789 // Are two DescriptorArrays equal?
2790 bool IsEqualTo(DescriptorArray* other);
2793 // Returns the fixed array length required to hold number_of_descriptors
2795 static int LengthFor(int number_of_descriptors) {
2796 return ToKeyIndex(number_of_descriptors);
2800 // WhitenessWitness is used to prove that a descriptor array is white
2801 // (unmarked), so incremental write barriers can be skipped because the
2802 // marking invariant cannot be broken and slots pointing into evacuation
2803 // candidates will be discovered when the object is scanned. A witness is
2804 // always stack-allocated right after creating an array. By allocating a
2805 // witness, incremental marking is globally disabled. The witness is then
2806 // passed along wherever needed to statically prove that the array is known to
2808 class WhitenessWitness {
2810 inline explicit WhitenessWitness(DescriptorArray* array);
2811 inline ~WhitenessWitness();
2814 IncrementalMarking* marking_;
2817 // An entry in a DescriptorArray, represented as an (array, index) pair.
2820 inline explicit Entry(DescriptorArray* descs, int index) :
2821 descs_(descs), index_(index) { }
2823 inline PropertyType type() { return descs_->GetType(index_); }
2824 inline Object* GetCallbackObject() { return descs_->GetValue(index_); }
2827 DescriptorArray* descs_;
2831 // Conversion from descriptor number to array indices.
2832 static int ToKeyIndex(int descriptor_number) {
2833 return kFirstIndex +
2834 (descriptor_number * kDescriptorSize) +
2838 static int ToDetailsIndex(int descriptor_number) {
2839 return kFirstIndex +
2840 (descriptor_number * kDescriptorSize) +
2844 static int ToValueIndex(int descriptor_number) {
2845 return kFirstIndex +
2846 (descriptor_number * kDescriptorSize) +
2850 // Transfer a complete descriptor from the src descriptor array to this
2851 // descriptor array.
2852 void CopyFrom(int index, DescriptorArray* src, const WhitenessWitness&);
2854 inline void Set(int descriptor_number,
2856 const WhitenessWitness&);
2858 // Swap first and second descriptor.
2859 inline void SwapSortedKeys(int first, int second);
2861 DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
2865 enum SearchMode { ALL_ENTRIES, VALID_ENTRIES };
2867 template <SearchMode search_mode, typename T>
2868 inline int Search(T* array, Name* name, int valid_entries = 0,
2869 int* out_insertion_index = NULL);
2872 // HashTable is a subclass of FixedArray that implements a hash table
2873 // that uses open addressing and quadratic probing.
2875 // In order for the quadratic probing to work, elements that have not
2876 // yet been used and elements that have been deleted are
2877 // distinguished. Probing continues when deleted elements are
2878 // encountered and stops when unused elements are encountered.
2880 // - Elements with key == undefined have not been used yet.
2881 // - Elements with key == the_hole have been deleted.
2883 // The hash table class is parameterized with a Shape and a Key.
2884 // Shape must be a class with the following interface:
2885 // class ExampleShape {
2887 // // Tells whether key matches other.
2888 // static bool IsMatch(Key key, Object* other);
2889 // // Returns the hash value for key.
2890 // static uint32_t Hash(Key key);
2891 // // Returns the hash value for object.
2892 // static uint32_t HashForObject(Key key, Object* object);
2893 // // Convert key to an object.
2894 // static inline Handle<Object> AsHandle(Isolate* isolate, Key key);
2895 // // The prefix size indicates number of elements in the beginning
2896 // // of the backing storage.
2897 // static const int kPrefixSize = ..;
2898 // // The Element size indicates number of elements per entry.
2899 // static const int kEntrySize = ..;
2901 // The prefix size indicates an amount of memory in the
2902 // beginning of the backing storage that can be used for non-element
2903 // information by subclasses.
2905 template<typename Key>
2908 static const bool UsesSeed = false;
2909 static uint32_t Hash(Key key) { return 0; }
2910 static uint32_t SeededHash(Key key, uint32_t seed) {
2914 static uint32_t HashForObject(Key key, Object* object) { return 0; }
2915 static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
2917 return HashForObject(key, object);
2922 class HashTableBase : public FixedArray {
2924 // Returns the number of elements in the hash table.
2925 int NumberOfElements() {
2926 return Smi::cast(get(kNumberOfElementsIndex))->value();
2929 // Returns the number of deleted elements in the hash table.
2930 int NumberOfDeletedElements() {
2931 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
2934 // Returns the capacity of the hash table.
2936 return Smi::cast(get(kCapacityIndex))->value();
2939 // ElementAdded should be called whenever an element is added to a
2941 void ElementAdded() { SetNumberOfElements(NumberOfElements() + 1); }
2943 // ElementRemoved should be called whenever an element is removed from
2945 void ElementRemoved() {
2946 SetNumberOfElements(NumberOfElements() - 1);
2947 SetNumberOfDeletedElements(NumberOfDeletedElements() + 1);
2949 void ElementsRemoved(int n) {
2950 SetNumberOfElements(NumberOfElements() - n);
2951 SetNumberOfDeletedElements(NumberOfDeletedElements() + n);
2954 // Computes the required capacity for a table holding the given
2955 // number of elements. May be more than HashTable::kMaxCapacity.
2956 static inline int ComputeCapacity(int at_least_space_for);
2958 // Tells whether k is a real key. The hole and undefined are not allowed
2959 // as keys and can be used to indicate missing or deleted elements.
2960 bool IsKey(Object* k) {
2961 return !k->IsTheHole() && !k->IsUndefined();
2964 // Compute the probe offset (quadratic probing).
2965 INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
2966 return (n + n * n) >> 1;
2969 static const int kNumberOfElementsIndex = 0;
2970 static const int kNumberOfDeletedElementsIndex = 1;
2971 static const int kCapacityIndex = 2;
2972 static const int kPrefixStartIndex = 3;
2974 // Constant used for denoting a absent entry.
2975 static const int kNotFound = -1;
2978 // Update the number of elements in the hash table.
2979 void SetNumberOfElements(int nof) {
2980 set(kNumberOfElementsIndex, Smi::FromInt(nof));
2983 // Update the number of deleted elements in the hash table.
2984 void SetNumberOfDeletedElements(int nod) {
2985 set(kNumberOfDeletedElementsIndex, Smi::FromInt(nod));
2988 // Returns probe entry.
2989 static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
2990 DCHECK(base::bits::IsPowerOfTwo32(size));
2991 return (hash + GetProbeOffset(number)) & (size - 1);
2994 inline static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
2995 return hash & (size - 1);
2998 inline static uint32_t NextProbe(
2999 uint32_t last, uint32_t number, uint32_t size) {
3000 return (last + number) & (size - 1);
3005 template <typename Derived, typename Shape, typename Key>
3006 class HashTable : public HashTableBase {
3009 inline uint32_t Hash(Key key) {
3010 if (Shape::UsesSeed) {
3011 return Shape::SeededHash(key, GetHeap()->HashSeed());
3013 return Shape::Hash(key);
3017 inline uint32_t HashForObject(Key key, Object* object) {
3018 if (Shape::UsesSeed) {
3019 return Shape::SeededHashForObject(key, GetHeap()->HashSeed(), object);
3021 return Shape::HashForObject(key, object);
3025 // Returns a new HashTable object.
3026 MUST_USE_RESULT static Handle<Derived> New(
3027 Isolate* isolate, int at_least_space_for,
3028 MinimumCapacity capacity_option = USE_DEFAULT_MINIMUM_CAPACITY,
3029 PretenureFlag pretenure = NOT_TENURED);
3031 DECLARE_CAST(HashTable)
3033 // Garbage collection support.
3034 void IteratePrefix(ObjectVisitor* visitor);
3035 void IterateElements(ObjectVisitor* visitor);
3037 // Find entry for key otherwise return kNotFound.
3038 inline int FindEntry(Key key);
3039 inline int FindEntry(Isolate* isolate, Key key, int32_t hash);
3040 int FindEntry(Isolate* isolate, Key key);
3042 // Rehashes the table in-place.
3043 void Rehash(Key key);
3045 // Returns the key at entry.
3046 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3048 static const int kElementsStartIndex = kPrefixStartIndex + Shape::kPrefixSize;
3049 static const int kEntrySize = Shape::kEntrySize;
3050 static const int kElementsStartOffset =
3051 kHeaderSize + kElementsStartIndex * kPointerSize;
3052 static const int kCapacityOffset =
3053 kHeaderSize + kCapacityIndex * kPointerSize;
3055 // Returns the index for an entry (of the key)
3056 static inline int EntryToIndex(int entry) {
3057 return (entry * kEntrySize) + kElementsStartIndex;
3061 friend class ObjectHashTable;
3063 // Find the entry at which to insert element with the given key that
3064 // has the given hash value.
3065 uint32_t FindInsertionEntry(uint32_t hash);
3067 // Attempt to shrink hash table after removal of key.
3068 MUST_USE_RESULT static Handle<Derived> Shrink(Handle<Derived> table, Key key);
3070 // Ensure enough space for n additional elements.
3071 MUST_USE_RESULT static Handle<Derived> EnsureCapacity(
3072 Handle<Derived> table,
3075 PretenureFlag pretenure = NOT_TENURED);
3077 // Sets the capacity of the hash table.
3078 void SetCapacity(int capacity) {
3079 // To scale a computed hash code to fit within the hash table, we
3080 // use bit-wise AND with a mask, so the capacity must be positive
3082 DCHECK(capacity > 0);
3083 DCHECK(capacity <= kMaxCapacity);
3084 set(kCapacityIndex, Smi::FromInt(capacity));
3087 // Maximal capacity of HashTable. Based on maximal length of underlying
3088 // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
3090 static const int kMaxCapacity =
3091 (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
3094 // Returns _expected_ if one of entries given by the first _probe_ probes is
3095 // equal to _expected_. Otherwise, returns the entry given by the probe
3097 uint32_t EntryForProbe(Key key, Object* k, int probe, uint32_t expected);
3099 void Swap(uint32_t entry1, uint32_t entry2, WriteBarrierMode mode);
3101 // Rehashes this hash-table into the new table.
3102 void Rehash(Handle<Derived> new_table, Key key);
3106 // HashTableKey is an abstract superclass for virtual key behavior.
3107 class HashTableKey {
3109 // Returns whether the other object matches this key.
3110 virtual bool IsMatch(Object* other) = 0;
3111 // Returns the hash value for this key.
3112 virtual uint32_t Hash() = 0;
3113 // Returns the hash value for object.
3114 virtual uint32_t HashForObject(Object* key) = 0;
3115 // Returns the key object for storing into the hash table.
3116 MUST_USE_RESULT virtual Handle<Object> AsHandle(Isolate* isolate) = 0;
3118 virtual ~HashTableKey() {}
3122 class StringTableShape : public BaseShape<HashTableKey*> {
3124 static inline bool IsMatch(HashTableKey* key, Object* value) {
3125 return key->IsMatch(value);
3128 static inline uint32_t Hash(HashTableKey* key) {
3132 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3133 return key->HashForObject(object);
3136 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3138 static const int kPrefixSize = 0;
3139 static const int kEntrySize = 1;
3142 class SeqOneByteString;
3146 // No special elements in the prefix and the element size is 1
3147 // because only the string itself (the key) needs to be stored.
3148 class StringTable: public HashTable<StringTable,
3152 // Find string in the string table. If it is not there yet, it is
3153 // added. The return value is the string found.
3154 static Handle<String> LookupString(Isolate* isolate, Handle<String> key);
3155 static Handle<String> LookupKey(Isolate* isolate, HashTableKey* key);
3156 static String* LookupKeyIfExists(Isolate* isolate, HashTableKey* key);
3158 // Tries to internalize given string and returns string handle on success
3159 // or an empty handle otherwise.
3160 MUST_USE_RESULT static MaybeHandle<String> InternalizeStringIfExists(
3162 Handle<String> string);
3164 // Looks up a string that is equal to the given string and returns
3165 // string handle if it is found, or an empty handle otherwise.
3166 MUST_USE_RESULT static MaybeHandle<String> LookupStringIfExists(
3168 Handle<String> str);
3169 MUST_USE_RESULT static MaybeHandle<String> LookupTwoCharsStringIfExists(
3174 static void EnsureCapacityForDeserialization(Isolate* isolate, int expected);
3176 DECLARE_CAST(StringTable)
3179 template <bool seq_one_byte>
3180 friend class JsonParser;
3182 DISALLOW_IMPLICIT_CONSTRUCTORS(StringTable);
3186 template <typename Derived, typename Shape, typename Key>
3187 class Dictionary: public HashTable<Derived, Shape, Key> {
3188 typedef HashTable<Derived, Shape, Key> DerivedHashTable;
3191 // Returns the value at entry.
3192 Object* ValueAt(int entry) {
3193 return this->get(Derived::EntryToIndex(entry) + 1);
3196 // Set the value for entry.
3197 void ValueAtPut(int entry, Object* value) {
3198 this->set(Derived::EntryToIndex(entry) + 1, value);
3201 // Returns the property details for the property at entry.
3202 PropertyDetails DetailsAt(int entry) {
3203 return Shape::DetailsAt(static_cast<Derived*>(this), entry);
3206 // Set the details for entry.
3207 void DetailsAtPut(int entry, PropertyDetails value) {
3208 Shape::DetailsAtPut(static_cast<Derived*>(this), entry, value);
3211 // Returns true if property at given entry is deleted.
3212 bool IsDeleted(int entry) {
3213 return Shape::IsDeleted(static_cast<Derived*>(this), entry);
3216 // Delete a property from the dictionary.
3217 static Handle<Object> DeleteProperty(Handle<Derived> dictionary, int entry);
3219 // Attempt to shrink the dictionary after deletion of key.
3220 MUST_USE_RESULT static inline Handle<Derived> Shrink(
3221 Handle<Derived> dictionary,
3223 return DerivedHashTable::Shrink(dictionary, key);
3227 // TODO(dcarney): templatize or move to SeededNumberDictionary
3228 void CopyValuesTo(FixedArray* elements);
3230 // Returns the number of elements in the dictionary filtering out properties
3231 // with the specified attributes.
3232 int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3234 // Returns the number of enumerable elements in the dictionary.
3235 int NumberOfEnumElements() {
3236 return NumberOfElementsFilterAttributes(
3237 static_cast<PropertyAttributes>(DONT_ENUM | SYMBOLIC));
3240 // Returns true if the dictionary contains any elements that are non-writable,
3241 // non-configurable, non-enumerable, or have getters/setters.
3242 bool HasComplexElements();
3244 enum SortMode { UNSORTED, SORTED };
3246 // Fill in details for properties into storage.
3247 // Returns the number of properties added.
3248 int CopyKeysTo(FixedArray* storage, int index, PropertyAttributes filter,
3249 SortMode sort_mode);
3251 // Copies enumerable keys to preallocated fixed array.
3252 void CopyEnumKeysTo(FixedArray* storage);
3254 // Accessors for next enumeration index.
3255 void SetNextEnumerationIndex(int index) {
3257 this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
3260 int NextEnumerationIndex() {
3261 return Smi::cast(this->get(kNextEnumerationIndexIndex))->value();
3264 // Creates a new dictionary.
3265 MUST_USE_RESULT static Handle<Derived> New(
3267 int at_least_space_for,
3268 PretenureFlag pretenure = NOT_TENURED);
3270 // Ensure enough space for n additional elements.
3271 static Handle<Derived> EnsureCapacity(Handle<Derived> obj, int n, Key key);
3274 void Print(std::ostream& os); // NOLINT
3276 // Returns the key (slow).
3277 Object* SlowReverseLookup(Object* value);
3279 // Sets the entry to (key, value) pair.
3280 inline void SetEntry(int entry,
3282 Handle<Object> value);
3283 inline void SetEntry(int entry,
3285 Handle<Object> value,
3286 PropertyDetails details);
3288 MUST_USE_RESULT static Handle<Derived> Add(
3289 Handle<Derived> dictionary,
3291 Handle<Object> value,
3292 PropertyDetails details);
3294 // Returns iteration indices array for the |dictionary|.
3295 // Values are direct indices in the |HashTable| array.
3296 static Handle<FixedArray> BuildIterationIndicesArray(
3297 Handle<Derived> dictionary);
3300 // Generic at put operation.
3301 MUST_USE_RESULT static Handle<Derived> AtPut(
3302 Handle<Derived> dictionary,
3304 Handle<Object> value);
3306 // Add entry to dictionary.
3307 static void AddEntry(
3308 Handle<Derived> dictionary,
3310 Handle<Object> value,
3311 PropertyDetails details,
3314 // Generate new enumeration indices to avoid enumeration index overflow.
3315 // Returns iteration indices array for the |dictionary|.
3316 static Handle<FixedArray> GenerateNewEnumerationIndices(
3317 Handle<Derived> dictionary);
3318 static const int kMaxNumberKeyIndex = DerivedHashTable::kPrefixStartIndex;
3319 static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
3323 template <typename Derived, typename Shape>
3324 class NameDictionaryBase : public Dictionary<Derived, Shape, Handle<Name> > {
3325 typedef Dictionary<Derived, Shape, Handle<Name> > DerivedDictionary;
3328 // Find entry for key, otherwise return kNotFound. Optimized version of
3329 // HashTable::FindEntry.
3330 int FindEntry(Handle<Name> key);
3334 template <typename Key>
3335 class BaseDictionaryShape : public BaseShape<Key> {
3337 template <typename Dictionary>
3338 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry) {
3339 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3340 DCHECK(entry >= 0); // Not found is -1, which is not caught by get().
3341 return PropertyDetails(
3342 Smi::cast(dict->get(Dictionary::EntryToIndex(entry) + 2)));
3345 template <typename Dictionary>
3346 static inline void DetailsAtPut(Dictionary* dict, int entry,
3347 PropertyDetails value) {
3348 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3349 dict->set(Dictionary::EntryToIndex(entry) + 2, value.AsSmi());
3352 template <typename Dictionary>
3353 static bool IsDeleted(Dictionary* dict, int entry) {
3357 template <typename Dictionary>
3358 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3359 Handle<Object> value, PropertyDetails details);
3363 class NameDictionaryShape : public BaseDictionaryShape<Handle<Name> > {
3365 static inline bool IsMatch(Handle<Name> key, Object* other);
3366 static inline uint32_t Hash(Handle<Name> key);
3367 static inline uint32_t HashForObject(Handle<Name> key, Object* object);
3368 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Name> key);
3369 static const int kPrefixSize = 2;
3370 static const int kEntrySize = 3;
3371 static const bool kIsEnumerable = true;
3375 class NameDictionary
3376 : public NameDictionaryBase<NameDictionary, NameDictionaryShape> {
3377 typedef NameDictionaryBase<NameDictionary, NameDictionaryShape>
3381 DECLARE_CAST(NameDictionary)
3383 inline static Handle<FixedArray> DoGenerateNewEnumerationIndices(
3384 Handle<NameDictionary> dictionary);
3388 class GlobalDictionaryShape : public NameDictionaryShape {
3390 static const int kEntrySize = 2; // Overrides NameDictionaryShape::kEntrySize
3392 template <typename Dictionary>
3393 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry);
3395 template <typename Dictionary>
3396 static inline void DetailsAtPut(Dictionary* dict, int entry,
3397 PropertyDetails value);
3399 template <typename Dictionary>
3400 static bool IsDeleted(Dictionary* dict, int entry);
3402 template <typename Dictionary>
3403 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3404 Handle<Object> value, PropertyDetails details);
3408 class GlobalDictionary
3409 : public NameDictionaryBase<GlobalDictionary, GlobalDictionaryShape> {
3411 DECLARE_CAST(GlobalDictionary)
3415 class NumberDictionaryShape : public BaseDictionaryShape<uint32_t> {
3417 static inline bool IsMatch(uint32_t key, Object* other);
3418 static inline Handle<Object> AsHandle(Isolate* isolate, uint32_t key);
3419 static const int kEntrySize = 3;
3420 static const bool kIsEnumerable = false;
3424 class SeededNumberDictionaryShape : public NumberDictionaryShape {
3426 static const bool UsesSeed = true;
3427 static const int kPrefixSize = 2;
3429 static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
3430 static inline uint32_t SeededHashForObject(uint32_t key,
3436 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
3438 static const int kPrefixSize = 0;
3440 static inline uint32_t Hash(uint32_t key);
3441 static inline uint32_t HashForObject(uint32_t key, Object* object);
3445 class SeededNumberDictionary
3446 : public Dictionary<SeededNumberDictionary,
3447 SeededNumberDictionaryShape,
3450 DECLARE_CAST(SeededNumberDictionary)
3452 // Type specific at put (default NONE attributes is used when adding).
3453 MUST_USE_RESULT static Handle<SeededNumberDictionary> AtNumberPut(
3454 Handle<SeededNumberDictionary> dictionary,
3456 Handle<Object> value);
3457 MUST_USE_RESULT static Handle<SeededNumberDictionary> AddNumberEntry(
3458 Handle<SeededNumberDictionary> dictionary,
3460 Handle<Object> value,
3461 PropertyDetails details);
3463 // Set an existing entry or add a new one if needed.
3464 // Return the updated dictionary.
3465 MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
3466 Handle<SeededNumberDictionary> dictionary,
3468 Handle<Object> value,
3469 PropertyDetails details);
3471 void UpdateMaxNumberKey(uint32_t key);
3473 // If slow elements are required we will never go back to fast-case
3474 // for the elements kept in this dictionary. We require slow
3475 // elements if an element has been added at an index larger than
3476 // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
3477 // when defining a getter or setter with a number key.
3478 inline bool requires_slow_elements();
3479 inline void set_requires_slow_elements();
3481 // Get the value of the max number key that has been added to this
3482 // dictionary. max_number_key can only be called if
3483 // requires_slow_elements returns false.
3484 inline uint32_t max_number_key();
3487 static const int kRequiresSlowElementsMask = 1;
3488 static const int kRequiresSlowElementsTagSize = 1;
3489 static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
3493 class UnseededNumberDictionary
3494 : public Dictionary<UnseededNumberDictionary,
3495 UnseededNumberDictionaryShape,
3498 DECLARE_CAST(UnseededNumberDictionary)
3500 // Type specific at put (default NONE attributes is used when adding).
3501 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AtNumberPut(
3502 Handle<UnseededNumberDictionary> dictionary,
3504 Handle<Object> value);
3505 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AddNumberEntry(
3506 Handle<UnseededNumberDictionary> dictionary,
3508 Handle<Object> value);
3510 // Set an existing entry or add a new one if needed.
3511 // Return the updated dictionary.
3512 MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
3513 Handle<UnseededNumberDictionary> dictionary,
3515 Handle<Object> value);
3519 class ObjectHashTableShape : public BaseShape<Handle<Object> > {
3521 static inline bool IsMatch(Handle<Object> key, Object* other);
3522 static inline uint32_t Hash(Handle<Object> key);
3523 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3524 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3525 static const int kPrefixSize = 0;
3526 static const int kEntrySize = 2;
3530 // ObjectHashTable maps keys that are arbitrary objects to object values by
3531 // using the identity hash of the key for hashing purposes.
3532 class ObjectHashTable: public HashTable<ObjectHashTable,
3533 ObjectHashTableShape,
3536 ObjectHashTable, ObjectHashTableShape, Handle<Object> > DerivedHashTable;
3538 DECLARE_CAST(ObjectHashTable)
3540 // Attempt to shrink hash table after removal of key.
3541 MUST_USE_RESULT static inline Handle<ObjectHashTable> Shrink(
3542 Handle<ObjectHashTable> table,
3543 Handle<Object> key);
3545 // Looks up the value associated with the given key. The hole value is
3546 // returned in case the key is not present.
3547 Object* Lookup(Handle<Object> key);
3548 Object* Lookup(Handle<Object> key, int32_t hash);
3549 Object* Lookup(Isolate* isolate, Handle<Object> key, int32_t hash);
3551 // Adds (or overwrites) the value associated with the given key.
3552 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3554 Handle<Object> value);
3555 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3556 Handle<Object> key, Handle<Object> value,
3559 // Returns an ObjectHashTable (possibly |table|) where |key| has been removed.
3560 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3563 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3564 Handle<Object> key, bool* was_present,
3568 friend class MarkCompactCollector;
3570 void AddEntry(int entry, Object* key, Object* value);
3571 void RemoveEntry(int entry);
3573 // Returns the index to the value of an entry.
3574 static inline int EntryToValueIndex(int entry) {
3575 return EntryToIndex(entry) + 1;
3580 // OrderedHashTable is a HashTable with Object keys that preserves
3581 // insertion order. There are Map and Set interfaces (OrderedHashMap
3582 // and OrderedHashTable, below). It is meant to be used by JSMap/JSSet.
3584 // Only Object* keys are supported, with Object::SameValueZero() used as the
3585 // equality operator and Object::GetHash() for the hash function.
3587 // Based on the "Deterministic Hash Table" as described by Jason Orendorff at
3588 // https://wiki.mozilla.org/User:Jorend/Deterministic_hash_tables
3589 // Originally attributed to Tyler Close.
3592 // [0]: bucket count
3593 // [1]: element count
3594 // [2]: deleted element count
3595 // [3..(3 + NumberOfBuckets() - 1)]: "hash table", where each item is an
3596 // offset into the data table (see below) where the
3597 // first item in this bucket is stored.
3598 // [3 + NumberOfBuckets()..length]: "data table", an array of length
3599 // Capacity() * kEntrySize, where the first entrysize
3600 // items are handled by the derived class and the
3601 // item at kChainOffset is another entry into the
3602 // data table indicating the next entry in this hash
3605 // When we transition the table to a new version we obsolete it and reuse parts
3606 // of the memory to store information how to transition an iterator to the new
3609 // Memory layout for obsolete table:
3610 // [0]: bucket count
3611 // [1]: Next newer table
3612 // [2]: Number of removed holes or -1 when the table was cleared.
3613 // [3..(3 + NumberOfRemovedHoles() - 1)]: The indexes of the removed holes.
3614 // [3 + NumberOfRemovedHoles()..length]: Not used
3616 template<class Derived, class Iterator, int entrysize>
3617 class OrderedHashTable: public FixedArray {
3619 // Returns an OrderedHashTable with a capacity of at least |capacity|.
3620 static Handle<Derived> Allocate(
3621 Isolate* isolate, int capacity, PretenureFlag pretenure = NOT_TENURED);
3623 // Returns an OrderedHashTable (possibly |table|) with enough space
3624 // to add at least one new element.
3625 static Handle<Derived> EnsureGrowable(Handle<Derived> table);
3627 // Returns an OrderedHashTable (possibly |table|) that's shrunken
3629 static Handle<Derived> Shrink(Handle<Derived> table);
3631 // Returns a new empty OrderedHashTable and records the clearing so that
3632 // exisiting iterators can be updated.
3633 static Handle<Derived> Clear(Handle<Derived> table);
3635 int NumberOfElements() {
3636 return Smi::cast(get(kNumberOfElementsIndex))->value();
3639 int NumberOfDeletedElements() {
3640 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3643 int UsedCapacity() { return NumberOfElements() + NumberOfDeletedElements(); }
3645 int NumberOfBuckets() {
3646 return Smi::cast(get(kNumberOfBucketsIndex))->value();
3649 // Returns an index into |this| for the given entry.
3650 int EntryToIndex(int entry) {
3651 return kHashTableStartIndex + NumberOfBuckets() + (entry * kEntrySize);
3654 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3657 return !get(kNextTableIndex)->IsSmi();
3660 // The next newer table. This is only valid if the table is obsolete.
3661 Derived* NextTable() {
3662 return Derived::cast(get(kNextTableIndex));
3665 // When the table is obsolete we store the indexes of the removed holes.
3666 int RemovedIndexAt(int index) {
3667 return Smi::cast(get(kRemovedHolesIndex + index))->value();
3670 static const int kNotFound = -1;
3671 static const int kMinCapacity = 4;
3673 static const int kNumberOfBucketsIndex = 0;
3674 static const int kNumberOfElementsIndex = kNumberOfBucketsIndex + 1;
3675 static const int kNumberOfDeletedElementsIndex = kNumberOfElementsIndex + 1;
3676 static const int kHashTableStartIndex = kNumberOfDeletedElementsIndex + 1;
3677 static const int kNextTableIndex = kNumberOfElementsIndex;
3679 static const int kNumberOfBucketsOffset =
3680 kHeaderSize + kNumberOfBucketsIndex * kPointerSize;
3681 static const int kNumberOfElementsOffset =
3682 kHeaderSize + kNumberOfElementsIndex * kPointerSize;
3683 static const int kNumberOfDeletedElementsOffset =
3684 kHeaderSize + kNumberOfDeletedElementsIndex * kPointerSize;
3685 static const int kHashTableStartOffset =
3686 kHeaderSize + kHashTableStartIndex * kPointerSize;
3687 static const int kNextTableOffset =
3688 kHeaderSize + kNextTableIndex * kPointerSize;
3690 static const int kEntrySize = entrysize + 1;
3691 static const int kChainOffset = entrysize;
3693 static const int kLoadFactor = 2;
3695 // NumberOfDeletedElements is set to kClearedTableSentinel when
3696 // the table is cleared, which allows iterator transitions to
3697 // optimize that case.
3698 static const int kClearedTableSentinel = -1;
3701 static Handle<Derived> Rehash(Handle<Derived> table, int new_capacity);
3703 void SetNumberOfBuckets(int num) {
3704 set(kNumberOfBucketsIndex, Smi::FromInt(num));
3707 void SetNumberOfElements(int num) {
3708 set(kNumberOfElementsIndex, Smi::FromInt(num));
3711 void SetNumberOfDeletedElements(int num) {
3712 set(kNumberOfDeletedElementsIndex, Smi::FromInt(num));
3716 return NumberOfBuckets() * kLoadFactor;
3719 void SetNextTable(Derived* next_table) {
3720 set(kNextTableIndex, next_table);
3723 void SetRemovedIndexAt(int index, int removed_index) {
3724 return set(kRemovedHolesIndex + index, Smi::FromInt(removed_index));
3727 static const int kRemovedHolesIndex = kHashTableStartIndex;
3729 static const int kMaxCapacity =
3730 (FixedArray::kMaxLength - kHashTableStartIndex)
3731 / (1 + (kEntrySize * kLoadFactor));
3735 class JSSetIterator;
3738 class OrderedHashSet: public OrderedHashTable<
3739 OrderedHashSet, JSSetIterator, 1> {
3741 DECLARE_CAST(OrderedHashSet)
3745 class JSMapIterator;
3748 class OrderedHashMap
3749 : public OrderedHashTable<OrderedHashMap, JSMapIterator, 2> {
3751 DECLARE_CAST(OrderedHashMap)
3753 Object* ValueAt(int entry) {
3754 return get(EntryToIndex(entry) + kValueOffset);
3757 static const int kValueOffset = 1;
3761 template <int entrysize>
3762 class WeakHashTableShape : public BaseShape<Handle<Object> > {
3764 static inline bool IsMatch(Handle<Object> key, Object* other);
3765 static inline uint32_t Hash(Handle<Object> key);
3766 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3767 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3768 static const int kPrefixSize = 0;
3769 static const int kEntrySize = entrysize;
3773 // WeakHashTable maps keys that are arbitrary heap objects to heap object
3774 // values. The table wraps the keys in weak cells and store values directly.
3775 // Thus it references keys weakly and values strongly.
3776 class WeakHashTable: public HashTable<WeakHashTable,
3777 WeakHashTableShape<2>,
3780 WeakHashTable, WeakHashTableShape<2>, Handle<Object> > DerivedHashTable;
3782 DECLARE_CAST(WeakHashTable)
3784 // Looks up the value associated with the given key. The hole value is
3785 // returned in case the key is not present.
3786 Object* Lookup(Handle<HeapObject> key);
3788 // Adds (or overwrites) the value associated with the given key. Mapping a
3789 // key to the hole value causes removal of the whole entry.
3790 MUST_USE_RESULT static Handle<WeakHashTable> Put(Handle<WeakHashTable> table,
3791 Handle<HeapObject> key,
3792 Handle<HeapObject> value);
3794 static Handle<FixedArray> GetValues(Handle<WeakHashTable> table);
3797 friend class MarkCompactCollector;
3799 void AddEntry(int entry, Handle<WeakCell> key, Handle<HeapObject> value);
3801 // Returns the index to the value of an entry.
3802 static inline int EntryToValueIndex(int entry) {
3803 return EntryToIndex(entry) + 1;
3808 class WeakValueHashTable : public ObjectHashTable {
3810 DECLARE_CAST(WeakValueHashTable)
3813 // Looks up the value associated with the given key. The hole value is
3814 // returned in case the key is not present.
3815 Object* LookupWeak(Handle<Object> key);
3818 // Adds (or overwrites) the value associated with the given key. Mapping a
3819 // key to the hole value causes removal of the whole entry.
3820 MUST_USE_RESULT static Handle<WeakValueHashTable> PutWeak(
3821 Handle<WeakValueHashTable> table, Handle<Object> key,
3822 Handle<HeapObject> value);
3824 static Handle<FixedArray> GetWeakValues(Handle<WeakValueHashTable> table);
3828 // ScopeInfo represents information about different scopes of a source
3829 // program and the allocation of the scope's variables. Scope information
3830 // is stored in a compressed form in ScopeInfo objects and is used
3831 // at runtime (stack dumps, deoptimization, etc.).
3833 // This object provides quick access to scope info details for runtime
3835 class ScopeInfo : public FixedArray {
3837 DECLARE_CAST(ScopeInfo)
3839 // Return the type of this scope.
3840 ScopeType scope_type();
3842 // Does this scope call eval?
3845 // Return the language mode of this scope.
3846 LanguageMode language_mode();
3848 // Does this scope make a sloppy eval call?
3849 bool CallsSloppyEval() { return CallsEval() && is_sloppy(language_mode()); }
3851 // Return the total number of locals allocated on the stack and in the
3852 // context. This includes the parameters that are allocated in the context.
3855 // Return the number of stack slots for code. This number consists of two
3857 // 1. One stack slot per stack allocated local.
3858 // 2. One stack slot for the function name if it is stack allocated.
3859 int StackSlotCount();
3861 // Return the number of context slots for code if a context is allocated. This
3862 // number consists of three parts:
3863 // 1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
3864 // 2. One context slot per context allocated local.
3865 // 3. One context slot for the function name if it is context allocated.
3866 // Parameters allocated in the context count as context allocated locals. If
3867 // no contexts are allocated for this scope ContextLength returns 0.
3868 int ContextLength();
3870 // Does this scope declare a "this" binding?
3873 // Does this scope declare a "this" binding, and the "this" binding is stack-
3874 // or context-allocated?
3875 bool HasAllocatedReceiver();
3877 // Is this scope the scope of a named function expression?
3878 bool HasFunctionName();
3880 // Return if this has context allocated locals.
3881 bool HasHeapAllocatedLocals();
3883 // Return if contexts are allocated for this scope.
3886 // Return if this is a function scope with "use asm".
3887 bool IsAsmModule() { return AsmModuleField::decode(Flags()); }
3889 // Return if this is a nested function within an asm module scope.
3890 bool IsAsmFunction() { return AsmFunctionField::decode(Flags()); }
3892 bool IsSimpleParameterList() {
3893 return IsSimpleParameterListField::decode(Flags());
3896 // Return the function_name if present.
3897 String* FunctionName();
3899 // Return the name of the given parameter.
3900 String* ParameterName(int var);
3902 // Return the name of the given local.
3903 String* LocalName(int var);
3905 // Return the name of the given stack local.
3906 String* StackLocalName(int var);
3908 // Return the name of the given stack local.
3909 int StackLocalIndex(int var);
3911 // Return the name of the given context local.
3912 String* ContextLocalName(int var);
3914 // Return the mode of the given context local.
3915 VariableMode ContextLocalMode(int var);
3917 // Return the initialization flag of the given context local.
3918 InitializationFlag ContextLocalInitFlag(int var);
3920 // Return the initialization flag of the given context local.
3921 MaybeAssignedFlag ContextLocalMaybeAssignedFlag(int var);
3923 // Return true if this local was introduced by the compiler, and should not be
3924 // exposed to the user in a debugger.
3925 bool LocalIsSynthetic(int var);
3927 String* StrongModeFreeVariableName(int var);
3928 int StrongModeFreeVariableStartPosition(int var);
3929 int StrongModeFreeVariableEndPosition(int var);
3931 // Lookup support for serialized scope info. Returns the
3932 // the stack slot index for a given slot name if the slot is
3933 // present; otherwise returns a value < 0. The name must be an internalized
3935 int StackSlotIndex(String* name);
3937 // Lookup support for serialized scope info. Returns the
3938 // context slot index for a given slot name if the slot is present; otherwise
3939 // returns a value < 0. The name must be an internalized string.
3940 // If the slot is present and mode != NULL, sets *mode to the corresponding
3941 // mode for that variable.
3942 static int ContextSlotIndex(Handle<ScopeInfo> scope_info, Handle<String> name,
3943 VariableMode* mode, VariableLocation* location,
3944 InitializationFlag* init_flag,
3945 MaybeAssignedFlag* maybe_assigned_flag);
3947 // Lookup the name of a certain context slot by its index.
3948 String* ContextSlotName(int slot_index);
3950 // Lookup support for serialized scope info. Returns the
3951 // parameter index for a given parameter name if the parameter is present;
3952 // otherwise returns a value < 0. The name must be an internalized string.
3953 int ParameterIndex(String* name);
3955 // Lookup support for serialized scope info. Returns the function context
3956 // slot index if the function name is present and context-allocated (named
3957 // function expressions, only), otherwise returns a value < 0. The name
3958 // must be an internalized string.
3959 int FunctionContextSlotIndex(String* name, VariableMode* mode);
3961 // Lookup support for serialized scope info. Returns the receiver context
3962 // slot index if scope has a "this" binding, and the binding is
3963 // context-allocated. Otherwise returns a value < 0.
3964 int ReceiverContextSlotIndex();
3966 FunctionKind function_kind();
3968 // Copies all the context locals into an object used to materialize a scope.
3969 static void CopyContextLocalsToScopeObject(Handle<ScopeInfo> scope_info,
3970 Handle<Context> context,
3971 Handle<JSObject> scope_object);
3974 static Handle<ScopeInfo> Create(Isolate* isolate, Zone* zone, Scope* scope);
3975 static Handle<ScopeInfo> CreateGlobalThisBinding(Isolate* isolate);
3977 // Serializes empty scope info.
3978 static ScopeInfo* Empty(Isolate* isolate);
3984 // The layout of the static part of a ScopeInfo is as follows. Each entry is
3985 // numeric and occupies one array slot.
3986 // 1. A set of properties of the scope
3987 // 2. The number of parameters. This only applies to function scopes. For
3988 // non-function scopes this is 0.
3989 // 3. The number of non-parameter variables allocated on the stack.
3990 // 4. The number of non-parameter and parameter variables allocated in the
3992 #define FOR_EACH_NUMERIC_FIELD(V) \
3995 V(StackLocalCount) \
3996 V(ContextLocalCount) \
3997 V(ContextGlobalCount) \
3998 V(StrongModeFreeVariableCount)
4000 #define FIELD_ACCESSORS(name) \
4001 void Set##name(int value) { \
4002 set(k##name, Smi::FromInt(value)); \
4005 if (length() > 0) { \
4006 return Smi::cast(get(k##name))->value(); \
4011 FOR_EACH_NUMERIC_FIELD(FIELD_ACCESSORS)
4012 #undef FIELD_ACCESSORS
4016 #define DECL_INDEX(name) k##name,
4017 FOR_EACH_NUMERIC_FIELD(DECL_INDEX)
4019 #undef FOR_EACH_NUMERIC_FIELD
4023 // The layout of the variable part of a ScopeInfo is as follows:
4024 // 1. ParameterEntries:
4025 // This part stores the names of the parameters for function scopes. One
4026 // slot is used per parameter, so in total this part occupies
4027 // ParameterCount() slots in the array. For other scopes than function
4028 // scopes ParameterCount() is 0.
4029 // 2. StackLocalFirstSlot:
4030 // Index of a first stack slot for stack local. Stack locals belonging to
4031 // this scope are located on a stack at slots starting from this index.
4032 // 3. StackLocalEntries:
4033 // Contains the names of local variables that are allocated on the stack,
4034 // in increasing order of the stack slot index. First local variable has
4035 // a stack slot index defined in StackLocalFirstSlot (point 2 above).
4036 // One slot is used per stack local, so in total this part occupies
4037 // StackLocalCount() slots in the array.
4038 // 4. ContextLocalNameEntries:
4039 // Contains the names of local variables and parameters that are allocated
4040 // in the context. They are stored in increasing order of the context slot
4041 // index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
4042 // context local, so in total this part occupies ContextLocalCount() slots
4044 // 5. ContextLocalInfoEntries:
4045 // Contains the variable modes and initialization flags corresponding to
4046 // the context locals in ContextLocalNameEntries. One slot is used per
4047 // context local, so in total this part occupies ContextLocalCount()
4048 // slots in the array.
4049 // 6. StrongModeFreeVariableNameEntries:
4050 // Stores the names of strong mode free variables.
4051 // 7. StrongModeFreeVariablePositionEntries:
4052 // Stores the locations (start and end position) of strong mode free
4054 // 8. RecieverEntryIndex:
4055 // If the scope binds a "this" value, one slot is reserved to hold the
4056 // context or stack slot index for the variable.
4057 // 9. FunctionNameEntryIndex:
4058 // If the scope belongs to a named function expression this part contains
4059 // information about the function variable. It always occupies two array
4060 // slots: a. The name of the function variable.
4061 // b. The context or stack slot index for the variable.
4062 int ParameterEntriesIndex();
4063 int StackLocalFirstSlotIndex();
4064 int StackLocalEntriesIndex();
4065 int ContextLocalNameEntriesIndex();
4066 int ContextGlobalNameEntriesIndex();
4067 int ContextLocalInfoEntriesIndex();
4068 int ContextGlobalInfoEntriesIndex();
4069 int StrongModeFreeVariableNameEntriesIndex();
4070 int StrongModeFreeVariablePositionEntriesIndex();
4071 int ReceiverEntryIndex();
4072 int FunctionNameEntryIndex();
4074 int Lookup(Handle<String> name, int start, int end, VariableMode* mode,
4075 VariableLocation* location, InitializationFlag* init_flag,
4076 MaybeAssignedFlag* maybe_assigned_flag);
4078 // Used for the function name variable for named function expressions, and for
4080 enum VariableAllocationInfo { NONE, STACK, CONTEXT, UNUSED };
4082 // Properties of scopes.
4083 class ScopeTypeField : public BitField<ScopeType, 0, 4> {};
4084 class CallsEvalField : public BitField<bool, ScopeTypeField::kNext, 1> {};
4085 STATIC_ASSERT(LANGUAGE_END == 3);
4086 class LanguageModeField
4087 : public BitField<LanguageMode, CallsEvalField::kNext, 2> {};
4088 class ReceiverVariableField
4089 : public BitField<VariableAllocationInfo, LanguageModeField::kNext, 2> {};
4090 class FunctionVariableField
4091 : public BitField<VariableAllocationInfo, ReceiverVariableField::kNext,
4093 class FunctionVariableMode
4094 : public BitField<VariableMode, FunctionVariableField::kNext, 3> {};
4095 class AsmModuleField : public BitField<bool, FunctionVariableMode::kNext, 1> {
4097 class AsmFunctionField : public BitField<bool, AsmModuleField::kNext, 1> {};
4098 class IsSimpleParameterListField
4099 : public BitField<bool, AsmFunctionField::kNext, 1> {};
4100 class FunctionKindField
4101 : public BitField<FunctionKind, IsSimpleParameterListField::kNext, 8> {};
4103 // BitFields representing the encoded information for context locals in the
4104 // ContextLocalInfoEntries part.
4105 class ContextLocalMode: public BitField<VariableMode, 0, 3> {};
4106 class ContextLocalInitFlag: public BitField<InitializationFlag, 3, 1> {};
4107 class ContextLocalMaybeAssignedFlag
4108 : public BitField<MaybeAssignedFlag, 4, 1> {};
4112 // The cache for maps used by normalized (dictionary mode) objects.
4113 // Such maps do not have property descriptors, so a typical program
4114 // needs very limited number of distinct normalized maps.
4115 class NormalizedMapCache: public FixedArray {
4117 static Handle<NormalizedMapCache> New(Isolate* isolate);
4119 MUST_USE_RESULT MaybeHandle<Map> Get(Handle<Map> fast_map,
4120 PropertyNormalizationMode mode);
4121 void Set(Handle<Map> fast_map, Handle<Map> normalized_map);
4125 DECLARE_CAST(NormalizedMapCache)
4127 static inline bool IsNormalizedMapCache(const Object* obj);
4129 DECLARE_VERIFIER(NormalizedMapCache)
4131 static const int kEntries = 64;
4133 static inline int GetIndex(Handle<Map> map);
4135 // The following declarations hide base class methods.
4136 Object* get(int index);
4137 void set(int index, Object* value);
4141 // ByteArray represents fixed sized byte arrays. Used for the relocation info
4142 // that is attached to code objects.
4143 class ByteArray: public FixedArrayBase {
4145 inline int Size() { return RoundUp(length() + kHeaderSize, kPointerSize); }
4147 // Setter and getter.
4148 inline byte get(int index);
4149 inline void set(int index, byte value);
4151 // Treat contents as an int array.
4152 inline int get_int(int index);
4154 static int SizeFor(int length) {
4155 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4157 // We use byte arrays for free blocks in the heap. Given a desired size in
4158 // bytes that is a multiple of the word size and big enough to hold a byte
4159 // array, this function returns the number of elements a byte array should
4161 static int LengthFor(int size_in_bytes) {
4162 DCHECK(IsAligned(size_in_bytes, kPointerSize));
4163 DCHECK(size_in_bytes >= kHeaderSize);
4164 return size_in_bytes - kHeaderSize;
4167 // Returns data start address.
4168 inline Address GetDataStartAddress();
4170 // Returns a pointer to the ByteArray object for a given data start address.
4171 static inline ByteArray* FromDataStartAddress(Address address);
4173 DECLARE_CAST(ByteArray)
4175 // Dispatched behavior.
4176 inline int ByteArraySize() {
4177 return SizeFor(this->length());
4179 DECLARE_PRINTER(ByteArray)
4180 DECLARE_VERIFIER(ByteArray)
4182 // Layout description.
4183 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4185 // Maximal memory consumption for a single ByteArray.
4186 static const int kMaxSize = 512 * MB;
4187 // Maximal length of a single ByteArray.
4188 static const int kMaxLength = kMaxSize - kHeaderSize;
4191 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4195 // BytecodeArray represents a sequence of interpreter bytecodes.
4196 class BytecodeArray : public FixedArrayBase {
4198 static int SizeFor(int length) {
4199 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4202 // Setter and getter
4203 inline byte get(int index);
4204 inline void set(int index, byte value);
4206 // Returns data start address.
4207 inline Address GetFirstBytecodeAddress();
4209 // Accessors for frame size and the number of locals
4210 inline int frame_size() const;
4211 inline void set_frame_size(int value);
4213 DECLARE_CAST(BytecodeArray)
4215 // Dispatched behavior.
4216 inline int BytecodeArraySize() { return SizeFor(this->length()); }
4218 DECLARE_PRINTER(BytecodeArray)
4219 DECLARE_VERIFIER(BytecodeArray)
4221 void Disassemble(std::ostream& os);
4223 // Layout description.
4224 static const int kFrameSizeOffset = FixedArrayBase::kHeaderSize;
4225 static const int kHeaderSize = kFrameSizeOffset + kIntSize;
4227 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4229 // Maximal memory consumption for a single BytecodeArray.
4230 static const int kMaxSize = 512 * MB;
4231 // Maximal length of a single BytecodeArray.
4232 static const int kMaxLength = kMaxSize - kHeaderSize;
4235 DISALLOW_IMPLICIT_CONSTRUCTORS(BytecodeArray);
4239 // FreeSpace are fixed-size free memory blocks used by the heap and GC.
4240 // They look like heap objects (are heap object tagged and have a map) so that
4241 // the heap remains iterable. They have a size and a next pointer.
4242 // The next pointer is the raw address of the next FreeSpace object (or NULL)
4243 // in the free list.
4244 class FreeSpace: public HeapObject {
4246 // [size]: size of the free space including the header.
4247 inline int size() const;
4248 inline void set_size(int value);
4250 inline int nobarrier_size() const;
4251 inline void nobarrier_set_size(int value);
4253 inline int Size() { return size(); }
4255 // Accessors for the next field.
4256 inline FreeSpace* next();
4257 inline FreeSpace** next_address();
4258 inline void set_next(FreeSpace* next);
4260 inline static FreeSpace* cast(HeapObject* obj);
4262 // Dispatched behavior.
4263 DECLARE_PRINTER(FreeSpace)
4264 DECLARE_VERIFIER(FreeSpace)
4266 // Layout description.
4267 // Size is smi tagged when it is stored.
4268 static const int kSizeOffset = HeapObject::kHeaderSize;
4269 static const int kNextOffset = POINTER_SIZE_ALIGN(kSizeOffset + kPointerSize);
4272 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
4276 // V has parameters (Type, type, TYPE, C type, element_size)
4277 #define TYPED_ARRAYS(V) \
4278 V(Uint8, uint8, UINT8, uint8_t, 1) \
4279 V(Int8, int8, INT8, int8_t, 1) \
4280 V(Uint16, uint16, UINT16, uint16_t, 2) \
4281 V(Int16, int16, INT16, int16_t, 2) \
4282 V(Uint32, uint32, UINT32, uint32_t, 4) \
4283 V(Int32, int32, INT32, int32_t, 4) \
4284 V(Float32, float32, FLOAT32, float, 4) \
4285 V(Float64, float64, FLOAT64, double, 8) \
4286 V(Uint8Clamped, uint8_clamped, UINT8_CLAMPED, uint8_t, 1)
4289 class FixedTypedArrayBase: public FixedArrayBase {
4291 // [base_pointer]: Either points to the FixedTypedArrayBase itself or nullptr.
4292 DECL_ACCESSORS(base_pointer, Object)
4294 // [external_pointer]: Contains the offset between base_pointer and the start
4295 // of the data. If the base_pointer is a nullptr, the external_pointer
4296 // therefore points to the actual backing store.
4297 DECL_ACCESSORS(external_pointer, void)
4299 // Dispatched behavior.
4300 inline void FixedTypedArrayBaseIterateBody(ObjectVisitor* v);
4302 template <typename StaticVisitor>
4303 inline void FixedTypedArrayBaseIterateBody();
4305 DECLARE_CAST(FixedTypedArrayBase)
4307 static const int kBasePointerOffset = FixedArrayBase::kHeaderSize;
4308 static const int kExternalPointerOffset = kBasePointerOffset + kPointerSize;
4309 static const int kHeaderSize =
4310 DOUBLE_POINTER_ALIGN(kExternalPointerOffset + kPointerSize);
4312 static const int kDataOffset = kHeaderSize;
4316 static inline int TypedArraySize(InstanceType type, int length);
4317 inline int TypedArraySize(InstanceType type);
4319 // Use with care: returns raw pointer into heap.
4320 inline void* DataPtr();
4322 inline int DataSize();
4325 static inline int ElementSize(InstanceType type);
4327 inline int DataSize(InstanceType type);
4329 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
4333 template <class Traits>
4334 class FixedTypedArray: public FixedTypedArrayBase {
4336 typedef typename Traits::ElementType ElementType;
4337 static const InstanceType kInstanceType = Traits::kInstanceType;
4339 DECLARE_CAST(FixedTypedArray<Traits>)
4341 inline ElementType get_scalar(int index);
4342 static inline Handle<Object> get(Handle<FixedTypedArray> array, int index);
4343 inline void set(int index, ElementType value);
4345 static inline ElementType from_int(int value);
4346 static inline ElementType from_double(double value);
4348 // This accessor applies the correct conversion from Smi, HeapNumber
4350 void SetValue(uint32_t index, Object* value);
4352 DECLARE_PRINTER(FixedTypedArray)
4353 DECLARE_VERIFIER(FixedTypedArray)
4356 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
4359 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size) \
4360 class Type##ArrayTraits { \
4361 public: /* NOLINT */ \
4362 typedef elementType ElementType; \
4363 static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE; \
4364 static const char* Designator() { return #type " array"; } \
4365 static inline Handle<Object> ToHandle(Isolate* isolate, \
4366 elementType scalar); \
4367 static inline elementType defaultValue(); \
4370 typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
4372 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
4374 #undef FIXED_TYPED_ARRAY_TRAITS
4377 // DeoptimizationInputData is a fixed array used to hold the deoptimization
4378 // data for code generated by the Hydrogen/Lithium compiler. It also
4379 // contains information about functions that were inlined. If N different
4380 // functions were inlined then first N elements of the literal array will
4381 // contain these functions.
4384 class DeoptimizationInputData: public FixedArray {
4386 // Layout description. Indices in the array.
4387 static const int kTranslationByteArrayIndex = 0;
4388 static const int kInlinedFunctionCountIndex = 1;
4389 static const int kLiteralArrayIndex = 2;
4390 static const int kOsrAstIdIndex = 3;
4391 static const int kOsrPcOffsetIndex = 4;
4392 static const int kOptimizationIdIndex = 5;
4393 static const int kSharedFunctionInfoIndex = 6;
4394 static const int kWeakCellCacheIndex = 7;
4395 static const int kFirstDeoptEntryIndex = 8;
4397 // Offsets of deopt entry elements relative to the start of the entry.
4398 static const int kAstIdRawOffset = 0;
4399 static const int kTranslationIndexOffset = 1;
4400 static const int kArgumentsStackHeightOffset = 2;
4401 static const int kPcOffset = 3;
4402 static const int kDeoptEntrySize = 4;
4404 // Simple element accessors.
4405 #define DEFINE_ELEMENT_ACCESSORS(name, type) \
4407 return type::cast(get(k##name##Index)); \
4409 void Set##name(type* value) { \
4410 set(k##name##Index, value); \
4413 DEFINE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
4414 DEFINE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
4415 DEFINE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
4416 DEFINE_ELEMENT_ACCESSORS(OsrAstId, Smi)
4417 DEFINE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
4418 DEFINE_ELEMENT_ACCESSORS(OptimizationId, Smi)
4419 DEFINE_ELEMENT_ACCESSORS(SharedFunctionInfo, Object)
4420 DEFINE_ELEMENT_ACCESSORS(WeakCellCache, Object)
4422 #undef DEFINE_ELEMENT_ACCESSORS
4424 // Accessors for elements of the ith deoptimization entry.
4425 #define DEFINE_ENTRY_ACCESSORS(name, type) \
4426 type* name(int i) { \
4427 return type::cast(get(IndexForEntry(i) + k##name##Offset)); \
4429 void Set##name(int i, type* value) { \
4430 set(IndexForEntry(i) + k##name##Offset, value); \
4433 DEFINE_ENTRY_ACCESSORS(AstIdRaw, Smi)
4434 DEFINE_ENTRY_ACCESSORS(TranslationIndex, Smi)
4435 DEFINE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
4436 DEFINE_ENTRY_ACCESSORS(Pc, Smi)
4438 #undef DEFINE_DEOPT_ENTRY_ACCESSORS
4440 BailoutId AstId(int i) {
4441 return BailoutId(AstIdRaw(i)->value());
4444 void SetAstId(int i, BailoutId value) {
4445 SetAstIdRaw(i, Smi::FromInt(value.ToInt()));
4449 return (length() - kFirstDeoptEntryIndex) / kDeoptEntrySize;
4452 // Allocates a DeoptimizationInputData.
4453 static Handle<DeoptimizationInputData> New(Isolate* isolate,
4454 int deopt_entry_count,
4455 PretenureFlag pretenure);
4457 DECLARE_CAST(DeoptimizationInputData)
4459 #ifdef ENABLE_DISASSEMBLER
4460 void DeoptimizationInputDataPrint(std::ostream& os); // NOLINT
4464 static int IndexForEntry(int i) {
4465 return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
4469 static int LengthFor(int entry_count) { return IndexForEntry(entry_count); }
4473 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
4474 // data for code generated by the full compiler.
4475 // The format of the these objects is
4476 // [i * 2]: Ast ID for ith deoptimization.
4477 // [i * 2 + 1]: PC and state of ith deoptimization
4478 class DeoptimizationOutputData: public FixedArray {
4480 int DeoptPoints() { return length() / 2; }
4482 BailoutId AstId(int index) {
4483 return BailoutId(Smi::cast(get(index * 2))->value());
4486 void SetAstId(int index, BailoutId id) {
4487 set(index * 2, Smi::FromInt(id.ToInt()));
4490 Smi* PcAndState(int index) { return Smi::cast(get(1 + index * 2)); }
4491 void SetPcAndState(int index, Smi* offset) { set(1 + index * 2, offset); }
4493 static int LengthOfFixedArray(int deopt_points) {
4494 return deopt_points * 2;
4497 // Allocates a DeoptimizationOutputData.
4498 static Handle<DeoptimizationOutputData> New(Isolate* isolate,
4499 int number_of_deopt_points,
4500 PretenureFlag pretenure);
4502 DECLARE_CAST(DeoptimizationOutputData)
4504 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4505 void DeoptimizationOutputDataPrint(std::ostream& os); // NOLINT
4510 // HandlerTable is a fixed array containing entries for exception handlers in
4511 // the code object it is associated with. The tables comes in two flavors:
4512 // 1) Based on ranges: Used for unoptimized code. Contains one entry per
4513 // exception handler and a range representing the try-block covered by that
4514 // handler. Layout looks as follows:
4515 // [ range-start , range-end , handler-offset , stack-depth ]
4516 // 2) Based on return addresses: Used for turbofanned code. Contains one entry
4517 // per call-site that could throw an exception. Layout looks as follows:
4518 // [ return-address-offset , handler-offset ]
4519 class HandlerTable : public FixedArray {
4521 // Conservative prediction whether a given handler will locally catch an
4522 // exception or cause a re-throw to outside the code boundary. Since this is
4523 // undecidable it is merely an approximation (e.g. useful for debugger).
4524 enum CatchPrediction { UNCAUGHT, CAUGHT };
4526 // Accessors for handler table based on ranges.
4527 void SetRangeStart(int index, int value) {
4528 set(index * kRangeEntrySize + kRangeStartIndex, Smi::FromInt(value));
4530 void SetRangeEnd(int index, int value) {
4531 set(index * kRangeEntrySize + kRangeEndIndex, Smi::FromInt(value));
4533 void SetRangeHandler(int index, int offset, CatchPrediction prediction) {
4534 int value = HandlerOffsetField::encode(offset) |
4535 HandlerPredictionField::encode(prediction);
4536 set(index * kRangeEntrySize + kRangeHandlerIndex, Smi::FromInt(value));
4538 void SetRangeDepth(int index, int value) {
4539 set(index * kRangeEntrySize + kRangeDepthIndex, Smi::FromInt(value));
4542 // Accessors for handler table based on return addresses.
4543 void SetReturnOffset(int index, int value) {
4544 set(index * kReturnEntrySize + kReturnOffsetIndex, Smi::FromInt(value));
4546 void SetReturnHandler(int index, int offset, CatchPrediction prediction) {
4547 int value = HandlerOffsetField::encode(offset) |
4548 HandlerPredictionField::encode(prediction);
4549 set(index * kReturnEntrySize + kReturnHandlerIndex, Smi::FromInt(value));
4552 // Lookup handler in a table based on ranges.
4553 int LookupRange(int pc_offset, int* stack_depth, CatchPrediction* prediction);
4555 // Lookup handler in a table based on return addresses.
4556 int LookupReturn(int pc_offset, CatchPrediction* prediction);
4558 // Returns the required length of the underlying fixed array.
4559 static int LengthForRange(int entries) { return entries * kRangeEntrySize; }
4560 static int LengthForReturn(int entries) { return entries * kReturnEntrySize; }
4562 DECLARE_CAST(HandlerTable)
4564 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4565 void HandlerTableRangePrint(std::ostream& os); // NOLINT
4566 void HandlerTableReturnPrint(std::ostream& os); // NOLINT
4570 // Layout description for handler table based on ranges.
4571 static const int kRangeStartIndex = 0;
4572 static const int kRangeEndIndex = 1;
4573 static const int kRangeHandlerIndex = 2;
4574 static const int kRangeDepthIndex = 3;
4575 static const int kRangeEntrySize = 4;
4577 // Layout description for handler table based on return addresses.
4578 static const int kReturnOffsetIndex = 0;
4579 static const int kReturnHandlerIndex = 1;
4580 static const int kReturnEntrySize = 2;
4582 // Encoding of the {handler} field.
4583 class HandlerPredictionField : public BitField<CatchPrediction, 0, 1> {};
4584 class HandlerOffsetField : public BitField<int, 1, 30> {};
4588 // Code describes objects with on-the-fly generated machine code.
4589 class Code: public HeapObject {
4591 // Opaque data type for encapsulating code flags like kind, inline
4592 // cache state, and arguments count.
4593 typedef uint32_t Flags;
4595 #define NON_IC_KIND_LIST(V) \
4597 V(OPTIMIZED_FUNCTION) \
4603 #define IC_KIND_LIST(V) \
4614 #define CODE_KIND_LIST(V) \
4615 NON_IC_KIND_LIST(V) \
4619 #define DEFINE_CODE_KIND_ENUM(name) name,
4620 CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
4621 #undef DEFINE_CODE_KIND_ENUM
4625 // No more than 16 kinds. The value is currently encoded in four bits in
4627 STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
4629 static const char* Kind2String(Kind kind);
4637 static const int kPrologueOffsetNotSet = -1;
4639 #ifdef ENABLE_DISASSEMBLER
4641 static const char* ICState2String(InlineCacheState state);
4642 static const char* StubType2String(StubType type);
4643 static void PrintExtraICState(std::ostream& os, // NOLINT
4644 Kind kind, ExtraICState extra);
4645 void Disassemble(const char* name, std::ostream& os); // NOLINT
4646 #endif // ENABLE_DISASSEMBLER
4648 // [instruction_size]: Size of the native instructions
4649 inline int instruction_size() const;
4650 inline void set_instruction_size(int value);
4652 // [relocation_info]: Code relocation information
4653 DECL_ACCESSORS(relocation_info, ByteArray)
4654 void InvalidateRelocation();
4655 void InvalidateEmbeddedObjects();
4657 // [handler_table]: Fixed array containing offsets of exception handlers.
4658 DECL_ACCESSORS(handler_table, FixedArray)
4660 // [deoptimization_data]: Array containing data for deopt.
4661 DECL_ACCESSORS(deoptimization_data, FixedArray)
4663 // [raw_type_feedback_info]: This field stores various things, depending on
4664 // the kind of the code object.
4665 // FUNCTION => type feedback information.
4666 // STUB and ICs => major/minor key as Smi.
4667 DECL_ACCESSORS(raw_type_feedback_info, Object)
4668 inline Object* type_feedback_info();
4669 inline void set_type_feedback_info(
4670 Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
4671 inline uint32_t stub_key();
4672 inline void set_stub_key(uint32_t key);
4674 // [next_code_link]: Link for lists of optimized or deoptimized code.
4675 // Note that storage for this field is overlapped with typefeedback_info.
4676 DECL_ACCESSORS(next_code_link, Object)
4678 // [gc_metadata]: Field used to hold GC related metadata. The contents of this
4679 // field does not have to be traced during garbage collection since
4680 // it is only used by the garbage collector itself.
4681 DECL_ACCESSORS(gc_metadata, Object)
4683 // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
4684 // at the moment when this object was created.
4685 inline void set_ic_age(int count);
4686 inline int ic_age() const;
4688 // [prologue_offset]: Offset of the function prologue, used for aging
4689 // FUNCTIONs and OPTIMIZED_FUNCTIONs.
4690 inline int prologue_offset() const;
4691 inline void set_prologue_offset(int offset);
4693 // [constant_pool offset]: Offset of the constant pool.
4694 // Valid for FLAG_enable_embedded_constant_pool only
4695 inline int constant_pool_offset() const;
4696 inline void set_constant_pool_offset(int offset);
4698 // Unchecked accessors to be used during GC.
4699 inline ByteArray* unchecked_relocation_info();
4701 inline int relocation_size();
4703 // [flags]: Various code flags.
4704 inline Flags flags();
4705 inline void set_flags(Flags flags);
4707 // [flags]: Access to specific code flags.
4709 inline InlineCacheState ic_state(); // Only valid for IC stubs.
4710 inline ExtraICState extra_ic_state(); // Only valid for IC stubs.
4712 inline StubType type(); // Only valid for monomorphic IC stubs.
4714 // Testers for IC stub kinds.
4715 inline bool is_inline_cache_stub();
4716 inline bool is_debug_stub();
4717 inline bool is_handler() { return kind() == HANDLER; }
4718 inline bool is_load_stub() { return kind() == LOAD_IC; }
4719 inline bool is_keyed_load_stub() { return kind() == KEYED_LOAD_IC; }
4720 inline bool is_store_stub() { return kind() == STORE_IC; }
4721 inline bool is_keyed_store_stub() { return kind() == KEYED_STORE_IC; }
4722 inline bool is_call_stub() { return kind() == CALL_IC; }
4723 inline bool is_binary_op_stub() { return kind() == BINARY_OP_IC; }
4724 inline bool is_compare_ic_stub() { return kind() == COMPARE_IC; }
4725 inline bool is_compare_nil_ic_stub() { return kind() == COMPARE_NIL_IC; }
4726 inline bool is_to_boolean_ic_stub() { return kind() == TO_BOOLEAN_IC; }
4727 inline bool is_keyed_stub();
4728 inline bool is_optimized_code() { return kind() == OPTIMIZED_FUNCTION; }
4729 inline bool embeds_maps_weakly() {
4731 return (k == LOAD_IC || k == STORE_IC || k == KEYED_LOAD_IC ||
4732 k == KEYED_STORE_IC || k == COMPARE_NIL_IC) &&
4733 ic_state() == MONOMORPHIC;
4736 inline bool IsCodeStubOrIC();
4738 inline void set_raw_kind_specific_flags1(int value);
4739 inline void set_raw_kind_specific_flags2(int value);
4741 // [is_crankshafted]: For kind STUB or ICs, tells whether or not a code
4742 // object was generated by either the hydrogen or the TurboFan optimizing
4743 // compiler (but it may not be an optimized function).
4744 inline bool is_crankshafted();
4745 inline bool is_hydrogen_stub(); // Crankshafted, but not a function.
4746 inline void set_is_crankshafted(bool value);
4748 // [is_turbofanned]: For kind STUB or OPTIMIZED_FUNCTION, tells whether the
4749 // code object was generated by the TurboFan optimizing compiler.
4750 inline bool is_turbofanned();
4751 inline void set_is_turbofanned(bool value);
4753 // [can_have_weak_objects]: For kind OPTIMIZED_FUNCTION, tells whether the
4754 // embedded objects in code should be treated weakly.
4755 inline bool can_have_weak_objects();
4756 inline void set_can_have_weak_objects(bool value);
4758 // [has_deoptimization_support]: For FUNCTION kind, tells if it has
4759 // deoptimization support.
4760 inline bool has_deoptimization_support();
4761 inline void set_has_deoptimization_support(bool value);
4763 // [has_debug_break_slots]: For FUNCTION kind, tells if it has
4764 // been compiled with debug break slots.
4765 inline bool has_debug_break_slots();
4766 inline void set_has_debug_break_slots(bool value);
4768 // [has_reloc_info_for_serialization]: For FUNCTION kind, tells if its
4769 // reloc info includes runtime and external references to support
4770 // serialization/deserialization.
4771 inline bool has_reloc_info_for_serialization();
4772 inline void set_has_reloc_info_for_serialization(bool value);
4774 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
4775 // how long the function has been marked for OSR and therefore which
4776 // level of loop nesting we are willing to do on-stack replacement
4778 inline void set_allow_osr_at_loop_nesting_level(int level);
4779 inline int allow_osr_at_loop_nesting_level();
4781 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
4782 // the code object was seen on the stack with no IC patching going on.
4783 inline int profiler_ticks();
4784 inline void set_profiler_ticks(int ticks);
4786 // [builtin_index]: For BUILTIN kind, tells which builtin index it has.
4787 // For builtins, tells which builtin index it has.
4788 // Note that builtins can have a code kind other than BUILTIN, which means
4789 // that for arbitrary code objects, this index value may be random garbage.
4790 // To verify in that case, compare the code object to the indexed builtin.
4791 inline int builtin_index();
4792 inline void set_builtin_index(int id);
4794 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
4795 // reserved in the code prologue.
4796 inline unsigned stack_slots();
4797 inline void set_stack_slots(unsigned slots);
4799 // [safepoint_table_start]: For kind OPTIMIZED_FUNCTION, the offset in
4800 // the instruction stream where the safepoint table starts.
4801 inline unsigned safepoint_table_offset();
4802 inline void set_safepoint_table_offset(unsigned offset);
4804 // [back_edge_table_start]: For kind FUNCTION, the offset in the
4805 // instruction stream where the back edge table starts.
4806 inline unsigned back_edge_table_offset();
4807 inline void set_back_edge_table_offset(unsigned offset);
4809 inline bool back_edges_patched_for_osr();
4811 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
4812 inline uint16_t to_boolean_state();
4814 // [has_function_cache]: For kind STUB tells whether there is a function
4815 // cache is passed to the stub.
4816 inline bool has_function_cache();
4817 inline void set_has_function_cache(bool flag);
4820 // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
4821 // the code is going to be deoptimized because of dead embedded maps.
4822 inline bool marked_for_deoptimization();
4823 inline void set_marked_for_deoptimization(bool flag);
4825 // [constant_pool]: The constant pool for this function.
4826 inline Address constant_pool();
4828 // Get the safepoint entry for the given pc.
4829 SafepointEntry GetSafepointEntry(Address pc);
4831 // Find an object in a stub with a specified map
4832 Object* FindNthObject(int n, Map* match_map);
4834 // Find the first allocation site in an IC stub.
4835 AllocationSite* FindFirstAllocationSite();
4837 // Find the first map in an IC stub.
4838 Map* FindFirstMap();
4839 void FindAllMaps(MapHandleList* maps);
4841 // Find the first handler in an IC stub.
4842 Code* FindFirstHandler();
4844 // Find |length| handlers and put them into |code_list|. Returns false if not
4845 // enough handlers can be found.
4846 bool FindHandlers(CodeHandleList* code_list, int length = -1);
4848 // Find the handler for |map|.
4849 MaybeHandle<Code> FindHandlerForMap(Map* map);
4851 // Find the first name in an IC stub.
4852 Name* FindFirstName();
4854 class FindAndReplacePattern;
4855 // For each (map-to-find, object-to-replace) pair in the pattern, this
4856 // function replaces the corresponding placeholder in the code with the
4857 // object-to-replace. The function assumes that pairs in the pattern come in
4858 // the same order as the placeholders in the code.
4859 // If the placeholder is a weak cell, then the value of weak cell is matched
4860 // against the map-to-find.
4861 void FindAndReplace(const FindAndReplacePattern& pattern);
4863 // The entire code object including its header is copied verbatim to the
4864 // snapshot so that it can be written in one, fast, memcpy during
4865 // deserialization. The deserializer will overwrite some pointers, rather
4866 // like a runtime linker, but the random allocation addresses used in the
4867 // mksnapshot process would still be present in the unlinked snapshot data,
4868 // which would make snapshot production non-reproducible. This method wipes
4869 // out the to-be-overwritten header data for reproducible snapshots.
4870 inline void WipeOutHeader();
4872 // Flags operations.
4873 static inline Flags ComputeFlags(
4874 Kind kind, InlineCacheState ic_state = UNINITIALIZED,
4875 ExtraICState extra_ic_state = kNoExtraICState, StubType type = NORMAL,
4876 CacheHolderFlag holder = kCacheOnReceiver);
4878 static inline Flags ComputeMonomorphicFlags(
4879 Kind kind, ExtraICState extra_ic_state = kNoExtraICState,
4880 CacheHolderFlag holder = kCacheOnReceiver, StubType type = NORMAL);
4882 static inline Flags ComputeHandlerFlags(
4883 Kind handler_kind, StubType type = NORMAL,
4884 CacheHolderFlag holder = kCacheOnReceiver);
4886 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
4887 static inline StubType ExtractTypeFromFlags(Flags flags);
4888 static inline CacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
4889 static inline Kind ExtractKindFromFlags(Flags flags);
4890 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
4892 static inline Flags RemoveTypeFromFlags(Flags flags);
4893 static inline Flags RemoveTypeAndHolderFromFlags(Flags flags);
4895 // Convert a target address into a code object.
4896 static inline Code* GetCodeFromTargetAddress(Address address);
4898 // Convert an entry address into an object.
4899 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
4901 // Returns the address of the first instruction.
4902 inline byte* instruction_start();
4904 // Returns the address right after the last instruction.
4905 inline byte* instruction_end();
4907 // Returns the size of the instructions, padding, and relocation information.
4908 inline int body_size();
4910 // Returns the address of the first relocation info (read backwards!).
4911 inline byte* relocation_start();
4913 // Code entry point.
4914 inline byte* entry();
4916 // Returns true if pc is inside this object's instructions.
4917 inline bool contains(byte* pc);
4919 // Relocate the code by delta bytes. Called to signal that this code
4920 // object has been moved by delta bytes.
4921 void Relocate(intptr_t delta);
4923 // Migrate code described by desc.
4924 void CopyFrom(const CodeDesc& desc);
4926 // Returns the object size for a given body (used for allocation).
4927 static int SizeFor(int body_size) {
4928 DCHECK_SIZE_TAG_ALIGNED(body_size);
4929 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
4932 // Calculate the size of the code object to report for log events. This takes
4933 // the layout of the code object into account.
4934 int ExecutableSize() {
4935 // Check that the assumptions about the layout of the code object holds.
4936 DCHECK_EQ(static_cast<int>(instruction_start() - address()),
4938 return instruction_size() + Code::kHeaderSize;
4941 // Locating source position.
4942 int SourcePosition(Address pc);
4943 int SourceStatementPosition(Address pc);
4947 // Dispatched behavior.
4948 int CodeSize() { return SizeFor(body_size()); }
4949 inline void CodeIterateBody(ObjectVisitor* v);
4951 template<typename StaticVisitor>
4952 inline void CodeIterateBody(Heap* heap);
4954 DECLARE_PRINTER(Code)
4955 DECLARE_VERIFIER(Code)
4957 void ClearInlineCaches();
4958 void ClearInlineCaches(Kind kind);
4960 BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
4961 uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
4963 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
4965 kToBeExecutedOnceCodeAge = -3,
4966 kNotExecutedCodeAge = -2,
4967 kExecutedOnceCodeAge = -1,
4969 CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
4971 kFirstCodeAge = kToBeExecutedOnceCodeAge,
4972 kLastCodeAge = kAfterLastCodeAge - 1,
4973 kCodeAgeCount = kAfterLastCodeAge - kFirstCodeAge - 1,
4974 kIsOldCodeAge = kSexagenarianCodeAge,
4975 kPreAgedCodeAge = kIsOldCodeAge - 1
4977 #undef DECLARE_CODE_AGE_ENUM
4979 // Code aging. Indicates how many full GCs this code has survived without
4980 // being entered through the prologue. Used to determine when it is
4981 // relatively safe to flush this code object and replace it with the lazy
4982 // compilation stub.
4983 static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
4984 static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
4985 void MakeYoung(Isolate* isolate);
4986 void MarkToBeExecutedOnce(Isolate* isolate);
4987 void MakeOlder(MarkingParity);
4988 static bool IsYoungSequence(Isolate* isolate, byte* sequence);
4991 static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
4992 return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
4995 void PrintDeoptLocation(FILE* out, Address pc);
4996 bool CanDeoptAt(Address pc);
4999 void VerifyEmbeddedObjectsDependency();
5003 enum VerifyMode { kNoContextSpecificPointers, kNoContextRetainingPointers };
5004 void VerifyEmbeddedObjects(VerifyMode mode = kNoContextRetainingPointers);
5005 static void VerifyRecompiledCode(Code* old_code, Code* new_code);
5008 inline bool CanContainWeakObjects() {
5009 // is_turbofanned() implies !can_have_weak_objects().
5010 DCHECK(!is_optimized_code() || !is_turbofanned() ||
5011 !can_have_weak_objects());
5012 return is_optimized_code() && can_have_weak_objects();
5015 inline bool IsWeakObject(Object* object) {
5016 return (CanContainWeakObjects() && IsWeakObjectInOptimizedCode(object));
5019 static inline bool IsWeakObjectInOptimizedCode(Object* object);
5021 static Handle<WeakCell> WeakCellFor(Handle<Code> code);
5022 WeakCell* CachedWeakCell();
5024 // Max loop nesting marker used to postpose OSR. We don't take loop
5025 // nesting that is deeper than 5 levels into account.
5026 static const int kMaxLoopNestingMarker = 6;
5028 static const int kConstantPoolSize =
5029 FLAG_enable_embedded_constant_pool ? kIntSize : 0;
5031 // Layout description.
5032 static const int kRelocationInfoOffset = HeapObject::kHeaderSize;
5033 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
5034 static const int kDeoptimizationDataOffset =
5035 kHandlerTableOffset + kPointerSize;
5036 // For FUNCTION kind, we store the type feedback info here.
5037 static const int kTypeFeedbackInfoOffset =
5038 kDeoptimizationDataOffset + kPointerSize;
5039 static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
5040 static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
5041 static const int kInstructionSizeOffset = kGCMetadataOffset + kPointerSize;
5042 static const int kICAgeOffset = kInstructionSizeOffset + kIntSize;
5043 static const int kFlagsOffset = kICAgeOffset + kIntSize;
5044 static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
5045 static const int kKindSpecificFlags2Offset =
5046 kKindSpecificFlags1Offset + kIntSize;
5047 // Note: We might be able to squeeze this into the flags above.
5048 static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
5049 static const int kConstantPoolOffset = kPrologueOffset + kIntSize;
5050 static const int kHeaderPaddingStart =
5051 kConstantPoolOffset + kConstantPoolSize;
5053 // Add padding to align the instruction start following right after
5054 // the Code object header.
5055 static const int kHeaderSize =
5056 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
5058 // Byte offsets within kKindSpecificFlags1Offset.
5059 static const int kFullCodeFlags = kKindSpecificFlags1Offset;
5060 class FullCodeFlagsHasDeoptimizationSupportField:
5061 public BitField<bool, 0, 1> {}; // NOLINT
5062 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
5063 class FullCodeFlagsHasRelocInfoForSerialization
5064 : public BitField<bool, 2, 1> {};
5065 // Bit 3 in this bitfield is unused.
5066 class ProfilerTicksField : public BitField<int, 4, 28> {};
5068 // Flags layout. BitField<type, shift, size>.
5069 class ICStateField : public BitField<InlineCacheState, 0, 4> {};
5070 class TypeField : public BitField<StubType, 4, 1> {};
5071 class CacheHolderField : public BitField<CacheHolderFlag, 5, 2> {};
5072 class KindField : public BitField<Kind, 7, 4> {};
5073 class ExtraICStateField: public BitField<ExtraICState, 11,
5074 PlatformSmiTagging::kSmiValueSize - 11 + 1> {}; // NOLINT
5076 // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
5077 static const int kStackSlotsFirstBit = 0;
5078 static const int kStackSlotsBitCount = 24;
5079 static const int kHasFunctionCacheBit =
5080 kStackSlotsFirstBit + kStackSlotsBitCount;
5081 static const int kMarkedForDeoptimizationBit = kHasFunctionCacheBit + 1;
5082 static const int kIsTurbofannedBit = kMarkedForDeoptimizationBit + 1;
5083 static const int kCanHaveWeakObjects = kIsTurbofannedBit + 1;
5085 STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
5086 STATIC_ASSERT(kCanHaveWeakObjects + 1 <= 32);
5088 class StackSlotsField: public BitField<int,
5089 kStackSlotsFirstBit, kStackSlotsBitCount> {}; // NOLINT
5090 class HasFunctionCacheField : public BitField<bool, kHasFunctionCacheBit, 1> {
5092 class MarkedForDeoptimizationField
5093 : public BitField<bool, kMarkedForDeoptimizationBit, 1> {}; // NOLINT
5094 class IsTurbofannedField : public BitField<bool, kIsTurbofannedBit, 1> {
5096 class CanHaveWeakObjectsField
5097 : public BitField<bool, kCanHaveWeakObjects, 1> {}; // NOLINT
5099 // KindSpecificFlags2 layout (ALL)
5100 static const int kIsCrankshaftedBit = 0;
5101 class IsCrankshaftedField: public BitField<bool,
5102 kIsCrankshaftedBit, 1> {}; // NOLINT
5104 // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
5105 static const int kSafepointTableOffsetFirstBit = kIsCrankshaftedBit + 1;
5106 static const int kSafepointTableOffsetBitCount = 30;
5108 STATIC_ASSERT(kSafepointTableOffsetFirstBit +
5109 kSafepointTableOffsetBitCount <= 32);
5110 STATIC_ASSERT(1 + kSafepointTableOffsetBitCount <= 32);
5112 class SafepointTableOffsetField: public BitField<int,
5113 kSafepointTableOffsetFirstBit,
5114 kSafepointTableOffsetBitCount> {}; // NOLINT
5116 // KindSpecificFlags2 layout (FUNCTION)
5117 class BackEdgeTableOffsetField: public BitField<int,
5118 kIsCrankshaftedBit + 1, 27> {}; // NOLINT
5119 class AllowOSRAtLoopNestingLevelField: public BitField<int,
5120 kIsCrankshaftedBit + 1 + 27, 4> {}; // NOLINT
5121 STATIC_ASSERT(AllowOSRAtLoopNestingLevelField::kMax >= kMaxLoopNestingMarker);
5123 static const int kArgumentsBits = 16;
5124 static const int kMaxArguments = (1 << kArgumentsBits) - 1;
5126 // This constant should be encodable in an ARM instruction.
5127 static const int kFlagsNotUsedInLookup =
5128 TypeField::kMask | CacheHolderField::kMask;
5131 friend class RelocIterator;
5132 friend class Deoptimizer; // For FindCodeAgeSequence.
5134 void ClearInlineCaches(Kind* kind);
5137 byte* FindCodeAgeSequence();
5138 static void GetCodeAgeAndParity(Code* code, Age* age,
5139 MarkingParity* parity);
5140 static void GetCodeAgeAndParity(Isolate* isolate, byte* sequence, Age* age,
5141 MarkingParity* parity);
5142 static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
5144 // Code aging -- platform-specific
5145 static void PatchPlatformCodeAge(Isolate* isolate,
5146 byte* sequence, Age age,
5147 MarkingParity parity);
5149 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5153 // This class describes the layout of dependent codes array of a map. The
5154 // array is partitioned into several groups of dependent codes. Each group
5155 // contains codes with the same dependency on the map. The array has the
5156 // following layout for n dependency groups:
5158 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5159 // | C1 | C2 | ... | Cn | group 1 | group 2 | ... | group n | undefined |
5160 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5162 // The first n elements are Smis, each of them specifies the number of codes
5163 // in the corresponding group. The subsequent elements contain grouped code
5164 // objects in weak cells. The suffix of the array can be filled with the
5165 // undefined value if the number of codes is less than the length of the
5166 // array. The order of the code objects within a group is not preserved.
5168 // All code indexes used in the class are counted starting from the first
5169 // code object of the first group. In other words, code index 0 corresponds
5170 // to array index n = kCodesStartIndex.
5172 class DependentCode: public FixedArray {
5174 enum DependencyGroup {
5175 // Group of code that weakly embed this map and depend on being
5176 // deoptimized when the map is garbage collected.
5178 // Group of code that embed a transition to this map, and depend on being
5179 // deoptimized when the transition is replaced by a new version.
5181 // Group of code that omit run-time prototype checks for prototypes
5182 // described by this map. The group is deoptimized whenever an object
5183 // described by this map changes shape (and transitions to a new map),
5184 // possibly invalidating the assumptions embedded in the code.
5185 kPrototypeCheckGroup,
5186 // Group of code that depends on global property values in property cells
5187 // not being changed.
5188 kPropertyCellChangedGroup,
5189 // Group of code that omit run-time type checks for the field(s) introduced
5192 // Group of code that omit run-time type checks for initial maps of
5194 kInitialMapChangedGroup,
5195 // Group of code that depends on tenuring information in AllocationSites
5196 // not being changed.
5197 kAllocationSiteTenuringChangedGroup,
5198 // Group of code that depends on element transition information in
5199 // AllocationSites not being changed.
5200 kAllocationSiteTransitionChangedGroup
5203 static const int kGroupCount = kAllocationSiteTransitionChangedGroup + 1;
5205 // Array for holding the index of the first code object of each group.
5206 // The last element stores the total number of code objects.
5207 class GroupStartIndexes {
5209 explicit GroupStartIndexes(DependentCode* entries);
5210 void Recompute(DependentCode* entries);
5211 int at(int i) { return start_indexes_[i]; }
5212 int number_of_entries() { return start_indexes_[kGroupCount]; }
5214 int start_indexes_[kGroupCount + 1];
5217 bool Contains(DependencyGroup group, WeakCell* code_cell);
5219 static Handle<DependentCode> InsertCompilationDependencies(
5220 Handle<DependentCode> entries, DependencyGroup group,
5221 Handle<Foreign> info);
5223 static Handle<DependentCode> InsertWeakCode(Handle<DependentCode> entries,
5224 DependencyGroup group,
5225 Handle<WeakCell> code_cell);
5227 void UpdateToFinishedCode(DependencyGroup group, Foreign* info,
5228 WeakCell* code_cell);
5230 void RemoveCompilationDependencies(DependentCode::DependencyGroup group,
5233 void DeoptimizeDependentCodeGroup(Isolate* isolate,
5234 DependentCode::DependencyGroup group);
5236 bool MarkCodeForDeoptimization(Isolate* isolate,
5237 DependentCode::DependencyGroup group);
5239 // The following low-level accessors should only be used by this class
5240 // and the mark compact collector.
5241 inline int number_of_entries(DependencyGroup group);
5242 inline void set_number_of_entries(DependencyGroup group, int value);
5243 inline Object* object_at(int i);
5244 inline void set_object_at(int i, Object* object);
5245 inline void clear_at(int i);
5246 inline void copy(int from, int to);
5247 DECLARE_CAST(DependentCode)
5249 static const char* DependencyGroupName(DependencyGroup group);
5250 static void SetMarkedForDeoptimization(Code* code, DependencyGroup group);
5253 static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5254 DependencyGroup group,
5255 Handle<Object> object);
5256 static Handle<DependentCode> EnsureSpace(Handle<DependentCode> entries);
5257 // Make a room at the end of the given group by moving out the first
5258 // code objects of the subsequent groups.
5259 inline void ExtendGroup(DependencyGroup group);
5260 // Compact by removing cleared weak cells and return true if there was
5261 // any cleared weak cell.
5263 static int Grow(int number_of_entries) {
5264 if (number_of_entries < 5) return number_of_entries + 1;
5265 return number_of_entries * 5 / 4;
5267 static const int kCodesStartIndex = kGroupCount;
5271 class PrototypeInfo;
5274 // All heap objects have a Map that describes their structure.
5275 // A Map contains information about:
5276 // - Size information about the object
5277 // - How to iterate over an object (for garbage collection)
5278 class Map: public HeapObject {
5281 // Size in bytes or kVariableSizeSentinel if instances do not have
5283 inline int instance_size();
5284 inline void set_instance_size(int value);
5286 // Only to clear an unused byte, remove once byte is used.
5287 inline void clear_unused();
5289 // Count of properties allocated in the object.
5290 inline int inobject_properties();
5291 inline void set_inobject_properties(int value);
5294 inline InstanceType instance_type();
5295 inline void set_instance_type(InstanceType value);
5297 // Tells how many unused property fields are available in the
5298 // instance (only used for JSObject in fast mode).
5299 inline int unused_property_fields();
5300 inline void set_unused_property_fields(int value);
5303 inline byte bit_field() const;
5304 inline void set_bit_field(byte value);
5307 inline byte bit_field2() const;
5308 inline void set_bit_field2(byte value);
5311 inline uint32_t bit_field3() const;
5312 inline void set_bit_field3(uint32_t bits);
5314 class EnumLengthBits: public BitField<int,
5315 0, kDescriptorIndexBitCount> {}; // NOLINT
5316 class NumberOfOwnDescriptorsBits: public BitField<int,
5317 kDescriptorIndexBitCount, kDescriptorIndexBitCount> {}; // NOLINT
5318 STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
5319 class DictionaryMap : public BitField<bool, 20, 1> {};
5320 class OwnsDescriptors : public BitField<bool, 21, 1> {};
5321 class HasInstanceCallHandler : public BitField<bool, 22, 1> {};
5322 class Deprecated : public BitField<bool, 23, 1> {};
5323 class IsUnstable : public BitField<bool, 24, 1> {};
5324 class IsMigrationTarget : public BitField<bool, 25, 1> {};
5325 class IsStrong : public BitField<bool, 26, 1> {};
5328 // Keep this bit field at the very end for better code in
5329 // Builtins::kJSConstructStubGeneric stub.
5330 // This counter is used for in-object slack tracking and for map aging.
5331 // The in-object slack tracking is considered enabled when the counter is
5332 // in the range [kSlackTrackingCounterStart, kSlackTrackingCounterEnd].
5333 class Counter : public BitField<int, 28, 4> {};
5334 static const int kSlackTrackingCounterStart = 14;
5335 static const int kSlackTrackingCounterEnd = 8;
5336 static const int kRetainingCounterStart = kSlackTrackingCounterEnd - 1;
5337 static const int kRetainingCounterEnd = 0;
5339 // Tells whether the object in the prototype property will be used
5340 // for instances created from this function. If the prototype
5341 // property is set to a value that is not a JSObject, the prototype
5342 // property will not be used to create instances of the function.
5343 // See ECMA-262, 13.2.2.
5344 inline void set_non_instance_prototype(bool value);
5345 inline bool has_non_instance_prototype();
5347 // Tells whether function has special prototype property. If not, prototype
5348 // property will not be created when accessed (will return undefined),
5349 // and construction from this function will not be allowed.
5350 inline void set_function_with_prototype(bool value);
5351 inline bool function_with_prototype();
5353 // Tells whether the instance with this map should be ignored by the
5354 // Object.getPrototypeOf() function and the __proto__ accessor.
5355 inline void set_is_hidden_prototype() {
5356 set_bit_field(bit_field() | (1 << kIsHiddenPrototype));
5359 inline bool is_hidden_prototype() {
5360 return ((1 << kIsHiddenPrototype) & bit_field()) != 0;
5363 // Records and queries whether the instance has a named interceptor.
5364 inline void set_has_named_interceptor() {
5365 set_bit_field(bit_field() | (1 << kHasNamedInterceptor));
5368 inline bool has_named_interceptor() {
5369 return ((1 << kHasNamedInterceptor) & bit_field()) != 0;
5372 // Records and queries whether the instance has an indexed interceptor.
5373 inline void set_has_indexed_interceptor() {
5374 set_bit_field(bit_field() | (1 << kHasIndexedInterceptor));
5377 inline bool has_indexed_interceptor() {
5378 return ((1 << kHasIndexedInterceptor) & bit_field()) != 0;
5381 // Tells whether the instance is undetectable.
5382 // An undetectable object is a special class of JSObject: 'typeof' operator
5383 // returns undefined, ToBoolean returns false. Otherwise it behaves like
5384 // a normal JS object. It is useful for implementing undetectable
5385 // document.all in Firefox & Safari.
5386 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
5387 inline void set_is_undetectable() {
5388 set_bit_field(bit_field() | (1 << kIsUndetectable));
5391 inline bool is_undetectable() {
5392 return ((1 << kIsUndetectable) & bit_field()) != 0;
5395 // Tells whether the instance has a call-as-function handler.
5396 inline void set_is_observed() {
5397 set_bit_field(bit_field() | (1 << kIsObserved));
5400 inline bool is_observed() {
5401 return ((1 << kIsObserved) & bit_field()) != 0;
5404 inline void set_is_strong();
5405 inline bool is_strong();
5406 inline void set_is_extensible(bool value);
5407 inline bool is_extensible();
5408 inline void set_is_prototype_map(bool value);
5409 inline bool is_prototype_map() const;
5411 inline void set_elements_kind(ElementsKind elements_kind) {
5412 DCHECK(static_cast<int>(elements_kind) < kElementsKindCount);
5413 DCHECK(kElementsKindCount <= (1 << Map::ElementsKindBits::kSize));
5414 set_bit_field2(Map::ElementsKindBits::update(bit_field2(), elements_kind));
5415 DCHECK(this->elements_kind() == elements_kind);
5418 inline ElementsKind elements_kind() {
5419 return Map::ElementsKindBits::decode(bit_field2());
5422 // Tells whether the instance has fast elements that are only Smis.
5423 inline bool has_fast_smi_elements() {
5424 return IsFastSmiElementsKind(elements_kind());
5427 // Tells whether the instance has fast elements.
5428 inline bool has_fast_object_elements() {
5429 return IsFastObjectElementsKind(elements_kind());
5432 inline bool has_fast_smi_or_object_elements() {
5433 return IsFastSmiOrObjectElementsKind(elements_kind());
5436 inline bool has_fast_double_elements() {
5437 return IsFastDoubleElementsKind(elements_kind());
5440 inline bool has_fast_elements() {
5441 return IsFastElementsKind(elements_kind());
5444 inline bool has_sloppy_arguments_elements() {
5445 return IsSloppyArgumentsElements(elements_kind());
5448 inline bool has_fixed_typed_array_elements() {
5449 return IsFixedTypedArrayElementsKind(elements_kind());
5452 inline bool has_dictionary_elements() {
5453 return IsDictionaryElementsKind(elements_kind());
5456 static bool IsValidElementsTransition(ElementsKind from_kind,
5457 ElementsKind to_kind);
5459 // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
5460 // map with DICTIONARY_ELEMENTS was found in the prototype chain.
5461 bool DictionaryElementsInPrototypeChainOnly();
5463 inline Map* ElementsTransitionMap();
5465 inline FixedArrayBase* GetInitialElements();
5467 // [raw_transitions]: Provides access to the transitions storage field.
5468 // Don't call set_raw_transitions() directly to overwrite transitions, use
5469 // the TransitionArray::ReplaceTransitions() wrapper instead!
5470 DECL_ACCESSORS(raw_transitions, Object)
5471 // [prototype_info]: Per-prototype metadata. Aliased with transitions
5472 // (which prototype maps don't have).
5473 DECL_ACCESSORS(prototype_info, Object)
5474 // PrototypeInfo is created lazily using this helper (which installs it on
5475 // the given prototype's map).
5476 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5477 Handle<JSObject> prototype, Isolate* isolate);
5479 // [prototype chain validity cell]: Associated with a prototype object,
5480 // stored in that object's map's PrototypeInfo, indicates that prototype
5481 // chains through this object are currently valid. The cell will be
5482 // invalidated and replaced when the prototype chain changes.
5483 static Handle<Cell> GetOrCreatePrototypeChainValidityCell(Handle<Map> map,
5485 static const int kPrototypeChainValid = 0;
5486 static const int kPrototypeChainInvalid = 1;
5489 Map* FindFieldOwner(int descriptor);
5491 inline int GetInObjectPropertyOffset(int index);
5493 int NumberOfFields();
5495 // TODO(ishell): candidate with JSObject::MigrateToMap().
5496 bool InstancesNeedRewriting(Map* target, int target_number_of_fields,
5497 int target_inobject, int target_unused,
5498 int* old_number_of_fields);
5499 // TODO(ishell): moveit!
5500 static Handle<Map> GeneralizeAllFieldRepresentations(Handle<Map> map);
5501 MUST_USE_RESULT static Handle<HeapType> GeneralizeFieldType(
5502 Handle<HeapType> type1,
5503 Handle<HeapType> type2,
5505 static void GeneralizeFieldType(Handle<Map> map, int modify_index,
5506 Representation new_representation,
5507 Handle<HeapType> new_field_type);
5508 static Handle<Map> ReconfigureProperty(Handle<Map> map, int modify_index,
5509 PropertyKind new_kind,
5510 PropertyAttributes new_attributes,
5511 Representation new_representation,
5512 Handle<HeapType> new_field_type,
5513 StoreMode store_mode);
5514 static Handle<Map> CopyGeneralizeAllRepresentations(
5515 Handle<Map> map, int modify_index, StoreMode store_mode,
5516 PropertyKind kind, PropertyAttributes attributes, const char* reason);
5518 static Handle<Map> PrepareForDataProperty(Handle<Map> old_map,
5519 int descriptor_number,
5520 Handle<Object> value);
5522 static Handle<Map> Normalize(Handle<Map> map, PropertyNormalizationMode mode,
5523 const char* reason);
5525 // Returns the constructor name (the name (possibly, inferred name) of the
5526 // function that was used to instantiate the object).
5527 String* constructor_name();
5529 // Tells whether the map is used for JSObjects in dictionary mode (ie
5530 // normalized objects, ie objects for which HasFastProperties returns false).
5531 // A map can never be used for both dictionary mode and fast mode JSObjects.
5532 // False by default and for HeapObjects that are not JSObjects.
5533 inline void set_dictionary_map(bool value);
5534 inline bool is_dictionary_map();
5536 // Tells whether the instance needs security checks when accessing its
5538 inline void set_is_access_check_needed(bool access_check_needed);
5539 inline bool is_access_check_needed();
5541 // Returns true if map has a non-empty stub code cache.
5542 inline bool has_code_cache();
5544 // [prototype]: implicit prototype object.
5545 DECL_ACCESSORS(prototype, Object)
5546 // TODO(jkummerow): make set_prototype private.
5547 static void SetPrototype(
5548 Handle<Map> map, Handle<Object> prototype,
5549 PrototypeOptimizationMode proto_mode = FAST_PROTOTYPE);
5551 // [constructor]: points back to the function responsible for this map.
5552 // The field overlaps with the back pointer. All maps in a transition tree
5553 // have the same constructor, so maps with back pointers can walk the
5554 // back pointer chain until they find the map holding their constructor.
5555 DECL_ACCESSORS(constructor_or_backpointer, Object)
5556 inline Object* GetConstructor() const;
5557 inline void SetConstructor(Object* constructor,
5558 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5559 // [back pointer]: points back to the parent map from which a transition
5560 // leads to this map. The field overlaps with the constructor (see above).
5561 inline Object* GetBackPointer();
5562 inline void SetBackPointer(Object* value,
5563 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5565 // [instance descriptors]: describes the object.
5566 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
5568 // [layout descriptor]: describes the object layout.
5569 DECL_ACCESSORS(layout_descriptor, LayoutDescriptor)
5570 // |layout descriptor| accessor which can be used from GC.
5571 inline LayoutDescriptor* layout_descriptor_gc_safe();
5572 inline bool HasFastPointerLayout() const;
5574 // |layout descriptor| accessor that is safe to call even when
5575 // FLAG_unbox_double_fields is disabled (in this case Map does not contain
5576 // |layout_descriptor| field at all).
5577 inline LayoutDescriptor* GetLayoutDescriptor();
5579 inline void UpdateDescriptors(DescriptorArray* descriptors,
5580 LayoutDescriptor* layout_descriptor);
5581 inline void InitializeDescriptors(DescriptorArray* descriptors,
5582 LayoutDescriptor* layout_descriptor);
5584 // [stub cache]: contains stubs compiled for this map.
5585 DECL_ACCESSORS(code_cache, Object)
5587 // [dependent code]: list of optimized codes that weakly embed this map.
5588 DECL_ACCESSORS(dependent_code, DependentCode)
5590 // [weak cell cache]: cache that stores a weak cell pointing to this map.
5591 DECL_ACCESSORS(weak_cell_cache, Object)
5593 inline PropertyDetails GetLastDescriptorDetails();
5596 int number_of_own_descriptors = NumberOfOwnDescriptors();
5597 DCHECK(number_of_own_descriptors > 0);
5598 return number_of_own_descriptors - 1;
5601 int NumberOfOwnDescriptors() {
5602 return NumberOfOwnDescriptorsBits::decode(bit_field3());
5605 void SetNumberOfOwnDescriptors(int number) {
5606 DCHECK(number <= instance_descriptors()->number_of_descriptors());
5607 set_bit_field3(NumberOfOwnDescriptorsBits::update(bit_field3(), number));
5610 inline Cell* RetrieveDescriptorsPointer();
5613 return EnumLengthBits::decode(bit_field3());
5616 void SetEnumLength(int length) {
5617 if (length != kInvalidEnumCacheSentinel) {
5618 DCHECK(length >= 0);
5619 DCHECK(length == 0 || instance_descriptors()->HasEnumCache());
5620 DCHECK(length <= NumberOfOwnDescriptors());
5622 set_bit_field3(EnumLengthBits::update(bit_field3(), length));
5625 inline bool owns_descriptors();
5626 inline void set_owns_descriptors(bool owns_descriptors);
5627 inline bool has_instance_call_handler();
5628 inline void set_has_instance_call_handler();
5629 inline void mark_unstable();
5630 inline bool is_stable();
5631 inline void set_migration_target(bool value);
5632 inline bool is_migration_target();
5633 inline void set_counter(int value);
5634 inline int counter();
5635 inline void deprecate();
5636 inline bool is_deprecated();
5637 inline bool CanBeDeprecated();
5638 // Returns a non-deprecated version of the input. If the input was not
5639 // deprecated, it is directly returned. Otherwise, the non-deprecated version
5640 // is found by re-transitioning from the root of the transition tree using the
5641 // descriptor array of the map. Returns MaybeHandle<Map>() if no updated map
5643 static MaybeHandle<Map> TryUpdate(Handle<Map> map) WARN_UNUSED_RESULT;
5645 // Returns a non-deprecated version of the input. This method may deprecate
5646 // existing maps along the way if encodings conflict. Not for use while
5647 // gathering type feedback. Use TryUpdate in those cases instead.
5648 static Handle<Map> Update(Handle<Map> map);
5650 static Handle<Map> CopyDropDescriptors(Handle<Map> map);
5651 static Handle<Map> CopyInsertDescriptor(Handle<Map> map,
5652 Descriptor* descriptor,
5653 TransitionFlag flag);
5655 MUST_USE_RESULT static MaybeHandle<Map> CopyWithField(
5658 Handle<HeapType> type,
5659 PropertyAttributes attributes,
5660 Representation representation,
5661 TransitionFlag flag);
5663 MUST_USE_RESULT static MaybeHandle<Map> CopyWithConstant(
5666 Handle<Object> constant,
5667 PropertyAttributes attributes,
5668 TransitionFlag flag);
5670 // Returns a new map with all transitions dropped from the given map and
5671 // the ElementsKind set.
5672 static Handle<Map> TransitionElementsTo(Handle<Map> map,
5673 ElementsKind to_kind);
5675 static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
5677 static Handle<Map> CopyAsElementsKind(Handle<Map> map,
5679 TransitionFlag flag);
5681 static Handle<Map> CopyForObserved(Handle<Map> map);
5683 static Handle<Map> CopyForPreventExtensions(Handle<Map> map,
5684 PropertyAttributes attrs_to_add,
5685 Handle<Symbol> transition_marker,
5686 const char* reason);
5688 static Handle<Map> FixProxy(Handle<Map> map, InstanceType type, int size);
5691 // Maximal number of fast properties. Used to restrict the number of map
5692 // transitions to avoid an explosion in the number of maps for objects used as
5694 inline bool TooManyFastProperties(StoreFromKeyed store_mode);
5695 static Handle<Map> TransitionToDataProperty(Handle<Map> map,
5697 Handle<Object> value,
5698 PropertyAttributes attributes,
5699 StoreFromKeyed store_mode);
5700 static Handle<Map> TransitionToAccessorProperty(
5701 Handle<Map> map, Handle<Name> name, AccessorComponent component,
5702 Handle<Object> accessor, PropertyAttributes attributes);
5703 static Handle<Map> ReconfigureExistingProperty(Handle<Map> map,
5706 PropertyAttributes attributes);
5708 inline void AppendDescriptor(Descriptor* desc);
5710 // Returns a copy of the map, prepared for inserting into the transition
5711 // tree (if the |map| owns descriptors then the new one will share
5712 // descriptors with |map|).
5713 static Handle<Map> CopyForTransition(Handle<Map> map, const char* reason);
5715 // Returns a copy of the map, with all transitions dropped from the
5716 // instance descriptors.
5717 static Handle<Map> Copy(Handle<Map> map, const char* reason);
5718 static Handle<Map> Create(Isolate* isolate, int inobject_properties);
5720 // Returns the next free property index (only valid for FAST MODE).
5721 int NextFreePropertyIndex();
5723 // Returns the number of properties described in instance_descriptors
5724 // filtering out properties with the specified attributes.
5725 int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
5726 PropertyAttributes filter = NONE);
5730 // Code cache operations.
5732 // Clears the code cache.
5733 inline void ClearCodeCache(Heap* heap);
5735 // Update code cache.
5736 static void UpdateCodeCache(Handle<Map> map,
5740 // Extend the descriptor array of the map with the list of descriptors.
5741 // In case of duplicates, the latest descriptor is used.
5742 static void AppendCallbackDescriptors(Handle<Map> map,
5743 Handle<Object> descriptors);
5745 static inline int SlackForArraySize(int old_size, int size_limit);
5747 static void EnsureDescriptorSlack(Handle<Map> map, int slack);
5749 // Returns the found code or undefined if absent.
5750 Object* FindInCodeCache(Name* name, Code::Flags flags);
5752 // Returns the non-negative index of the code object if it is in the
5753 // cache and -1 otherwise.
5754 int IndexInCodeCache(Object* name, Code* code);
5756 // Removes a code object from the code cache at the given index.
5757 void RemoveFromCodeCache(Name* name, Code* code, int index);
5759 // Computes a hash value for this map, to be used in HashTables and such.
5762 // Returns the map that this map transitions to if its elements_kind
5763 // is changed to |elements_kind|, or NULL if no such map is cached yet.
5764 // |safe_to_add_transitions| is set to false if adding transitions is not
5766 Map* LookupElementsTransitionMap(ElementsKind elements_kind);
5768 // Returns the transitioned map for this map with the most generic
5769 // elements_kind that's found in |candidates|, or null handle if no match is
5771 static Handle<Map> FindTransitionedMap(Handle<Map> map,
5772 MapHandleList* candidates);
5774 bool CanTransition() {
5775 // Only JSObject and subtypes have map transitions and back pointers.
5776 STATIC_ASSERT(LAST_TYPE == LAST_JS_OBJECT_TYPE);
5777 return instance_type() >= FIRST_JS_OBJECT_TYPE;
5780 bool IsJSObjectMap() {
5781 return instance_type() >= FIRST_JS_OBJECT_TYPE;
5783 bool IsJSArrayMap() { return instance_type() == JS_ARRAY_TYPE; }
5784 bool IsStringMap() { return instance_type() < FIRST_NONSTRING_TYPE; }
5785 bool IsJSProxyMap() {
5786 InstanceType type = instance_type();
5787 return FIRST_JS_PROXY_TYPE <= type && type <= LAST_JS_PROXY_TYPE;
5789 bool IsJSGlobalProxyMap() {
5790 return instance_type() == JS_GLOBAL_PROXY_TYPE;
5792 bool IsJSGlobalObjectMap() {
5793 return instance_type() == JS_GLOBAL_OBJECT_TYPE;
5795 bool IsGlobalObjectMap() {
5796 const InstanceType type = instance_type();
5797 return type == JS_GLOBAL_OBJECT_TYPE || type == JS_BUILTINS_OBJECT_TYPE;
5800 inline bool CanOmitMapChecks();
5802 static void AddDependentCode(Handle<Map> map,
5803 DependentCode::DependencyGroup group,
5806 bool IsMapInArrayPrototypeChain();
5808 static Handle<WeakCell> WeakCellForMap(Handle<Map> map);
5810 // Dispatched behavior.
5811 DECLARE_PRINTER(Map)
5812 DECLARE_VERIFIER(Map)
5815 void DictionaryMapVerify();
5816 void VerifyOmittedMapChecks();
5819 inline int visitor_id();
5820 inline void set_visitor_id(int visitor_id);
5822 static Handle<Map> TransitionToPrototype(Handle<Map> map,
5823 Handle<Object> prototype,
5824 PrototypeOptimizationMode mode);
5826 static const int kMaxPreAllocatedPropertyFields = 255;
5828 // Layout description.
5829 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
5830 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
5831 static const int kBitField3Offset = kInstanceAttributesOffset + kIntSize;
5832 static const int kPrototypeOffset = kBitField3Offset + kPointerSize;
5833 static const int kConstructorOrBackPointerOffset =
5834 kPrototypeOffset + kPointerSize;
5835 // When there is only one transition, it is stored directly in this field;
5836 // otherwise a transition array is used.
5837 // For prototype maps, this slot is used to store this map's PrototypeInfo
5839 static const int kTransitionsOrPrototypeInfoOffset =
5840 kConstructorOrBackPointerOffset + kPointerSize;
5841 static const int kDescriptorsOffset =
5842 kTransitionsOrPrototypeInfoOffset + kPointerSize;
5843 #if V8_DOUBLE_FIELDS_UNBOXING
5844 static const int kLayoutDecriptorOffset = kDescriptorsOffset + kPointerSize;
5845 static const int kCodeCacheOffset = kLayoutDecriptorOffset + kPointerSize;
5847 static const int kLayoutDecriptorOffset = 1; // Must not be ever accessed.
5848 static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
5850 static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
5851 static const int kWeakCellCacheOffset = kDependentCodeOffset + kPointerSize;
5852 static const int kSize = kWeakCellCacheOffset + kPointerSize;
5854 // Layout of pointer fields. Heap iteration code relies on them
5855 // being continuously allocated.
5856 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
5857 static const int kPointerFieldsEndOffset = kSize;
5859 // Byte offsets within kInstanceSizesOffset.
5860 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
5861 static const int kInObjectPropertiesByte = 1;
5862 static const int kInObjectPropertiesOffset =
5863 kInstanceSizesOffset + kInObjectPropertiesByte;
5864 // Note there is one byte available for use here.
5865 static const int kUnusedByte = 2;
5866 static const int kUnusedOffset = kInstanceSizesOffset + kUnusedByte;
5867 static const int kVisitorIdByte = 3;
5868 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
5870 // Byte offsets within kInstanceAttributesOffset attributes.
5871 #if V8_TARGET_LITTLE_ENDIAN
5872 // Order instance type and bit field together such that they can be loaded
5873 // together as a 16-bit word with instance type in the lower 8 bits regardless
5874 // of endianess. Also provide endian-independent offset to that 16-bit word.
5875 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
5876 static const int kBitFieldOffset = kInstanceAttributesOffset + 1;
5878 static const int kBitFieldOffset = kInstanceAttributesOffset + 0;
5879 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 1;
5881 static const int kInstanceTypeAndBitFieldOffset =
5882 kInstanceAttributesOffset + 0;
5883 static const int kBitField2Offset = kInstanceAttributesOffset + 2;
5884 static const int kUnusedPropertyFieldsByte = 3;
5885 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 3;
5887 STATIC_ASSERT(kInstanceTypeAndBitFieldOffset ==
5888 Internals::kMapInstanceTypeAndBitFieldOffset);
5890 // Bit positions for bit field.
5891 static const int kHasNonInstancePrototype = 0;
5892 static const int kIsHiddenPrototype = 1;
5893 static const int kHasNamedInterceptor = 2;
5894 static const int kHasIndexedInterceptor = 3;
5895 static const int kIsUndetectable = 4;
5896 static const int kIsObserved = 5;
5897 static const int kIsAccessCheckNeeded = 6;
5898 class FunctionWithPrototype: public BitField<bool, 7, 1> {};
5900 // Bit positions for bit field 2
5901 static const int kIsExtensible = 0;
5902 static const int kStringWrapperSafeForDefaultValueOf = 1;
5903 class IsPrototypeMapBits : public BitField<bool, 2, 1> {};
5904 class ElementsKindBits: public BitField<ElementsKind, 3, 5> {};
5906 // Derived values from bit field 2
5907 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
5908 (FAST_ELEMENTS + 1) << Map::ElementsKindBits::kShift) - 1;
5909 static const int8_t kMaximumBitField2FastSmiElementValue =
5910 static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
5911 Map::ElementsKindBits::kShift) - 1;
5912 static const int8_t kMaximumBitField2FastHoleyElementValue =
5913 static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
5914 Map::ElementsKindBits::kShift) - 1;
5915 static const int8_t kMaximumBitField2FastHoleySmiElementValue =
5916 static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
5917 Map::ElementsKindBits::kShift) - 1;
5919 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
5920 kPointerFieldsEndOffset,
5921 kSize> BodyDescriptor;
5923 // Compares this map to another to see if they describe equivalent objects.
5924 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
5925 // it had exactly zero inobject properties.
5926 // The "shared" flags of both this map and |other| are ignored.
5927 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
5929 // Returns true if given field is unboxed double.
5930 inline bool IsUnboxedDoubleField(FieldIndex index);
5933 static void TraceTransition(const char* what, Map* from, Map* to, Name* name);
5934 static void TraceAllTransitions(Map* map);
5937 static inline Handle<Map> CopyInstallDescriptorsForTesting(
5938 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5939 Handle<LayoutDescriptor> layout_descriptor);
5942 static void ConnectTransition(Handle<Map> parent, Handle<Map> child,
5943 Handle<Name> name, SimpleTransitionFlag flag);
5945 bool EquivalentToForTransition(Map* other);
5946 static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
5947 static Handle<Map> ShareDescriptor(Handle<Map> map,
5948 Handle<DescriptorArray> descriptors,
5949 Descriptor* descriptor);
5950 static Handle<Map> CopyInstallDescriptors(
5951 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5952 Handle<LayoutDescriptor> layout_descriptor);
5953 static Handle<Map> CopyAddDescriptor(Handle<Map> map,
5954 Descriptor* descriptor,
5955 TransitionFlag flag);
5956 static Handle<Map> CopyReplaceDescriptors(
5957 Handle<Map> map, Handle<DescriptorArray> descriptors,
5958 Handle<LayoutDescriptor> layout_descriptor, TransitionFlag flag,
5959 MaybeHandle<Name> maybe_name, const char* reason,
5960 SimpleTransitionFlag simple_flag);
5962 static Handle<Map> CopyReplaceDescriptor(Handle<Map> map,
5963 Handle<DescriptorArray> descriptors,
5964 Descriptor* descriptor,
5966 TransitionFlag flag);
5967 static MUST_USE_RESULT MaybeHandle<Map> TryReconfigureExistingProperty(
5968 Handle<Map> map, int descriptor, PropertyKind kind,
5969 PropertyAttributes attributes, const char** reason);
5971 static Handle<Map> CopyNormalized(Handle<Map> map,
5972 PropertyNormalizationMode mode);
5974 // Fires when the layout of an object with a leaf map changes.
5975 // This includes adding transitions to the leaf map or changing
5976 // the descriptor array.
5977 inline void NotifyLeafMapLayoutChange();
5979 void DeprecateTransitionTree();
5980 bool DeprecateTarget(PropertyKind kind, Name* key,
5981 PropertyAttributes attributes,
5982 DescriptorArray* new_descriptors,
5983 LayoutDescriptor* new_layout_descriptor);
5985 Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
5987 // Update field type of the given descriptor to new representation and new
5988 // type. The type must be prepared for storing in descriptor array:
5989 // it must be either a simple type or a map wrapped in a weak cell.
5990 void UpdateFieldType(int descriptor_number, Handle<Name> name,
5991 Representation new_representation,
5992 Handle<Object> new_wrapped_type);
5994 void PrintReconfiguration(FILE* file, int modify_index, PropertyKind kind,
5995 PropertyAttributes attributes);
5996 void PrintGeneralization(FILE* file,
6001 bool constant_to_field,
6002 Representation old_representation,
6003 Representation new_representation,
6004 HeapType* old_field_type,
6005 HeapType* new_field_type);
6007 static const int kFastPropertiesSoftLimit = 12;
6008 static const int kMaxFastProperties = 128;
6010 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
6014 // An abstract superclass, a marker class really, for simple structure classes.
6015 // It doesn't carry much functionality but allows struct classes to be
6016 // identified in the type system.
6017 class Struct: public HeapObject {
6019 inline void InitializeBody(int object_size);
6020 DECLARE_CAST(Struct)
6024 // A simple one-element struct, useful where smis need to be boxed.
6025 class Box : public Struct {
6027 // [value]: the boxed contents.
6028 DECL_ACCESSORS(value, Object)
6032 // Dispatched behavior.
6033 DECLARE_PRINTER(Box)
6034 DECLARE_VERIFIER(Box)
6036 static const int kValueOffset = HeapObject::kHeaderSize;
6037 static const int kSize = kValueOffset + kPointerSize;
6040 DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
6044 // Container for metadata stored on each prototype map.
6045 class PrototypeInfo : public Struct {
6047 // [prototype_users]: WeakFixedArray containing maps using this prototype,
6048 // or Smi(0) if uninitialized.
6049 DECL_ACCESSORS(prototype_users, Object)
6050 // [validity_cell]: Cell containing the validity bit for prototype chains
6051 // going through this object, or Smi(0) if uninitialized.
6052 DECL_ACCESSORS(validity_cell, Object)
6053 // [constructor_name]: User-friendly name of the original constructor.
6054 DECL_ACCESSORS(constructor_name, Object)
6056 DECLARE_CAST(PrototypeInfo)
6058 // Dispatched behavior.
6059 DECLARE_PRINTER(PrototypeInfo)
6060 DECLARE_VERIFIER(PrototypeInfo)
6062 static const int kPrototypeUsersOffset = HeapObject::kHeaderSize;
6063 static const int kValidityCellOffset = kPrototypeUsersOffset + kPointerSize;
6064 static const int kConstructorNameOffset = kValidityCellOffset + kPointerSize;
6065 static const int kSize = kConstructorNameOffset + kPointerSize;
6068 DISALLOW_IMPLICIT_CONSTRUCTORS(PrototypeInfo);
6072 // Script describes a script which has been added to the VM.
6073 class Script: public Struct {
6082 // Script compilation types.
6083 enum CompilationType {
6084 COMPILATION_TYPE_HOST = 0,
6085 COMPILATION_TYPE_EVAL = 1
6088 // Script compilation state.
6089 enum CompilationState {
6090 COMPILATION_STATE_INITIAL = 0,
6091 COMPILATION_STATE_COMPILED = 1
6094 // [source]: the script source.
6095 DECL_ACCESSORS(source, Object)
6097 // [name]: the script name.
6098 DECL_ACCESSORS(name, Object)
6100 // [id]: the script id.
6101 DECL_ACCESSORS(id, Smi)
6103 // [line_offset]: script line offset in resource from where it was extracted.
6104 DECL_ACCESSORS(line_offset, Smi)
6106 // [column_offset]: script column offset in resource from where it was
6108 DECL_ACCESSORS(column_offset, Smi)
6110 // [context_data]: context data for the context this script was compiled in.
6111 DECL_ACCESSORS(context_data, Object)
6113 // [wrapper]: the wrapper cache. This is either undefined or a WeakCell.
6114 DECL_ACCESSORS(wrapper, HeapObject)
6116 // [type]: the script type.
6117 DECL_ACCESSORS(type, Smi)
6119 // [line_ends]: FixedArray of line ends positions.
6120 DECL_ACCESSORS(line_ends, Object)
6122 // [eval_from_shared]: for eval scripts the shared funcion info for the
6123 // function from which eval was called.
6124 DECL_ACCESSORS(eval_from_shared, Object)
6126 // [eval_from_instructions_offset]: the instruction offset in the code for the
6127 // function from which eval was called where eval was called.
6128 DECL_ACCESSORS(eval_from_instructions_offset, Smi)
6130 // [shared_function_infos]: weak fixed array containing all shared
6131 // function infos created from this script.
6132 DECL_ACCESSORS(shared_function_infos, Object)
6134 // [flags]: Holds an exciting bitfield.
6135 DECL_ACCESSORS(flags, Smi)
6137 // [source_url]: sourceURL from magic comment
6138 DECL_ACCESSORS(source_url, Object)
6140 // [source_url]: sourceMappingURL magic comment
6141 DECL_ACCESSORS(source_mapping_url, Object)
6143 // [compilation_type]: how the the script was compiled. Encoded in the
6145 inline CompilationType compilation_type();
6146 inline void set_compilation_type(CompilationType type);
6148 // [compilation_state]: determines whether the script has already been
6149 // compiled. Encoded in the 'flags' field.
6150 inline CompilationState compilation_state();
6151 inline void set_compilation_state(CompilationState state);
6153 // [origin_options]: optional attributes set by the embedder via ScriptOrigin,
6154 // and used by the embedder to make decisions about the script. V8 just passes
6155 // this through. Encoded in the 'flags' field.
6156 inline v8::ScriptOriginOptions origin_options();
6157 inline void set_origin_options(ScriptOriginOptions origin_options);
6159 DECLARE_CAST(Script)
6161 // If script source is an external string, check that the underlying
6162 // resource is accessible. Otherwise, always return true.
6163 inline bool HasValidSource();
6165 // Convert code position into column number.
6166 static int GetColumnNumber(Handle<Script> script, int code_pos);
6168 // Convert code position into (zero-based) line number.
6169 // The non-handlified version does not allocate, but may be much slower.
6170 static int GetLineNumber(Handle<Script> script, int code_pos);
6171 int GetLineNumber(int code_pos);
6173 static Handle<Object> GetNameOrSourceURL(Handle<Script> script);
6175 // Init line_ends array with code positions of line ends inside script source.
6176 static void InitLineEnds(Handle<Script> script);
6178 // Get the JS object wrapping the given script; create it if none exists.
6179 static Handle<JSObject> GetWrapper(Handle<Script> script);
6181 // Look through the list of existing shared function infos to find one
6182 // that matches the function literal. Return empty handle if not found.
6183 MaybeHandle<SharedFunctionInfo> FindSharedFunctionInfo(FunctionLiteral* fun);
6185 // Dispatched behavior.
6186 DECLARE_PRINTER(Script)
6187 DECLARE_VERIFIER(Script)
6189 static const int kSourceOffset = HeapObject::kHeaderSize;
6190 static const int kNameOffset = kSourceOffset + kPointerSize;
6191 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
6192 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
6193 static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
6194 static const int kWrapperOffset = kContextOffset + kPointerSize;
6195 static const int kTypeOffset = kWrapperOffset + kPointerSize;
6196 static const int kLineEndsOffset = kTypeOffset + kPointerSize;
6197 static const int kIdOffset = kLineEndsOffset + kPointerSize;
6198 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
6199 static const int kEvalFrominstructionsOffsetOffset =
6200 kEvalFromSharedOffset + kPointerSize;
6201 static const int kSharedFunctionInfosOffset =
6202 kEvalFrominstructionsOffsetOffset + kPointerSize;
6203 static const int kFlagsOffset = kSharedFunctionInfosOffset + kPointerSize;
6204 static const int kSourceUrlOffset = kFlagsOffset + kPointerSize;
6205 static const int kSourceMappingUrlOffset = kSourceUrlOffset + kPointerSize;
6206 static const int kSize = kSourceMappingUrlOffset + kPointerSize;
6209 int GetLineNumberWithArray(int code_pos);
6211 // Bit positions in the flags field.
6212 static const int kCompilationTypeBit = 0;
6213 static const int kCompilationStateBit = 1;
6214 static const int kOriginOptionsShift = 2;
6215 static const int kOriginOptionsSize = 3;
6216 static const int kOriginOptionsMask = ((1 << kOriginOptionsSize) - 1)
6217 << kOriginOptionsShift;
6219 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6223 // List of builtin functions we want to identify to improve code
6226 // Each entry has a name of a global object property holding an object
6227 // optionally followed by ".prototype", a name of a builtin function
6228 // on the object (the one the id is set for), and a label.
6230 // Installation of ids for the selected builtin functions is handled
6231 // by the bootstrapper.
6232 #define FUNCTIONS_WITH_ID_LIST(V) \
6233 V(Array.prototype, indexOf, ArrayIndexOf) \
6234 V(Array.prototype, lastIndexOf, ArrayLastIndexOf) \
6235 V(Array.prototype, push, ArrayPush) \
6236 V(Array.prototype, pop, ArrayPop) \
6237 V(Array.prototype, shift, ArrayShift) \
6238 V(Function.prototype, apply, FunctionApply) \
6239 V(Function.prototype, call, FunctionCall) \
6240 V(String.prototype, charCodeAt, StringCharCodeAt) \
6241 V(String.prototype, charAt, StringCharAt) \
6242 V(String, fromCharCode, StringFromCharCode) \
6243 V(Math, random, MathRandom) \
6244 V(Math, floor, MathFloor) \
6245 V(Math, round, MathRound) \
6246 V(Math, ceil, MathCeil) \
6247 V(Math, abs, MathAbs) \
6248 V(Math, log, MathLog) \
6249 V(Math, exp, MathExp) \
6250 V(Math, sqrt, MathSqrt) \
6251 V(Math, pow, MathPow) \
6252 V(Math, max, MathMax) \
6253 V(Math, min, MathMin) \
6254 V(Math, cos, MathCos) \
6255 V(Math, sin, MathSin) \
6256 V(Math, tan, MathTan) \
6257 V(Math, acos, MathAcos) \
6258 V(Math, asin, MathAsin) \
6259 V(Math, atan, MathAtan) \
6260 V(Math, atan2, MathAtan2) \
6261 V(Math, imul, MathImul) \
6262 V(Math, clz32, MathClz32) \
6263 V(Math, fround, MathFround)
6265 #define ATOMIC_FUNCTIONS_WITH_ID_LIST(V) \
6266 V(Atomics, load, AtomicsLoad) \
6267 V(Atomics, store, AtomicsStore)
6269 enum BuiltinFunctionId {
6271 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
6273 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6274 ATOMIC_FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6275 #undef DECLARE_FUNCTION_ID
6276 // Fake id for a special case of Math.pow. Note, it continues the
6277 // list of math functions.
6282 // Result of searching in an optimized code map of a SharedFunctionInfo. Note
6283 // that both {code} and {literals} can be NULL to pass search result status.
6284 struct CodeAndLiterals {
6285 Code* code; // Cached optimized code.
6286 FixedArray* literals; // Cached literals array.
6290 // SharedFunctionInfo describes the JSFunction information that can be
6291 // shared by multiple instances of the function.
6292 class SharedFunctionInfo: public HeapObject {
6294 // [name]: Function name.
6295 DECL_ACCESSORS(name, Object)
6297 // [code]: Function code.
6298 DECL_ACCESSORS(code, Code)
6299 inline void ReplaceCode(Code* code);
6301 // [optimized_code_map]: Map from native context to optimized code
6302 // and a shared literals array or Smi(0) if none.
6303 DECL_ACCESSORS(optimized_code_map, Object)
6305 // Returns entry from optimized code map for specified context and OSR entry.
6306 // Note that {code == nullptr} indicates no matching entry has been found,
6307 // whereas {literals == nullptr} indicates the code is context-independent.
6308 CodeAndLiterals SearchOptimizedCodeMap(Context* native_context,
6309 BailoutId osr_ast_id);
6311 // Clear optimized code map.
6312 void ClearOptimizedCodeMap();
6314 // Removed a specific optimized code object from the optimized code map.
6315 void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
6317 // Trims the optimized code map after entries have been removed.
6318 void TrimOptimizedCodeMap(int shrink_by);
6320 // Add a new entry to the optimized code map for context-independent code.
6321 static void AddSharedCodeToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6324 // Add a new entry to the optimized code map for context-dependent code.
6325 static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6326 Handle<Context> native_context,
6328 Handle<FixedArray> literals,
6329 BailoutId osr_ast_id);
6331 // Set up the link between shared function info and the script. The shared
6332 // function info is added to the list on the script.
6333 static void SetScript(Handle<SharedFunctionInfo> shared,
6334 Handle<Object> script_object);
6336 // Layout description of the optimized code map.
6337 static const int kNextMapIndex = 0;
6338 static const int kSharedCodeIndex = 1;
6339 static const int kEntriesStart = 2;
6340 static const int kContextOffset = 0;
6341 static const int kCachedCodeOffset = 1;
6342 static const int kLiteralsOffset = 2;
6343 static const int kOsrAstIdOffset = 3;
6344 static const int kEntryLength = 4;
6345 static const int kInitialLength = kEntriesStart + kEntryLength;
6347 // [scope_info]: Scope info.
6348 DECL_ACCESSORS(scope_info, ScopeInfo)
6350 // [construct stub]: Code stub for constructing instances of this function.
6351 DECL_ACCESSORS(construct_stub, Code)
6353 // Returns if this function has been compiled to native code yet.
6354 inline bool is_compiled();
6356 // [length]: The function length - usually the number of declared parameters.
6357 // Use up to 2^30 parameters.
6358 inline int length() const;
6359 inline void set_length(int value);
6361 // [internal formal parameter count]: The declared number of parameters.
6362 // For subclass constructors, also includes new.target.
6363 // The size of function's frame is internal_formal_parameter_count + 1.
6364 inline int internal_formal_parameter_count() const;
6365 inline void set_internal_formal_parameter_count(int value);
6367 // Set the formal parameter count so the function code will be
6368 // called without using argument adaptor frames.
6369 inline void DontAdaptArguments();
6371 // [expected_nof_properties]: Expected number of properties for the function.
6372 inline int expected_nof_properties() const;
6373 inline void set_expected_nof_properties(int value);
6375 // [feedback_vector] - accumulates ast node feedback from full-codegen and
6376 // (increasingly) from crankshafted code where sufficient feedback isn't
6378 DECL_ACCESSORS(feedback_vector, TypeFeedbackVector)
6380 // Unconditionally clear the type feedback vector (including vector ICs).
6381 void ClearTypeFeedbackInfo();
6383 // Clear the type feedback vector with a more subtle policy at GC time.
6384 void ClearTypeFeedbackInfoAtGCTime();
6387 // [unique_id] - For --trace-maps purposes, an identifier that's persistent
6388 // even if the GC moves this SharedFunctionInfo.
6389 inline int unique_id() const;
6390 inline void set_unique_id(int value);
6393 // [instance class name]: class name for instances.
6394 DECL_ACCESSORS(instance_class_name, Object)
6396 // [function data]: This field holds some additional data for function.
6397 // Currently it has one of:
6398 // - a FunctionTemplateInfo to make benefit the API [IsApiFunction()].
6399 // - a Smi identifying a builtin function [HasBuiltinFunctionId()].
6400 // - a BytecodeArray for the interpreter [HasBytecodeArray()].
6401 // In the long run we don't want all functions to have this field but
6402 // we can fix that when we have a better model for storing hidden data
6404 DECL_ACCESSORS(function_data, Object)
6406 inline bool IsApiFunction();
6407 inline FunctionTemplateInfo* get_api_func_data();
6408 inline bool HasBuiltinFunctionId();
6409 inline BuiltinFunctionId builtin_function_id();
6410 inline bool HasBytecodeArray();
6411 inline BytecodeArray* bytecode_array();
6413 // [script info]: Script from which the function originates.
6414 DECL_ACCESSORS(script, Object)
6416 // [num_literals]: Number of literals used by this function.
6417 inline int num_literals() const;
6418 inline void set_num_literals(int value);
6420 // [start_position_and_type]: Field used to store both the source code
6421 // position, whether or not the function is a function expression,
6422 // and whether or not the function is a toplevel function. The two
6423 // least significants bit indicates whether the function is an
6424 // expression and the rest contains the source code position.
6425 inline int start_position_and_type() const;
6426 inline void set_start_position_and_type(int value);
6428 // The function is subject to debugging if a debug info is attached.
6429 inline bool HasDebugInfo();
6430 inline DebugInfo* GetDebugInfo();
6432 // A function has debug code if the compiled code has debug break slots.
6433 inline bool HasDebugCode();
6435 // [debug info]: Debug information.
6436 DECL_ACCESSORS(debug_info, Object)
6438 // [inferred name]: Name inferred from variable or property
6439 // assignment of this function. Used to facilitate debugging and
6440 // profiling of JavaScript code written in OO style, where almost
6441 // all functions are anonymous but are assigned to object
6443 DECL_ACCESSORS(inferred_name, String)
6445 // The function's name if it is non-empty, otherwise the inferred name.
6446 String* DebugName();
6448 // Position of the 'function' token in the script source.
6449 inline int function_token_position() const;
6450 inline void set_function_token_position(int function_token_position);
6452 // Position of this function in the script source.
6453 inline int start_position() const;
6454 inline void set_start_position(int start_position);
6456 // End position of this function in the script source.
6457 inline int end_position() const;
6458 inline void set_end_position(int end_position);
6460 // Is this function a function expression in the source code.
6461 DECL_BOOLEAN_ACCESSORS(is_expression)
6463 // Is this function a top-level function (scripts, evals).
6464 DECL_BOOLEAN_ACCESSORS(is_toplevel)
6466 // Bit field containing various information collected by the compiler to
6467 // drive optimization.
6468 inline int compiler_hints() const;
6469 inline void set_compiler_hints(int value);
6471 inline int ast_node_count() const;
6472 inline void set_ast_node_count(int count);
6474 inline int profiler_ticks() const;
6475 inline void set_profiler_ticks(int ticks);
6477 // Inline cache age is used to infer whether the function survived a context
6478 // disposal or not. In the former case we reset the opt_count.
6479 inline int ic_age();
6480 inline void set_ic_age(int age);
6482 // Indicates if this function can be lazy compiled.
6483 // This is used to determine if we can safely flush code from a function
6484 // when doing GC if we expect that the function will no longer be used.
6485 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
6487 // Indicates if this function can be lazy compiled without a context.
6488 // This is used to determine if we can force compilation without reaching
6489 // the function through program execution but through other means (e.g. heap
6490 // iteration by the debugger).
6491 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
6493 // Indicates whether optimizations have been disabled for this
6494 // shared function info. If a function is repeatedly optimized or if
6495 // we cannot optimize the function we disable optimization to avoid
6496 // spending time attempting to optimize it again.
6497 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
6499 // Indicates the language mode.
6500 inline LanguageMode language_mode();
6501 inline void set_language_mode(LanguageMode language_mode);
6503 // False if the function definitely does not allocate an arguments object.
6504 DECL_BOOLEAN_ACCESSORS(uses_arguments)
6506 // Indicates that this function uses a super property (or an eval that may
6507 // use a super property).
6508 // This is needed to set up the [[HomeObject]] on the function instance.
6509 DECL_BOOLEAN_ACCESSORS(needs_home_object)
6511 // True if the function has any duplicated parameter names.
6512 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
6514 // Indicates whether the function is a native function.
6515 // These needs special treatment in .call and .apply since
6516 // null passed as the receiver should not be translated to the
6518 DECL_BOOLEAN_ACCESSORS(native)
6520 // Indicate that this function should always be inlined in optimized code.
6521 DECL_BOOLEAN_ACCESSORS(force_inline)
6523 // Indicates that the function was created by the Function function.
6524 // Though it's anonymous, toString should treat it as if it had the name
6525 // "anonymous". We don't set the name itself so that the system does not
6526 // see a binding for it.
6527 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
6529 // Indicates whether the function is a bound function created using
6530 // the bind function.
6531 DECL_BOOLEAN_ACCESSORS(bound)
6533 // Indicates that the function is anonymous (the name field can be set
6534 // through the API, which does not change this flag).
6535 DECL_BOOLEAN_ACCESSORS(is_anonymous)
6537 // Is this a function or top-level/eval code.
6538 DECL_BOOLEAN_ACCESSORS(is_function)
6540 // Indicates that code for this function cannot be compiled with Crankshaft.
6541 DECL_BOOLEAN_ACCESSORS(dont_crankshaft)
6543 // Indicates that code for this function cannot be flushed.
6544 DECL_BOOLEAN_ACCESSORS(dont_flush)
6546 // Indicates that this function is a generator.
6547 DECL_BOOLEAN_ACCESSORS(is_generator)
6549 // Indicates that this function is an arrow function.
6550 DECL_BOOLEAN_ACCESSORS(is_arrow)
6552 // Indicates that this function is a concise method.
6553 DECL_BOOLEAN_ACCESSORS(is_concise_method)
6555 // Indicates that this function is an accessor (getter or setter).
6556 DECL_BOOLEAN_ACCESSORS(is_accessor_function)
6558 // Indicates that this function is a default constructor.
6559 DECL_BOOLEAN_ACCESSORS(is_default_constructor)
6561 // Indicates that this function is an asm function.
6562 DECL_BOOLEAN_ACCESSORS(asm_function)
6564 // Indicates that the the shared function info is deserialized from cache.
6565 DECL_BOOLEAN_ACCESSORS(deserialized)
6567 // Indicates that the the shared function info has never been compiled before.
6568 DECL_BOOLEAN_ACCESSORS(never_compiled)
6570 inline FunctionKind kind();
6571 inline void set_kind(FunctionKind kind);
6573 // Indicates whether or not the code in the shared function support
6575 inline bool has_deoptimization_support();
6577 // Enable deoptimization support through recompiled code.
6578 void EnableDeoptimizationSupport(Code* recompiled);
6580 // Disable (further) attempted optimization of all functions sharing this
6581 // shared function info.
6582 void DisableOptimization(BailoutReason reason);
6584 inline BailoutReason disable_optimization_reason();
6586 // Lookup the bailout ID and DCHECK that it exists in the non-optimized
6587 // code, returns whether it asserted (i.e., always true if assertions are
6589 bool VerifyBailoutId(BailoutId id);
6591 // [source code]: Source code for the function.
6592 bool HasSourceCode() const;
6593 Handle<Object> GetSourceCode();
6595 // Number of times the function was optimized.
6596 inline int opt_count();
6597 inline void set_opt_count(int opt_count);
6599 // Number of times the function was deoptimized.
6600 inline void set_deopt_count(int value);
6601 inline int deopt_count();
6602 inline void increment_deopt_count();
6604 // Number of time we tried to re-enable optimization after it
6605 // was disabled due to high number of deoptimizations.
6606 inline void set_opt_reenable_tries(int value);
6607 inline int opt_reenable_tries();
6609 inline void TryReenableOptimization();
6611 // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
6612 inline void set_counters(int value);
6613 inline int counters() const;
6615 // Stores opt_count and bailout_reason as bit-fields.
6616 inline void set_opt_count_and_bailout_reason(int value);
6617 inline int opt_count_and_bailout_reason() const;
6619 void set_disable_optimization_reason(BailoutReason reason) {
6620 set_opt_count_and_bailout_reason(
6621 DisabledOptimizationReasonBits::update(opt_count_and_bailout_reason(),
6625 // Tells whether this function should be subject to debugging.
6626 inline bool IsSubjectToDebugging();
6628 // Check whether or not this function is inlineable.
6629 bool IsInlineable();
6631 // Source size of this function.
6634 // Calculate the instance size.
6635 int CalculateInstanceSize();
6637 // Calculate the number of in-object properties.
6638 int CalculateInObjectProperties();
6640 inline bool is_simple_parameter_list();
6642 // Initialize a SharedFunctionInfo from a parsed function literal.
6643 static void InitFromFunctionLiteral(Handle<SharedFunctionInfo> shared_info,
6644 FunctionLiteral* lit);
6646 // Dispatched behavior.
6647 DECLARE_PRINTER(SharedFunctionInfo)
6648 DECLARE_VERIFIER(SharedFunctionInfo)
6650 void ResetForNewContext(int new_ic_age);
6652 DECLARE_CAST(SharedFunctionInfo)
6655 static const int kDontAdaptArgumentsSentinel = -1;
6657 // Layout description.
6659 static const int kNameOffset = HeapObject::kHeaderSize;
6660 static const int kCodeOffset = kNameOffset + kPointerSize;
6661 static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
6662 static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
6663 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
6664 static const int kInstanceClassNameOffset =
6665 kConstructStubOffset + kPointerSize;
6666 static const int kFunctionDataOffset =
6667 kInstanceClassNameOffset + kPointerSize;
6668 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
6669 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
6670 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
6671 static const int kFeedbackVectorOffset =
6672 kInferredNameOffset + kPointerSize;
6674 static const int kUniqueIdOffset = kFeedbackVectorOffset + kPointerSize;
6675 static const int kLastPointerFieldOffset = kUniqueIdOffset;
6677 // Just to not break the postmortrem support with conditional offsets
6678 static const int kUniqueIdOffset = kFeedbackVectorOffset;
6679 static const int kLastPointerFieldOffset = kFeedbackVectorOffset;
6682 #if V8_HOST_ARCH_32_BIT
6684 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6685 static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
6686 static const int kExpectedNofPropertiesOffset =
6687 kFormalParameterCountOffset + kPointerSize;
6688 static const int kNumLiteralsOffset =
6689 kExpectedNofPropertiesOffset + kPointerSize;
6690 static const int kStartPositionAndTypeOffset =
6691 kNumLiteralsOffset + kPointerSize;
6692 static const int kEndPositionOffset =
6693 kStartPositionAndTypeOffset + kPointerSize;
6694 static const int kFunctionTokenPositionOffset =
6695 kEndPositionOffset + kPointerSize;
6696 static const int kCompilerHintsOffset =
6697 kFunctionTokenPositionOffset + kPointerSize;
6698 static const int kOptCountAndBailoutReasonOffset =
6699 kCompilerHintsOffset + kPointerSize;
6700 static const int kCountersOffset =
6701 kOptCountAndBailoutReasonOffset + kPointerSize;
6702 static const int kAstNodeCountOffset =
6703 kCountersOffset + kPointerSize;
6704 static const int kProfilerTicksOffset =
6705 kAstNodeCountOffset + kPointerSize;
6708 static const int kSize = kProfilerTicksOffset + kPointerSize;
6710 // The only reason to use smi fields instead of int fields
6711 // is to allow iteration without maps decoding during
6712 // garbage collections.
6713 // To avoid wasting space on 64-bit architectures we use
6714 // the following trick: we group integer fields into pairs
6715 // The least significant integer in each pair is shifted left by 1.
6716 // By doing this we guarantee that LSB of each kPointerSize aligned
6717 // word is not set and thus this word cannot be treated as pointer
6718 // to HeapObject during old space traversal.
6719 #if V8_TARGET_LITTLE_ENDIAN
6720 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6721 static const int kFormalParameterCountOffset =
6722 kLengthOffset + kIntSize;
6724 static const int kExpectedNofPropertiesOffset =
6725 kFormalParameterCountOffset + kIntSize;
6726 static const int kNumLiteralsOffset =
6727 kExpectedNofPropertiesOffset + kIntSize;
6729 static const int kEndPositionOffset =
6730 kNumLiteralsOffset + kIntSize;
6731 static const int kStartPositionAndTypeOffset =
6732 kEndPositionOffset + kIntSize;
6734 static const int kFunctionTokenPositionOffset =
6735 kStartPositionAndTypeOffset + kIntSize;
6736 static const int kCompilerHintsOffset =
6737 kFunctionTokenPositionOffset + kIntSize;
6739 static const int kOptCountAndBailoutReasonOffset =
6740 kCompilerHintsOffset + kIntSize;
6741 static const int kCountersOffset =
6742 kOptCountAndBailoutReasonOffset + kIntSize;
6744 static const int kAstNodeCountOffset =
6745 kCountersOffset + kIntSize;
6746 static const int kProfilerTicksOffset =
6747 kAstNodeCountOffset + kIntSize;
6750 static const int kSize = kProfilerTicksOffset + kIntSize;
6752 #elif V8_TARGET_BIG_ENDIAN
6753 static const int kFormalParameterCountOffset =
6754 kLastPointerFieldOffset + kPointerSize;
6755 static const int kLengthOffset = kFormalParameterCountOffset + kIntSize;
6757 static const int kNumLiteralsOffset = kLengthOffset + kIntSize;
6758 static const int kExpectedNofPropertiesOffset = kNumLiteralsOffset + kIntSize;
6760 static const int kStartPositionAndTypeOffset =
6761 kExpectedNofPropertiesOffset + kIntSize;
6762 static const int kEndPositionOffset = kStartPositionAndTypeOffset + kIntSize;
6764 static const int kCompilerHintsOffset = kEndPositionOffset + kIntSize;
6765 static const int kFunctionTokenPositionOffset =
6766 kCompilerHintsOffset + kIntSize;
6768 static const int kCountersOffset = kFunctionTokenPositionOffset + kIntSize;
6769 static const int kOptCountAndBailoutReasonOffset = kCountersOffset + kIntSize;
6771 static const int kProfilerTicksOffset =
6772 kOptCountAndBailoutReasonOffset + kIntSize;
6773 static const int kAstNodeCountOffset = kProfilerTicksOffset + kIntSize;
6776 static const int kSize = kAstNodeCountOffset + kIntSize;
6779 #error Unknown byte ordering
6780 #endif // Big endian
6784 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
6786 typedef FixedBodyDescriptor<kNameOffset,
6787 kLastPointerFieldOffset + kPointerSize,
6788 kSize> BodyDescriptor;
6790 // Bit positions in start_position_and_type.
6791 // The source code start position is in the 30 most significant bits of
6792 // the start_position_and_type field.
6793 static const int kIsExpressionBit = 0;
6794 static const int kIsTopLevelBit = 1;
6795 static const int kStartPositionShift = 2;
6796 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
6798 // Bit positions in compiler_hints.
6799 enum CompilerHints {
6800 kAllowLazyCompilation,
6801 kAllowLazyCompilationWithoutContext,
6802 kOptimizationDisabled,
6803 kStrictModeFunction,
6804 kStrongModeFunction,
6807 kHasDuplicateParameters,
6812 kNameShouldPrintAsAnonymous,
6819 kIsAccessorFunction,
6820 kIsDefaultConstructor,
6821 kIsSubclassConstructor,
6827 kCompilerHintsCount // Pseudo entry
6829 // Add hints for other modes when they're added.
6830 STATIC_ASSERT(LANGUAGE_END == 3);
6832 class FunctionKindBits : public BitField<FunctionKind, kIsArrow, 8> {};
6834 class DeoptCountBits : public BitField<int, 0, 4> {};
6835 class OptReenableTriesBits : public BitField<int, 4, 18> {};
6836 class ICAgeBits : public BitField<int, 22, 8> {};
6838 class OptCountBits : public BitField<int, 0, 22> {};
6839 class DisabledOptimizationReasonBits : public BitField<int, 22, 8> {};
6842 #if V8_HOST_ARCH_32_BIT
6843 // On 32 bit platforms, compiler hints is a smi.
6844 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
6845 static const int kCompilerHintsSize = kPointerSize;
6847 // On 64 bit platforms, compiler hints is not a smi, see comment above.
6848 static const int kCompilerHintsSmiTagSize = 0;
6849 static const int kCompilerHintsSize = kIntSize;
6852 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
6853 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
6856 // Constants for optimizing codegen for strict mode function and
6858 // Allows to use byte-width instructions.
6859 static const int kStrictModeBitWithinByte =
6860 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6861 static const int kStrongModeBitWithinByte =
6862 (kStrongModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6864 static const int kNativeBitWithinByte =
6865 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
6867 #if defined(V8_TARGET_LITTLE_ENDIAN)
6868 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6869 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6870 static const int kStrongModeByteOffset =
6871 kCompilerHintsOffset +
6872 (kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6873 static const int kNativeByteOffset = kCompilerHintsOffset +
6874 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
6875 #elif defined(V8_TARGET_BIG_ENDIAN)
6876 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6877 (kCompilerHintsSize - 1) -
6878 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6879 static const int kStrongModeByteOffset =
6880 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6881 ((kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6882 static const int kNativeByteOffset = kCompilerHintsOffset +
6883 (kCompilerHintsSize - 1) -
6884 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
6886 #error Unknown byte ordering
6890 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
6894 // Printing support.
6895 struct SourceCodeOf {
6896 explicit SourceCodeOf(SharedFunctionInfo* v, int max = -1)
6897 : value(v), max_length(max) {}
6898 const SharedFunctionInfo* value;
6903 std::ostream& operator<<(std::ostream& os, const SourceCodeOf& v);
6906 class JSGeneratorObject: public JSObject {
6908 // [function]: The function corresponding to this generator object.
6909 DECL_ACCESSORS(function, JSFunction)
6911 // [context]: The context of the suspended computation.
6912 DECL_ACCESSORS(context, Context)
6914 // [receiver]: The receiver of the suspended computation.
6915 DECL_ACCESSORS(receiver, Object)
6917 // [continuation]: Offset into code of continuation.
6919 // A positive offset indicates a suspended generator. The special
6920 // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
6921 // cannot be resumed.
6922 inline int continuation() const;
6923 inline void set_continuation(int continuation);
6924 inline bool is_closed();
6925 inline bool is_executing();
6926 inline bool is_suspended();
6928 // [operand_stack]: Saved operand stack.
6929 DECL_ACCESSORS(operand_stack, FixedArray)
6931 DECLARE_CAST(JSGeneratorObject)
6933 // Dispatched behavior.
6934 DECLARE_PRINTER(JSGeneratorObject)
6935 DECLARE_VERIFIER(JSGeneratorObject)
6937 // Magic sentinel values for the continuation.
6938 static const int kGeneratorExecuting = -1;
6939 static const int kGeneratorClosed = 0;
6941 // Layout description.
6942 static const int kFunctionOffset = JSObject::kHeaderSize;
6943 static const int kContextOffset = kFunctionOffset + kPointerSize;
6944 static const int kReceiverOffset = kContextOffset + kPointerSize;
6945 static const int kContinuationOffset = kReceiverOffset + kPointerSize;
6946 static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
6947 static const int kSize = kOperandStackOffset + kPointerSize;
6949 // Resume mode, for use by runtime functions.
6950 enum ResumeMode { NEXT, THROW };
6952 // Yielding from a generator returns an object with the following inobject
6953 // properties. See Context::iterator_result_map() for the map.
6954 static const int kResultValuePropertyIndex = 0;
6955 static const int kResultDonePropertyIndex = 1;
6956 static const int kResultPropertyCount = 2;
6958 static const int kResultValuePropertyOffset = JSObject::kHeaderSize;
6959 static const int kResultDonePropertyOffset =
6960 kResultValuePropertyOffset + kPointerSize;
6961 static const int kResultSize = kResultDonePropertyOffset + kPointerSize;
6964 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
6968 // Representation for module instance objects.
6969 class JSModule: public JSObject {
6971 // [context]: the context holding the module's locals, or undefined if none.
6972 DECL_ACCESSORS(context, Object)
6974 // [scope_info]: Scope info.
6975 DECL_ACCESSORS(scope_info, ScopeInfo)
6977 DECLARE_CAST(JSModule)
6979 // Dispatched behavior.
6980 DECLARE_PRINTER(JSModule)
6981 DECLARE_VERIFIER(JSModule)
6983 // Layout description.
6984 static const int kContextOffset = JSObject::kHeaderSize;
6985 static const int kScopeInfoOffset = kContextOffset + kPointerSize;
6986 static const int kSize = kScopeInfoOffset + kPointerSize;
6989 DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
6993 // JSFunction describes JavaScript functions.
6994 class JSFunction: public JSObject {
6996 // [prototype_or_initial_map]:
6997 DECL_ACCESSORS(prototype_or_initial_map, Object)
6999 // [shared]: The information about the function that
7000 // can be shared by instances.
7001 DECL_ACCESSORS(shared, SharedFunctionInfo)
7003 // [context]: The context for this function.
7004 inline Context* context();
7005 inline void set_context(Object* context);
7006 inline JSObject* global_proxy();
7008 // [code]: The generated code object for this function. Executed
7009 // when the function is invoked, e.g. foo() or new foo(). See
7010 // [[Call]] and [[Construct]] description in ECMA-262, section
7012 inline Code* code();
7013 inline void set_code(Code* code);
7014 inline void set_code_no_write_barrier(Code* code);
7015 inline void ReplaceCode(Code* code);
7017 // Tells whether this function is builtin.
7018 inline bool IsBuiltin();
7020 // Tells whether this function inlines the given shared function info.
7021 bool Inlines(SharedFunctionInfo* candidate);
7023 // Tells whether this function should be subject to debugging.
7024 inline bool IsSubjectToDebugging();
7026 // Tells whether or not the function needs arguments adaption.
7027 inline bool NeedsArgumentsAdaption();
7029 // Tells whether or not this function has been optimized.
7030 inline bool IsOptimized();
7032 // Mark this function for lazy recompilation. The function will be
7033 // recompiled the next time it is executed.
7034 void MarkForOptimization();
7035 void AttemptConcurrentOptimization();
7037 // Tells whether or not the function is already marked for lazy
7039 inline bool IsMarkedForOptimization();
7040 inline bool IsMarkedForConcurrentOptimization();
7042 // Tells whether or not the function is on the concurrent recompilation queue.
7043 inline bool IsInOptimizationQueue();
7045 // Inobject slack tracking is the way to reclaim unused inobject space.
7047 // The instance size is initially determined by adding some slack to
7048 // expected_nof_properties (to allow for a few extra properties added
7049 // after the constructor). There is no guarantee that the extra space
7050 // will not be wasted.
7052 // Here is the algorithm to reclaim the unused inobject space:
7053 // - Detect the first constructor call for this JSFunction.
7054 // When it happens enter the "in progress" state: initialize construction
7055 // counter in the initial_map.
7056 // - While the tracking is in progress create objects filled with
7057 // one_pointer_filler_map instead of undefined_value. This way they can be
7058 // resized quickly and safely.
7059 // - Once enough objects have been created compute the 'slack'
7060 // (traverse the map transition tree starting from the
7061 // initial_map and find the lowest value of unused_property_fields).
7062 // - Traverse the transition tree again and decrease the instance size
7063 // of every map. Existing objects will resize automatically (they are
7064 // filled with one_pointer_filler_map). All further allocations will
7065 // use the adjusted instance size.
7066 // - SharedFunctionInfo's expected_nof_properties left unmodified since
7067 // allocations made using different closures could actually create different
7068 // kind of objects (see prototype inheritance pattern).
7070 // Important: inobject slack tracking is not attempted during the snapshot
7073 // True if the initial_map is set and the object constructions countdown
7074 // counter is not zero.
7075 static const int kGenerousAllocationCount =
7076 Map::kSlackTrackingCounterStart - Map::kSlackTrackingCounterEnd + 1;
7077 inline bool IsInobjectSlackTrackingInProgress();
7079 // Starts the tracking.
7080 // Initializes object constructions countdown counter in the initial map.
7081 void StartInobjectSlackTracking();
7083 // Completes the tracking.
7084 void CompleteInobjectSlackTracking();
7086 // [literals_or_bindings]: Fixed array holding either
7087 // the materialized literals or the bindings of a bound function.
7089 // If the function contains object, regexp or array literals, the
7090 // literals array prefix contains the object, regexp, and array
7091 // function to be used when creating these literals. This is
7092 // necessary so that we do not dynamically lookup the object, regexp
7093 // or array functions. Performing a dynamic lookup, we might end up
7094 // using the functions from a new context that we should not have
7097 // On bound functions, the array is a (copy-on-write) fixed-array containing
7098 // the function that was bound, bound this-value and any bound
7099 // arguments. Bound functions never contain literals.
7100 DECL_ACCESSORS(literals_or_bindings, FixedArray)
7102 inline FixedArray* literals();
7103 inline void set_literals(FixedArray* literals);
7105 inline FixedArray* function_bindings();
7106 inline void set_function_bindings(FixedArray* bindings);
7108 // The initial map for an object created by this constructor.
7109 inline Map* initial_map();
7110 static void SetInitialMap(Handle<JSFunction> function, Handle<Map> map,
7111 Handle<Object> prototype);
7112 inline bool has_initial_map();
7113 static void EnsureHasInitialMap(Handle<JSFunction> function);
7115 // Get and set the prototype property on a JSFunction. If the
7116 // function has an initial map the prototype is set on the initial
7117 // map. Otherwise, the prototype is put in the initial map field
7118 // until an initial map is needed.
7119 inline bool has_prototype();
7120 inline bool has_instance_prototype();
7121 inline Object* prototype();
7122 inline Object* instance_prototype();
7123 static void SetPrototype(Handle<JSFunction> function,
7124 Handle<Object> value);
7125 static void SetInstancePrototype(Handle<JSFunction> function,
7126 Handle<Object> value);
7128 // Creates a new closure for the fucntion with the same bindings,
7129 // bound values, and prototype. An equivalent of spec operations
7130 // ``CloneMethod`` and ``CloneBoundFunction``.
7131 static Handle<JSFunction> CloneClosure(Handle<JSFunction> function);
7133 // After prototype is removed, it will not be created when accessed, and
7134 // [[Construct]] from this function will not be allowed.
7135 bool RemovePrototype();
7136 inline bool should_have_prototype();
7138 // Accessor for this function's initial map's [[class]]
7139 // property. This is primarily used by ECMA native functions. This
7140 // method sets the class_name field of this function's initial map
7141 // to a given value. It creates an initial map if this function does
7142 // not have one. Note that this method does not copy the initial map
7143 // if it has one already, but simply replaces it with the new value.
7144 // Instances created afterwards will have a map whose [[class]] is
7145 // set to 'value', but there is no guarantees on instances created
7147 void SetInstanceClassName(String* name);
7149 // Returns if this function has been compiled to native code yet.
7150 inline bool is_compiled();
7152 // Returns `false` if formal parameters include rest parameters, optional
7153 // parameters, or destructuring parameters.
7154 // TODO(caitp): make this a flag set during parsing
7155 inline bool is_simple_parameter_list();
7157 // [next_function_link]: Links functions into various lists, e.g. the list
7158 // of optimized functions hanging off the native_context. The CodeFlusher
7159 // uses this link to chain together flushing candidates. Treated weakly
7160 // by the garbage collector.
7161 DECL_ACCESSORS(next_function_link, Object)
7163 // Prints the name of the function using PrintF.
7164 void PrintName(FILE* out = stdout);
7166 DECLARE_CAST(JSFunction)
7168 // Iterates the objects, including code objects indirectly referenced
7169 // through pointers to the first instruction in the code object.
7170 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
7172 // Dispatched behavior.
7173 DECLARE_PRINTER(JSFunction)
7174 DECLARE_VERIFIER(JSFunction)
7176 // Returns the number of allocated literals.
7177 inline int NumberOfLiterals();
7179 // Used for flags such as --hydrogen-filter.
7180 bool PassesFilter(const char* raw_filter);
7182 // The function's name if it is configured, otherwise shared function info
7184 static Handle<String> GetDebugName(Handle<JSFunction> function);
7186 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
7187 // kSize) is weak and has special handling during garbage collection.
7188 static const int kCodeEntryOffset = JSObject::kHeaderSize;
7189 static const int kPrototypeOrInitialMapOffset =
7190 kCodeEntryOffset + kPointerSize;
7191 static const int kSharedFunctionInfoOffset =
7192 kPrototypeOrInitialMapOffset + kPointerSize;
7193 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
7194 static const int kLiteralsOffset = kContextOffset + kPointerSize;
7195 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
7196 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
7197 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
7199 // Layout of the bound-function binding array.
7200 static const int kBoundFunctionIndex = 0;
7201 static const int kBoundThisIndex = 1;
7202 static const int kBoundArgumentsStartIndex = 2;
7205 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7209 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7210 // and the prototype is hidden. JSGlobalProxy always delegates
7211 // property accesses to its prototype if the prototype is not null.
7213 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7215 // Accessing a JSGlobalProxy requires security check.
7217 class JSGlobalProxy : public JSObject {
7219 // [native_context]: the owner native context of this global proxy object.
7220 // It is null value if this object is not used by any context.
7221 DECL_ACCESSORS(native_context, Object)
7223 // [hash]: The hash code property (undefined if not initialized yet).
7224 DECL_ACCESSORS(hash, Object)
7226 DECLARE_CAST(JSGlobalProxy)
7228 inline bool IsDetachedFrom(GlobalObject* global) const;
7230 // Dispatched behavior.
7231 DECLARE_PRINTER(JSGlobalProxy)
7232 DECLARE_VERIFIER(JSGlobalProxy)
7234 // Layout description.
7235 static const int kNativeContextOffset = JSObject::kHeaderSize;
7236 static const int kHashOffset = kNativeContextOffset + kPointerSize;
7237 static const int kSize = kHashOffset + kPointerSize;
7240 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7244 // Common super class for JavaScript global objects and the special
7245 // builtins global objects.
7246 class GlobalObject: public JSObject {
7248 // [builtins]: the object holding the runtime routines written in JS.
7249 DECL_ACCESSORS(builtins, JSBuiltinsObject)
7251 // [native context]: the natives corresponding to this global object.
7252 DECL_ACCESSORS(native_context, Context)
7254 // [global proxy]: the global proxy object of the context
7255 DECL_ACCESSORS(global_proxy, JSObject)
7257 DECLARE_CAST(GlobalObject)
7259 static void InvalidatePropertyCell(Handle<GlobalObject> object,
7261 // Ensure that the global object has a cell for the given property name.
7262 static Handle<PropertyCell> EnsurePropertyCell(Handle<GlobalObject> global,
7265 // Layout description.
7266 static const int kBuiltinsOffset = JSObject::kHeaderSize;
7267 static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7268 static const int kGlobalProxyOffset = kNativeContextOffset + kPointerSize;
7269 static const int kHeaderSize = kGlobalProxyOffset + kPointerSize;
7272 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7276 // JavaScript global object.
7277 class JSGlobalObject: public GlobalObject {
7279 DECLARE_CAST(JSGlobalObject)
7281 inline bool IsDetached();
7283 // Dispatched behavior.
7284 DECLARE_PRINTER(JSGlobalObject)
7285 DECLARE_VERIFIER(JSGlobalObject)
7287 // Layout description.
7288 static const int kSize = GlobalObject::kHeaderSize;
7291 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7295 // Builtins global object which holds the runtime routines written in
7297 class JSBuiltinsObject: public GlobalObject {
7299 // Accessors for the runtime routines written in JavaScript.
7300 inline Object* javascript_builtin(Builtins::JavaScript id);
7301 inline void set_javascript_builtin(Builtins::JavaScript id, Object* value);
7303 DECLARE_CAST(JSBuiltinsObject)
7305 // Dispatched behavior.
7306 DECLARE_PRINTER(JSBuiltinsObject)
7307 DECLARE_VERIFIER(JSBuiltinsObject)
7309 // Layout description. The size of the builtins object includes
7310 // room for two pointers per runtime routine written in javascript
7311 // (function and code object).
7312 static const int kJSBuiltinsCount = Builtins::id_count;
7313 static const int kJSBuiltinsOffset = GlobalObject::kHeaderSize;
7314 static const int kSize =
7315 GlobalObject::kHeaderSize + (kJSBuiltinsCount * kPointerSize);
7317 static int OffsetOfFunctionWithId(Builtins::JavaScript id) {
7318 return kJSBuiltinsOffset + id * kPointerSize;
7322 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7326 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
7327 class JSValue: public JSObject {
7329 // [value]: the object being wrapped.
7330 DECL_ACCESSORS(value, Object)
7332 DECLARE_CAST(JSValue)
7334 // Dispatched behavior.
7335 DECLARE_PRINTER(JSValue)
7336 DECLARE_VERIFIER(JSValue)
7338 // Layout description.
7339 static const int kValueOffset = JSObject::kHeaderSize;
7340 static const int kSize = kValueOffset + kPointerSize;
7343 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
7349 // Representation for JS date objects.
7350 class JSDate: public JSObject {
7352 // If one component is NaN, all of them are, indicating a NaN time value.
7353 // [value]: the time value.
7354 DECL_ACCESSORS(value, Object)
7355 // [year]: caches year. Either undefined, smi, or NaN.
7356 DECL_ACCESSORS(year, Object)
7357 // [month]: caches month. Either undefined, smi, or NaN.
7358 DECL_ACCESSORS(month, Object)
7359 // [day]: caches day. Either undefined, smi, or NaN.
7360 DECL_ACCESSORS(day, Object)
7361 // [weekday]: caches day of week. Either undefined, smi, or NaN.
7362 DECL_ACCESSORS(weekday, Object)
7363 // [hour]: caches hours. Either undefined, smi, or NaN.
7364 DECL_ACCESSORS(hour, Object)
7365 // [min]: caches minutes. Either undefined, smi, or NaN.
7366 DECL_ACCESSORS(min, Object)
7367 // [sec]: caches seconds. Either undefined, smi, or NaN.
7368 DECL_ACCESSORS(sec, Object)
7369 // [cache stamp]: sample of the date cache stamp at the
7370 // moment when chached fields were cached.
7371 DECL_ACCESSORS(cache_stamp, Object)
7373 DECLARE_CAST(JSDate)
7375 // Returns the date field with the specified index.
7376 // See FieldIndex for the list of date fields.
7377 static Object* GetField(Object* date, Smi* index);
7379 void SetValue(Object* value, bool is_value_nan);
7382 // Dispatched behavior.
7383 DECLARE_PRINTER(JSDate)
7384 DECLARE_VERIFIER(JSDate)
7386 // The order is important. It must be kept in sync with date macros
7397 kFirstUncachedField,
7398 kMillisecond = kFirstUncachedField,
7402 kYearUTC = kFirstUTCField,
7415 // Layout description.
7416 static const int kValueOffset = JSObject::kHeaderSize;
7417 static const int kYearOffset = kValueOffset + kPointerSize;
7418 static const int kMonthOffset = kYearOffset + kPointerSize;
7419 static const int kDayOffset = kMonthOffset + kPointerSize;
7420 static const int kWeekdayOffset = kDayOffset + kPointerSize;
7421 static const int kHourOffset = kWeekdayOffset + kPointerSize;
7422 static const int kMinOffset = kHourOffset + kPointerSize;
7423 static const int kSecOffset = kMinOffset + kPointerSize;
7424 static const int kCacheStampOffset = kSecOffset + kPointerSize;
7425 static const int kSize = kCacheStampOffset + kPointerSize;
7428 inline Object* DoGetField(FieldIndex index);
7430 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
7432 // Computes and caches the cacheable fields of the date.
7433 inline void SetCachedFields(int64_t local_time_ms, DateCache* date_cache);
7436 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
7440 // Representation of message objects used for error reporting through
7441 // the API. The messages are formatted in JavaScript so this object is
7442 // a real JavaScript object. The information used for formatting the
7443 // error messages are not directly accessible from JavaScript to
7444 // prevent leaking information to user code called during error
7446 class JSMessageObject: public JSObject {
7448 // [type]: the type of error message.
7449 inline int type() const;
7450 inline void set_type(int value);
7452 // [arguments]: the arguments for formatting the error message.
7453 DECL_ACCESSORS(argument, Object)
7455 // [script]: the script from which the error message originated.
7456 DECL_ACCESSORS(script, Object)
7458 // [stack_frames]: an array of stack frames for this error object.
7459 DECL_ACCESSORS(stack_frames, Object)
7461 // [start_position]: the start position in the script for the error message.
7462 inline int start_position() const;
7463 inline void set_start_position(int value);
7465 // [end_position]: the end position in the script for the error message.
7466 inline int end_position() const;
7467 inline void set_end_position(int value);
7469 DECLARE_CAST(JSMessageObject)
7471 // Dispatched behavior.
7472 DECLARE_PRINTER(JSMessageObject)
7473 DECLARE_VERIFIER(JSMessageObject)
7475 // Layout description.
7476 static const int kTypeOffset = JSObject::kHeaderSize;
7477 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
7478 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
7479 static const int kStackFramesOffset = kScriptOffset + kPointerSize;
7480 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
7481 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
7482 static const int kSize = kEndPositionOffset + kPointerSize;
7484 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
7485 kStackFramesOffset + kPointerSize,
7486 kSize> BodyDescriptor;
7490 // Regular expressions
7491 // The regular expression holds a single reference to a FixedArray in
7492 // the kDataOffset field.
7493 // The FixedArray contains the following data:
7494 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
7495 // - reference to the original source string
7496 // - reference to the original flag string
7497 // If it is an atom regexp
7498 // - a reference to a literal string to search for
7499 // If it is an irregexp regexp:
7500 // - a reference to code for Latin1 inputs (bytecode or compiled), or a smi
7501 // used for tracking the last usage (used for code flushing).
7502 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
7503 // used for tracking the last usage (used for code flushing)..
7504 // - max number of registers used by irregexp implementations.
7505 // - number of capture registers (output values) of the regexp.
7506 class JSRegExp: public JSObject {
7509 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
7510 // ATOM: A simple string to match against using an indexOf operation.
7511 // IRREGEXP: Compiled with Irregexp.
7512 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
7513 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
7520 UNICODE_ESCAPES = 16
7525 explicit Flags(uint32_t value) : value_(value) { }
7526 bool is_global() { return (value_ & GLOBAL) != 0; }
7527 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
7528 bool is_multiline() { return (value_ & MULTILINE) != 0; }
7529 bool is_sticky() { return (value_ & STICKY) != 0; }
7530 bool is_unicode() { return (value_ & UNICODE_ESCAPES) != 0; }
7531 uint32_t value() { return value_; }
7536 DECL_ACCESSORS(data, Object)
7538 inline Type TypeTag();
7539 inline int CaptureCount();
7540 inline Flags GetFlags();
7541 inline String* Pattern();
7542 inline Object* DataAt(int index);
7543 // Set implementation data after the object has been prepared.
7544 inline void SetDataAt(int index, Object* value);
7546 static int code_index(bool is_latin1) {
7548 return kIrregexpLatin1CodeIndex;
7550 return kIrregexpUC16CodeIndex;
7554 static int saved_code_index(bool is_latin1) {
7556 return kIrregexpLatin1CodeSavedIndex;
7558 return kIrregexpUC16CodeSavedIndex;
7562 DECLARE_CAST(JSRegExp)
7564 // Dispatched behavior.
7565 DECLARE_VERIFIER(JSRegExp)
7567 static const int kDataOffset = JSObject::kHeaderSize;
7568 static const int kSize = kDataOffset + kPointerSize;
7570 // Indices in the data array.
7571 static const int kTagIndex = 0;
7572 static const int kSourceIndex = kTagIndex + 1;
7573 static const int kFlagsIndex = kSourceIndex + 1;
7574 static const int kDataIndex = kFlagsIndex + 1;
7575 // The data fields are used in different ways depending on the
7576 // value of the tag.
7577 // Atom regexps (literal strings).
7578 static const int kAtomPatternIndex = kDataIndex;
7580 static const int kAtomDataSize = kAtomPatternIndex + 1;
7582 // Irregexp compiled code or bytecode for Latin1. If compilation
7583 // fails, this fields hold an exception object that should be
7584 // thrown if the regexp is used again.
7585 static const int kIrregexpLatin1CodeIndex = kDataIndex;
7586 // Irregexp compiled code or bytecode for UC16. If compilation
7587 // fails, this fields hold an exception object that should be
7588 // thrown if the regexp is used again.
7589 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
7591 // Saved instance of Irregexp compiled code or bytecode for Latin1 that
7592 // is a potential candidate for flushing.
7593 static const int kIrregexpLatin1CodeSavedIndex = kDataIndex + 2;
7594 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
7595 // a potential candidate for flushing.
7596 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
7598 // Maximal number of registers used by either Latin1 or UC16.
7599 // Only used to check that there is enough stack space
7600 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
7601 // Number of captures in the compiled regexp.
7602 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
7604 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
7606 // Offsets directly into the data fixed array.
7607 static const int kDataTagOffset =
7608 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
7609 static const int kDataOneByteCodeOffset =
7610 FixedArray::kHeaderSize + kIrregexpLatin1CodeIndex * kPointerSize;
7611 static const int kDataUC16CodeOffset =
7612 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
7613 static const int kIrregexpCaptureCountOffset =
7614 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
7616 // In-object fields.
7617 static const int kSourceFieldIndex = 0;
7618 static const int kGlobalFieldIndex = 1;
7619 static const int kIgnoreCaseFieldIndex = 2;
7620 static const int kMultilineFieldIndex = 3;
7621 static const int kLastIndexFieldIndex = 4;
7622 static const int kInObjectFieldCount = 5;
7624 // The uninitialized value for a regexp code object.
7625 static const int kUninitializedValue = -1;
7627 // The compilation error value for the regexp code object. The real error
7628 // object is in the saved code field.
7629 static const int kCompilationErrorValue = -2;
7631 // When we store the sweep generation at which we moved the code from the
7632 // code index to the saved code index we mask it of to be in the [0:255]
7634 static const int kCodeAgeMask = 0xff;
7638 class CompilationCacheShape : public BaseShape<HashTableKey*> {
7640 static inline bool IsMatch(HashTableKey* key, Object* value) {
7641 return key->IsMatch(value);
7644 static inline uint32_t Hash(HashTableKey* key) {
7648 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7649 return key->HashForObject(object);
7652 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7654 static const int kPrefixSize = 0;
7655 static const int kEntrySize = 2;
7659 // This cache is used in two different variants. For regexp caching, it simply
7660 // maps identifying info of the regexp to the cached regexp object. Scripts and
7661 // eval code only gets cached after a second probe for the code object. To do
7662 // so, on first "put" only a hash identifying the source is entered into the
7663 // cache, mapping it to a lifetime count of the hash. On each call to Age all
7664 // such lifetimes get reduced, and removed once they reach zero. If a second put
7665 // is called while such a hash is live in the cache, the hash gets replaced by
7666 // an actual cache entry. Age also removes stale live entries from the cache.
7667 // Such entries are identified by SharedFunctionInfos pointing to either the
7668 // recompilation stub, or to "old" code. This avoids memory leaks due to
7669 // premature caching of scripts and eval strings that are never needed later.
7670 class CompilationCacheTable: public HashTable<CompilationCacheTable,
7671 CompilationCacheShape,
7674 // Find cached value for a string key, otherwise return null.
7675 Handle<Object> Lookup(
7676 Handle<String> src, Handle<Context> context, LanguageMode language_mode);
7677 Handle<Object> LookupEval(
7678 Handle<String> src, Handle<SharedFunctionInfo> shared,
7679 LanguageMode language_mode, int scope_position);
7680 Handle<Object> LookupRegExp(Handle<String> source, JSRegExp::Flags flags);
7681 static Handle<CompilationCacheTable> Put(
7682 Handle<CompilationCacheTable> cache, Handle<String> src,
7683 Handle<Context> context, LanguageMode language_mode,
7684 Handle<Object> value);
7685 static Handle<CompilationCacheTable> PutEval(
7686 Handle<CompilationCacheTable> cache, Handle<String> src,
7687 Handle<SharedFunctionInfo> context, Handle<SharedFunctionInfo> value,
7688 int scope_position);
7689 static Handle<CompilationCacheTable> PutRegExp(
7690 Handle<CompilationCacheTable> cache, Handle<String> src,
7691 JSRegExp::Flags flags, Handle<FixedArray> value);
7692 void Remove(Object* value);
7694 static const int kHashGenerations = 10;
7696 DECLARE_CAST(CompilationCacheTable)
7699 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
7703 class CodeCache: public Struct {
7705 DECL_ACCESSORS(default_cache, FixedArray)
7706 DECL_ACCESSORS(normal_type_cache, Object)
7708 // Add the code object to the cache.
7710 Handle<CodeCache> cache, Handle<Name> name, Handle<Code> code);
7712 // Lookup code object in the cache. Returns code object if found and undefined
7714 Object* Lookup(Name* name, Code::Flags flags);
7716 // Get the internal index of a code object in the cache. Returns -1 if the
7717 // code object is not in that cache. This index can be used to later call
7718 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
7720 int GetIndex(Object* name, Code* code);
7722 // Remove an object from the cache with the provided internal index.
7723 void RemoveByIndex(Object* name, Code* code, int index);
7725 DECLARE_CAST(CodeCache)
7727 // Dispatched behavior.
7728 DECLARE_PRINTER(CodeCache)
7729 DECLARE_VERIFIER(CodeCache)
7731 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
7732 static const int kNormalTypeCacheOffset =
7733 kDefaultCacheOffset + kPointerSize;
7734 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
7737 static void UpdateDefaultCache(
7738 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7739 static void UpdateNormalTypeCache(
7740 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7741 Object* LookupDefaultCache(Name* name, Code::Flags flags);
7742 Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
7744 // Code cache layout of the default cache. Elements are alternating name and
7745 // code objects for non normal load/store/call IC's.
7746 static const int kCodeCacheEntrySize = 2;
7747 static const int kCodeCacheEntryNameOffset = 0;
7748 static const int kCodeCacheEntryCodeOffset = 1;
7750 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
7754 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
7756 static inline bool IsMatch(HashTableKey* key, Object* value) {
7757 return key->IsMatch(value);
7760 static inline uint32_t Hash(HashTableKey* key) {
7764 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7765 return key->HashForObject(object);
7768 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7770 static const int kPrefixSize = 0;
7771 static const int kEntrySize = 2;
7775 class CodeCacheHashTable: public HashTable<CodeCacheHashTable,
7776 CodeCacheHashTableShape,
7779 Object* Lookup(Name* name, Code::Flags flags);
7780 static Handle<CodeCacheHashTable> Put(
7781 Handle<CodeCacheHashTable> table,
7785 int GetIndex(Name* name, Code::Flags flags);
7786 void RemoveByIndex(int index);
7788 DECLARE_CAST(CodeCacheHashTable)
7790 // Initial size of the fixed array backing the hash table.
7791 static const int kInitialSize = 64;
7794 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
7798 class PolymorphicCodeCache: public Struct {
7800 DECL_ACCESSORS(cache, Object)
7802 static void Update(Handle<PolymorphicCodeCache> cache,
7803 MapHandleList* maps,
7808 // Returns an undefined value if the entry is not found.
7809 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
7811 DECLARE_CAST(PolymorphicCodeCache)
7813 // Dispatched behavior.
7814 DECLARE_PRINTER(PolymorphicCodeCache)
7815 DECLARE_VERIFIER(PolymorphicCodeCache)
7817 static const int kCacheOffset = HeapObject::kHeaderSize;
7818 static const int kSize = kCacheOffset + kPointerSize;
7821 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
7825 class PolymorphicCodeCacheHashTable
7826 : public HashTable<PolymorphicCodeCacheHashTable,
7827 CodeCacheHashTableShape,
7830 Object* Lookup(MapHandleList* maps, int code_kind);
7832 static Handle<PolymorphicCodeCacheHashTable> Put(
7833 Handle<PolymorphicCodeCacheHashTable> hash_table,
7834 MapHandleList* maps,
7838 DECLARE_CAST(PolymorphicCodeCacheHashTable)
7840 static const int kInitialSize = 64;
7842 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
7846 class TypeFeedbackInfo: public Struct {
7848 inline int ic_total_count();
7849 inline void set_ic_total_count(int count);
7851 inline int ic_with_type_info_count();
7852 inline void change_ic_with_type_info_count(int delta);
7854 inline int ic_generic_count();
7855 inline void change_ic_generic_count(int delta);
7857 inline void initialize_storage();
7859 inline void change_own_type_change_checksum();
7860 inline int own_type_change_checksum();
7862 inline void set_inlined_type_change_checksum(int checksum);
7863 inline bool matches_inlined_type_change_checksum(int checksum);
7865 DECLARE_CAST(TypeFeedbackInfo)
7867 // Dispatched behavior.
7868 DECLARE_PRINTER(TypeFeedbackInfo)
7869 DECLARE_VERIFIER(TypeFeedbackInfo)
7871 static const int kStorage1Offset = HeapObject::kHeaderSize;
7872 static const int kStorage2Offset = kStorage1Offset + kPointerSize;
7873 static const int kStorage3Offset = kStorage2Offset + kPointerSize;
7874 static const int kSize = kStorage3Offset + kPointerSize;
7877 static const int kTypeChangeChecksumBits = 7;
7879 class ICTotalCountField: public BitField<int, 0,
7880 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7881 class OwnTypeChangeChecksum: public BitField<int,
7882 kSmiValueSize - kTypeChangeChecksumBits,
7883 kTypeChangeChecksumBits> {}; // NOLINT
7884 class ICsWithTypeInfoCountField: public BitField<int, 0,
7885 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7886 class InlinedTypeChangeChecksum: public BitField<int,
7887 kSmiValueSize - kTypeChangeChecksumBits,
7888 kTypeChangeChecksumBits> {}; // NOLINT
7890 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
7894 enum AllocationSiteMode {
7895 DONT_TRACK_ALLOCATION_SITE,
7896 TRACK_ALLOCATION_SITE,
7897 LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
7901 class AllocationSite: public Struct {
7903 static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
7904 static const double kPretenureRatio;
7905 static const int kPretenureMinimumCreated = 100;
7907 // Values for pretenure decision field.
7908 enum PretenureDecision {
7914 kLastPretenureDecisionValue = kZombie
7917 const char* PretenureDecisionName(PretenureDecision decision);
7919 DECL_ACCESSORS(transition_info, Object)
7920 // nested_site threads a list of sites that represent nested literals
7921 // walked in a particular order. So [[1, 2], 1, 2] will have one
7922 // nested_site, but [[1, 2], 3, [4]] will have a list of two.
7923 DECL_ACCESSORS(nested_site, Object)
7924 DECL_ACCESSORS(pretenure_data, Smi)
7925 DECL_ACCESSORS(pretenure_create_count, Smi)
7926 DECL_ACCESSORS(dependent_code, DependentCode)
7927 DECL_ACCESSORS(weak_next, Object)
7929 inline void Initialize();
7931 // This method is expensive, it should only be called for reporting.
7932 bool IsNestedSite();
7934 // transition_info bitfields, for constructed array transition info.
7935 class ElementsKindBits: public BitField<ElementsKind, 0, 15> {};
7936 class UnusedBits: public BitField<int, 15, 14> {};
7937 class DoNotInlineBit: public BitField<bool, 29, 1> {};
7939 // Bitfields for pretenure_data
7940 class MementoFoundCountBits: public BitField<int, 0, 26> {};
7941 class PretenureDecisionBits: public BitField<PretenureDecision, 26, 3> {};
7942 class DeoptDependentCodeBit: public BitField<bool, 29, 1> {};
7943 STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
7945 // Increments the mementos found counter and returns true when the first
7946 // memento was found for a given allocation site.
7947 inline bool IncrementMementoFoundCount();
7949 inline void IncrementMementoCreateCount();
7951 PretenureFlag GetPretenureMode();
7953 void ResetPretenureDecision();
7955 PretenureDecision pretenure_decision() {
7956 int value = pretenure_data()->value();
7957 return PretenureDecisionBits::decode(value);
7960 void set_pretenure_decision(PretenureDecision decision) {
7961 int value = pretenure_data()->value();
7963 Smi::FromInt(PretenureDecisionBits::update(value, decision)),
7964 SKIP_WRITE_BARRIER);
7967 bool deopt_dependent_code() {
7968 int value = pretenure_data()->value();
7969 return DeoptDependentCodeBit::decode(value);
7972 void set_deopt_dependent_code(bool deopt) {
7973 int value = pretenure_data()->value();
7975 Smi::FromInt(DeoptDependentCodeBit::update(value, deopt)),
7976 SKIP_WRITE_BARRIER);
7979 int memento_found_count() {
7980 int value = pretenure_data()->value();
7981 return MementoFoundCountBits::decode(value);
7984 inline void set_memento_found_count(int count);
7986 int memento_create_count() {
7987 return pretenure_create_count()->value();
7990 void set_memento_create_count(int count) {
7991 set_pretenure_create_count(Smi::FromInt(count), SKIP_WRITE_BARRIER);
7994 // The pretenuring decision is made during gc, and the zombie state allows
7995 // us to recognize when an allocation site is just being kept alive because
7996 // a later traversal of new space may discover AllocationMementos that point
7997 // to this AllocationSite.
7999 return pretenure_decision() == kZombie;
8002 bool IsMaybeTenure() {
8003 return pretenure_decision() == kMaybeTenure;
8006 inline void MarkZombie();
8008 inline bool MakePretenureDecision(PretenureDecision current_decision,
8010 bool maximum_size_scavenge);
8012 inline bool DigestPretenuringFeedback(bool maximum_size_scavenge);
8014 ElementsKind GetElementsKind() {
8015 DCHECK(!SitePointsToLiteral());
8016 int value = Smi::cast(transition_info())->value();
8017 return ElementsKindBits::decode(value);
8020 void SetElementsKind(ElementsKind kind) {
8021 int value = Smi::cast(transition_info())->value();
8022 set_transition_info(Smi::FromInt(ElementsKindBits::update(value, kind)),
8023 SKIP_WRITE_BARRIER);
8026 bool CanInlineCall() {
8027 int value = Smi::cast(transition_info())->value();
8028 return DoNotInlineBit::decode(value) == 0;
8031 void SetDoNotInlineCall() {
8032 int value = Smi::cast(transition_info())->value();
8033 set_transition_info(Smi::FromInt(DoNotInlineBit::update(value, true)),
8034 SKIP_WRITE_BARRIER);
8037 bool SitePointsToLiteral() {
8038 // If transition_info is a smi, then it represents an ElementsKind
8039 // for a constructed array. Otherwise, it must be a boilerplate
8040 // for an object or array literal.
8041 return transition_info()->IsJSArray() || transition_info()->IsJSObject();
8044 static void DigestTransitionFeedback(Handle<AllocationSite> site,
8045 ElementsKind to_kind);
8047 DECLARE_PRINTER(AllocationSite)
8048 DECLARE_VERIFIER(AllocationSite)
8050 DECLARE_CAST(AllocationSite)
8051 static inline AllocationSiteMode GetMode(
8052 ElementsKind boilerplate_elements_kind);
8053 static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
8054 static inline bool CanTrack(InstanceType type);
8056 static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
8057 static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
8058 static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
8059 static const int kPretenureCreateCountOffset =
8060 kPretenureDataOffset + kPointerSize;
8061 static const int kDependentCodeOffset =
8062 kPretenureCreateCountOffset + kPointerSize;
8063 static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
8064 static const int kSize = kWeakNextOffset + kPointerSize;
8066 // During mark compact we need to take special care for the dependent code
8068 static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
8069 static const int kPointerFieldsEndOffset = kWeakNextOffset;
8071 // For other visitors, use the fixed body descriptor below.
8072 typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
8073 kDependentCodeOffset + kPointerSize,
8074 kSize> BodyDescriptor;
8077 bool PretenuringDecisionMade() {
8078 return pretenure_decision() != kUndecided;
8081 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
8085 class AllocationMemento: public Struct {
8087 static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
8088 static const int kSize = kAllocationSiteOffset + kPointerSize;
8090 DECL_ACCESSORS(allocation_site, Object)
8093 return allocation_site()->IsAllocationSite() &&
8094 !AllocationSite::cast(allocation_site())->IsZombie();
8096 AllocationSite* GetAllocationSite() {
8098 return AllocationSite::cast(allocation_site());
8101 DECLARE_PRINTER(AllocationMemento)
8102 DECLARE_VERIFIER(AllocationMemento)
8104 DECLARE_CAST(AllocationMemento)
8107 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
8111 // Representation of a slow alias as part of a sloppy arguments objects.
8112 // For fast aliases (if HasSloppyArgumentsElements()):
8113 // - the parameter map contains an index into the context
8114 // - all attributes of the element have default values
8115 // For slow aliases (if HasDictionaryArgumentsElements()):
8116 // - the parameter map contains no fast alias mapping (i.e. the hole)
8117 // - this struct (in the slow backing store) contains an index into the context
8118 // - all attributes are available as part if the property details
8119 class AliasedArgumentsEntry: public Struct {
8121 inline int aliased_context_slot() const;
8122 inline void set_aliased_context_slot(int count);
8124 DECLARE_CAST(AliasedArgumentsEntry)
8126 // Dispatched behavior.
8127 DECLARE_PRINTER(AliasedArgumentsEntry)
8128 DECLARE_VERIFIER(AliasedArgumentsEntry)
8130 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
8131 static const int kSize = kAliasedContextSlot + kPointerSize;
8134 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
8138 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
8139 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
8142 class StringHasher {
8144 explicit inline StringHasher(int length, uint32_t seed);
8146 template <typename schar>
8147 static inline uint32_t HashSequentialString(const schar* chars,
8151 // Reads all the data, even for long strings and computes the utf16 length.
8152 static uint32_t ComputeUtf8Hash(Vector<const char> chars,
8154 int* utf16_length_out);
8156 // Calculated hash value for a string consisting of 1 to
8157 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
8158 // value is represented decimal value.
8159 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
8161 // No string is allowed to have a hash of zero. That value is reserved
8162 // for internal properties. If the hash calculation yields zero then we
8164 static const int kZeroHash = 27;
8166 // Reusable parts of the hashing algorithm.
8167 INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
8168 INLINE(static uint32_t GetHashCore(uint32_t running_hash));
8169 INLINE(static uint32_t ComputeRunningHash(uint32_t running_hash,
8170 const uc16* chars, int length));
8171 INLINE(static uint32_t ComputeRunningHashOneByte(uint32_t running_hash,
8176 // Returns the value to store in the hash field of a string with
8177 // the given length and contents.
8178 uint32_t GetHashField();
8179 // Returns true if the hash of this string can be computed without
8180 // looking at the contents.
8181 inline bool has_trivial_hash();
8182 // Adds a block of characters to the hash.
8183 template<typename Char>
8184 inline void AddCharacters(const Char* chars, int len);
8187 // Add a character to the hash.
8188 inline void AddCharacter(uint16_t c);
8189 // Update index. Returns true if string is still an index.
8190 inline bool UpdateIndex(uint16_t c);
8193 uint32_t raw_running_hash_;
8194 uint32_t array_index_;
8195 bool is_array_index_;
8196 bool is_first_char_;
8197 DISALLOW_COPY_AND_ASSIGN(StringHasher);
8201 class IteratingStringHasher : public StringHasher {
8203 static inline uint32_t Hash(String* string, uint32_t seed);
8204 inline void VisitOneByteString(const uint8_t* chars, int length);
8205 inline void VisitTwoByteString(const uint16_t* chars, int length);
8208 inline IteratingStringHasher(int len, uint32_t seed)
8209 : StringHasher(len, seed) {}
8210 void VisitConsString(ConsString* cons_string);
8211 DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher);
8215 // The characteristics of a string are stored in its map. Retrieving these
8216 // few bits of information is moderately expensive, involving two memory
8217 // loads where the second is dependent on the first. To improve efficiency
8218 // the shape of the string is given its own class so that it can be retrieved
8219 // once and used for several string operations. A StringShape is small enough
8220 // to be passed by value and is immutable, but be aware that flattening a
8221 // string can potentially alter its shape. Also be aware that a GC caused by
8222 // something else can alter the shape of a string due to ConsString
8223 // shortcutting. Keeping these restrictions in mind has proven to be error-
8224 // prone and so we no longer put StringShapes in variables unless there is a
8225 // concrete performance benefit at that particular point in the code.
8226 class StringShape BASE_EMBEDDED {
8228 inline explicit StringShape(const String* s);
8229 inline explicit StringShape(Map* s);
8230 inline explicit StringShape(InstanceType t);
8231 inline bool IsSequential();
8232 inline bool IsExternal();
8233 inline bool IsCons();
8234 inline bool IsSliced();
8235 inline bool IsIndirect();
8236 inline bool IsExternalOneByte();
8237 inline bool IsExternalTwoByte();
8238 inline bool IsSequentialOneByte();
8239 inline bool IsSequentialTwoByte();
8240 inline bool IsInternalized();
8241 inline StringRepresentationTag representation_tag();
8242 inline uint32_t encoding_tag();
8243 inline uint32_t full_representation_tag();
8244 inline uint32_t size_tag();
8246 inline uint32_t type() { return type_; }
8247 inline void invalidate() { valid_ = false; }
8248 inline bool valid() { return valid_; }
8250 inline void invalidate() { }
8256 inline void set_valid() { valid_ = true; }
8259 inline void set_valid() { }
8264 // The Name abstract class captures anything that can be used as a property
8265 // name, i.e., strings and symbols. All names store a hash value.
8266 class Name: public HeapObject {
8268 // Get and set the hash field of the name.
8269 inline uint32_t hash_field();
8270 inline void set_hash_field(uint32_t value);
8272 // Tells whether the hash code has been computed.
8273 inline bool HasHashCode();
8275 // Returns a hash value used for the property table
8276 inline uint32_t Hash();
8278 // Equality operations.
8279 inline bool Equals(Name* other);
8280 inline static bool Equals(Handle<Name> one, Handle<Name> two);
8283 inline bool AsArrayIndex(uint32_t* index);
8285 // If the name is private, it can only name own properties.
8286 inline bool IsPrivate();
8288 // If the name is a non-flat string, this method returns a flat version of the
8289 // string. Otherwise it'll just return the input.
8290 static inline Handle<Name> Flatten(Handle<Name> name,
8291 PretenureFlag pretenure = NOT_TENURED);
8295 DECLARE_PRINTER(Name)
8297 void NameShortPrint();
8298 int NameShortPrint(Vector<char> str);
8301 // Layout description.
8302 static const int kHashFieldSlot = HeapObject::kHeaderSize;
8303 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
8304 static const int kHashFieldOffset = kHashFieldSlot;
8306 static const int kHashFieldOffset = kHashFieldSlot + kIntSize;
8308 static const int kSize = kHashFieldSlot + kPointerSize;
8310 // Mask constant for checking if a name has a computed hash code
8311 // and if it is a string that is an array index. The least significant bit
8312 // indicates whether a hash code has been computed. If the hash code has
8313 // been computed the 2nd bit tells whether the string can be used as an
8315 static const int kHashNotComputedMask = 1;
8316 static const int kIsNotArrayIndexMask = 1 << 1;
8317 static const int kNofHashBitFields = 2;
8319 // Shift constant retrieving hash code from hash field.
8320 static const int kHashShift = kNofHashBitFields;
8322 // Only these bits are relevant in the hash, since the top two are shifted
8324 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8326 // Array index strings this short can keep their index in the hash field.
8327 static const int kMaxCachedArrayIndexLength = 7;
8329 // For strings which are array indexes the hash value has the string length
8330 // mixed into the hash, mainly to avoid a hash value of zero which would be
8331 // the case for the string '0'. 24 bits are used for the array index value.
8332 static const int kArrayIndexValueBits = 24;
8333 static const int kArrayIndexLengthBits =
8334 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8336 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8338 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8339 kArrayIndexValueBits> {}; // NOLINT
8340 class ArrayIndexLengthBits : public BitField<unsigned int,
8341 kNofHashBitFields + kArrayIndexValueBits,
8342 kArrayIndexLengthBits> {}; // NOLINT
8344 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8345 // could use a mask to test if the length of string is less than or equal to
8346 // kMaxCachedArrayIndexLength.
8347 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8349 static const unsigned int kContainsCachedArrayIndexMask =
8350 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8351 << ArrayIndexLengthBits::kShift) |
8352 kIsNotArrayIndexMask;
8354 // Value of empty hash field indicating that the hash is not computed.
8355 static const int kEmptyHashField =
8356 kIsNotArrayIndexMask | kHashNotComputedMask;
8359 static inline bool IsHashFieldComputed(uint32_t field);
8362 DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8367 class Symbol: public Name {
8369 // [name]: The print name of a symbol, or undefined if none.
8370 DECL_ACCESSORS(name, Object)
8372 DECL_ACCESSORS(flags, Smi)
8374 // [is_private]: Whether this is a private symbol. Private symbols can only
8375 // be used to designate own properties of objects.
8376 DECL_BOOLEAN_ACCESSORS(is_private)
8378 DECLARE_CAST(Symbol)
8380 // Dispatched behavior.
8381 DECLARE_PRINTER(Symbol)
8382 DECLARE_VERIFIER(Symbol)
8384 // Layout description.
8385 static const int kNameOffset = Name::kSize;
8386 static const int kFlagsOffset = kNameOffset + kPointerSize;
8387 static const int kSize = kFlagsOffset + kPointerSize;
8389 typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
8391 void SymbolShortPrint(std::ostream& os);
8394 static const int kPrivateBit = 0;
8396 const char* PrivateSymbolToName() const;
8399 friend class Name; // For PrivateSymbolToName.
8402 DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
8408 // The String abstract class captures JavaScript string values:
8411 // 4.3.16 String Value
8412 // A string value is a member of the type String and is a finite
8413 // ordered sequence of zero or more 16-bit unsigned integer values.
8415 // All string values have a length field.
8416 class String: public Name {
8418 enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
8420 // Array index strings this short can keep their index in the hash field.
8421 static const int kMaxCachedArrayIndexLength = 7;
8423 // For strings which are array indexes the hash value has the string length
8424 // mixed into the hash, mainly to avoid a hash value of zero which would be
8425 // the case for the string '0'. 24 bits are used for the array index value.
8426 static const int kArrayIndexValueBits = 24;
8427 static const int kArrayIndexLengthBits =
8428 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8430 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8432 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8433 kArrayIndexValueBits> {}; // NOLINT
8434 class ArrayIndexLengthBits : public BitField<unsigned int,
8435 kNofHashBitFields + kArrayIndexValueBits,
8436 kArrayIndexLengthBits> {}; // NOLINT
8438 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8439 // could use a mask to test if the length of string is less than or equal to
8440 // kMaxCachedArrayIndexLength.
8441 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8443 static const unsigned int kContainsCachedArrayIndexMask =
8444 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8445 << ArrayIndexLengthBits::kShift) |
8446 kIsNotArrayIndexMask;
8448 class SubStringRange {
8450 explicit SubStringRange(String* string, int first = 0, int length = -1)
8453 length_(length == -1 ? string->length() : length) {}
8455 inline iterator begin();
8456 inline iterator end();
8464 // Representation of the flat content of a String.
8465 // A non-flat string doesn't have flat content.
8466 // A flat string has content that's encoded as a sequence of either
8467 // one-byte chars or two-byte UC16.
8468 // Returned by String::GetFlatContent().
8471 // Returns true if the string is flat and this structure contains content.
8472 bool IsFlat() { return state_ != NON_FLAT; }
8473 // Returns true if the structure contains one-byte content.
8474 bool IsOneByte() { return state_ == ONE_BYTE; }
8475 // Returns true if the structure contains two-byte content.
8476 bool IsTwoByte() { return state_ == TWO_BYTE; }
8478 // Return the one byte content of the string. Only use if IsOneByte()
8480 Vector<const uint8_t> ToOneByteVector() {
8481 DCHECK_EQ(ONE_BYTE, state_);
8482 return Vector<const uint8_t>(onebyte_start, length_);
8484 // Return the two-byte content of the string. Only use if IsTwoByte()
8486 Vector<const uc16> ToUC16Vector() {
8487 DCHECK_EQ(TWO_BYTE, state_);
8488 return Vector<const uc16>(twobyte_start, length_);
8492 DCHECK(i < length_);
8493 DCHECK(state_ != NON_FLAT);
8494 if (state_ == ONE_BYTE) return onebyte_start[i];
8495 return twobyte_start[i];
8498 bool UsesSameString(const FlatContent& other) const {
8499 return onebyte_start == other.onebyte_start;
8503 enum State { NON_FLAT, ONE_BYTE, TWO_BYTE };
8505 // Constructors only used by String::GetFlatContent().
8506 explicit FlatContent(const uint8_t* start, int length)
8507 : onebyte_start(start), length_(length), state_(ONE_BYTE) {}
8508 explicit FlatContent(const uc16* start, int length)
8509 : twobyte_start(start), length_(length), state_(TWO_BYTE) { }
8510 FlatContent() : onebyte_start(NULL), length_(0), state_(NON_FLAT) { }
8513 const uint8_t* onebyte_start;
8514 const uc16* twobyte_start;
8519 friend class String;
8520 friend class IterableSubString;
8523 template <typename Char>
8524 INLINE(Vector<const Char> GetCharVector());
8526 // Get and set the length of the string.
8527 inline int length() const;
8528 inline void set_length(int value);
8530 // Get and set the length of the string using acquire loads and release
8532 inline int synchronized_length() const;
8533 inline void synchronized_set_length(int value);
8535 // Returns whether this string has only one-byte chars, i.e. all of them can
8536 // be one-byte encoded. This might be the case even if the string is
8537 // two-byte. Such strings may appear when the embedder prefers
8538 // two-byte external representations even for one-byte data.
8539 inline bool IsOneByteRepresentation() const;
8540 inline bool IsTwoByteRepresentation() const;
8542 // Cons and slices have an encoding flag that may not represent the actual
8543 // encoding of the underlying string. This is taken into account here.
8544 // Requires: this->IsFlat()
8545 inline bool IsOneByteRepresentationUnderneath();
8546 inline bool IsTwoByteRepresentationUnderneath();
8548 // NOTE: this should be considered only a hint. False negatives are
8550 inline bool HasOnlyOneByteChars();
8552 // Get and set individual two byte chars in the string.
8553 inline void Set(int index, uint16_t value);
8554 // Get individual two byte char in the string. Repeated calls
8555 // to this method are not efficient unless the string is flat.
8556 INLINE(uint16_t Get(int index));
8558 // Flattens the string. Checks first inline to see if it is
8559 // necessary. Does nothing if the string is not a cons string.
8560 // Flattening allocates a sequential string with the same data as
8561 // the given string and mutates the cons string to a degenerate
8562 // form, where the first component is the new sequential string and
8563 // the second component is the empty string. If allocation fails,
8564 // this function returns a failure. If flattening succeeds, this
8565 // function returns the sequential string that is now the first
8566 // component of the cons string.
8568 // Degenerate cons strings are handled specially by the garbage
8569 // collector (see IsShortcutCandidate).
8571 static inline Handle<String> Flatten(Handle<String> string,
8572 PretenureFlag pretenure = NOT_TENURED);
8574 // Tries to return the content of a flat string as a structure holding either
8575 // a flat vector of char or of uc16.
8576 // If the string isn't flat, and therefore doesn't have flat content, the
8577 // returned structure will report so, and can't provide a vector of either
8579 FlatContent GetFlatContent();
8581 // Returns the parent of a sliced string or first part of a flat cons string.
8582 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
8583 inline String* GetUnderlying();
8585 // String equality operations.
8586 inline bool Equals(String* other);
8587 inline static bool Equals(Handle<String> one, Handle<String> two);
8588 bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
8589 bool IsOneByteEqualTo(Vector<const uint8_t> str);
8590 bool IsTwoByteEqualTo(Vector<const uc16> str);
8592 // Return a UTF8 representation of the string. The string is null
8593 // terminated but may optionally contain nulls. Length is returned
8594 // in length_output if length_output is not a null pointer The string
8595 // should be nearly flat, otherwise the performance of this method may
8596 // be very slow (quadratic in the length). Setting robustness_flag to
8597 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8598 // handles unexpected data without causing assert failures and it does not
8599 // do any heap allocations. This is useful when printing stack traces.
8600 base::SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
8601 RobustnessFlag robustness_flag,
8602 int offset, int length,
8603 int* length_output = 0);
8604 base::SmartArrayPointer<char> ToCString(
8605 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
8606 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
8607 int* length_output = 0);
8609 // Return a 16 bit Unicode representation of the string.
8610 // The string should be nearly flat, otherwise the performance of
8611 // of this method may be very bad. Setting robustness_flag to
8612 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8613 // handles unexpected data without causing assert failures and it does not
8614 // do any heap allocations. This is useful when printing stack traces.
8615 base::SmartArrayPointer<uc16> ToWideCString(
8616 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
8618 bool ComputeArrayIndex(uint32_t* index);
8621 bool MakeExternal(v8::String::ExternalStringResource* resource);
8622 bool MakeExternal(v8::String::ExternalOneByteStringResource* resource);
8625 inline bool AsArrayIndex(uint32_t* index);
8627 DECLARE_CAST(String)
8629 void PrintOn(FILE* out);
8631 // For use during stack traces. Performs rudimentary sanity check.
8634 // Dispatched behavior.
8635 void StringShortPrint(StringStream* accumulator);
8636 void PrintUC16(std::ostream& os, int start = 0, int end = -1); // NOLINT
8637 #if defined(DEBUG) || defined(OBJECT_PRINT)
8638 char* ToAsciiArray();
8640 DECLARE_PRINTER(String)
8641 DECLARE_VERIFIER(String)
8643 inline bool IsFlat();
8645 // Layout description.
8646 static const int kLengthOffset = Name::kSize;
8647 static const int kSize = kLengthOffset + kPointerSize;
8649 // Maximum number of characters to consider when trying to convert a string
8650 // value into an array index.
8651 static const int kMaxArrayIndexSize = 10;
8652 STATIC_ASSERT(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
8655 static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
8656 static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
8657 static const int kMaxUtf16CodeUnit = 0xffff;
8658 static const uint32_t kMaxUtf16CodeUnitU = kMaxUtf16CodeUnit;
8660 // Value of hash field containing computed hash equal to zero.
8661 static const int kEmptyStringHash = kIsNotArrayIndexMask;
8663 // Maximal string length.
8664 static const int kMaxLength = (1 << 28) - 16;
8666 // Max length for computing hash. For strings longer than this limit the
8667 // string length is used as the hash value.
8668 static const int kMaxHashCalcLength = 16383;
8670 // Limit for truncation in short printing.
8671 static const int kMaxShortPrintLength = 1024;
8673 // Support for regular expressions.
8674 const uc16* GetTwoByteData(unsigned start);
8676 // Helper function for flattening strings.
8677 template <typename sinkchar>
8678 static void WriteToFlat(String* source,
8683 // The return value may point to the first aligned word containing the first
8684 // non-one-byte character, rather than directly to the non-one-byte character.
8685 // If the return value is >= the passed length, the entire string was
8687 static inline int NonAsciiStart(const char* chars, int length) {
8688 const char* start = chars;
8689 const char* limit = chars + length;
8691 if (length >= kIntptrSize) {
8692 // Check unaligned bytes.
8693 while (!IsAligned(reinterpret_cast<intptr_t>(chars), sizeof(uintptr_t))) {
8694 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8695 return static_cast<int>(chars - start);
8699 // Check aligned words.
8700 DCHECK(unibrow::Utf8::kMaxOneByteChar == 0x7F);
8701 const uintptr_t non_one_byte_mask = kUintptrAllBitsSet / 0xFF * 0x80;
8702 while (chars + sizeof(uintptr_t) <= limit) {
8703 if (*reinterpret_cast<const uintptr_t*>(chars) & non_one_byte_mask) {
8704 return static_cast<int>(chars - start);
8706 chars += sizeof(uintptr_t);
8709 // Check remaining unaligned bytes.
8710 while (chars < limit) {
8711 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8712 return static_cast<int>(chars - start);
8717 return static_cast<int>(chars - start);
8720 static inline bool IsAscii(const char* chars, int length) {
8721 return NonAsciiStart(chars, length) >= length;
8724 static inline bool IsAscii(const uint8_t* chars, int length) {
8726 NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
8729 static inline int NonOneByteStart(const uc16* chars, int length) {
8730 const uc16* limit = chars + length;
8731 const uc16* start = chars;
8732 while (chars < limit) {
8733 if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
8736 return static_cast<int>(chars - start);
8739 static inline bool IsOneByte(const uc16* chars, int length) {
8740 return NonOneByteStart(chars, length) >= length;
8743 template<class Visitor>
8744 static inline ConsString* VisitFlat(Visitor* visitor,
8748 static Handle<FixedArray> CalculateLineEnds(Handle<String> string,
8749 bool include_ending_line);
8751 // Use the hash field to forward to the canonical internalized string
8752 // when deserializing an internalized string.
8753 inline void SetForwardedInternalizedString(String* string);
8754 inline String* GetForwardedInternalizedString();
8758 friend class StringTableInsertionKey;
8760 static Handle<String> SlowFlatten(Handle<ConsString> cons,
8761 PretenureFlag tenure);
8763 // Slow case of String::Equals. This implementation works on any strings
8764 // but it is most efficient on strings that are almost flat.
8765 bool SlowEquals(String* other);
8767 static bool SlowEquals(Handle<String> one, Handle<String> two);
8769 // Slow case of AsArrayIndex.
8770 bool SlowAsArrayIndex(uint32_t* index);
8772 // Compute and set the hash code.
8773 uint32_t ComputeAndSetHash();
8775 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
8779 // The SeqString abstract class captures sequential string values.
8780 class SeqString: public String {
8782 DECLARE_CAST(SeqString)
8784 // Layout description.
8785 static const int kHeaderSize = String::kSize;
8787 // Truncate the string in-place if possible and return the result.
8788 // In case of new_length == 0, the empty string is returned without
8789 // truncating the original string.
8790 MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
8793 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
8797 // The OneByteString class captures sequential one-byte string objects.
8798 // Each character in the OneByteString is an one-byte character.
8799 class SeqOneByteString: public SeqString {
8801 static const bool kHasOneByteEncoding = true;
8803 // Dispatched behavior.
8804 inline uint16_t SeqOneByteStringGet(int index);
8805 inline void SeqOneByteStringSet(int index, uint16_t value);
8807 // Get the address of the characters in this string.
8808 inline Address GetCharsAddress();
8810 inline uint8_t* GetChars();
8812 DECLARE_CAST(SeqOneByteString)
8814 // Garbage collection support. This method is called by the
8815 // garbage collector to compute the actual size of an OneByteString
8817 inline int SeqOneByteStringSize(InstanceType instance_type);
8819 // Computes the size for an OneByteString instance of a given length.
8820 static int SizeFor(int length) {
8821 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
8824 // Maximal memory usage for a single sequential one-byte string.
8825 static const int kMaxSize = 512 * MB - 1;
8826 STATIC_ASSERT((kMaxSize - kHeaderSize) >= String::kMaxLength);
8829 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
8833 // The TwoByteString class captures sequential unicode string objects.
8834 // Each character in the TwoByteString is a two-byte uint16_t.
8835 class SeqTwoByteString: public SeqString {
8837 static const bool kHasOneByteEncoding = false;
8839 // Dispatched behavior.
8840 inline uint16_t SeqTwoByteStringGet(int index);
8841 inline void SeqTwoByteStringSet(int index, uint16_t value);
8843 // Get the address of the characters in this string.
8844 inline Address GetCharsAddress();
8846 inline uc16* GetChars();
8849 const uint16_t* SeqTwoByteStringGetData(unsigned start);
8851 DECLARE_CAST(SeqTwoByteString)
8853 // Garbage collection support. This method is called by the
8854 // garbage collector to compute the actual size of a TwoByteString
8856 inline int SeqTwoByteStringSize(InstanceType instance_type);
8858 // Computes the size for a TwoByteString instance of a given length.
8859 static int SizeFor(int length) {
8860 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
8863 // Maximal memory usage for a single sequential two-byte string.
8864 static const int kMaxSize = 512 * MB - 1;
8865 STATIC_ASSERT(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
8866 String::kMaxLength);
8869 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
8873 // The ConsString class describes string values built by using the
8874 // addition operator on strings. A ConsString is a pair where the
8875 // first and second components are pointers to other string values.
8876 // One or both components of a ConsString can be pointers to other
8877 // ConsStrings, creating a binary tree of ConsStrings where the leaves
8878 // are non-ConsString string values. The string value represented by
8879 // a ConsString can be obtained by concatenating the leaf string
8880 // values in a left-to-right depth-first traversal of the tree.
8881 class ConsString: public String {
8883 // First string of the cons cell.
8884 inline String* first();
8885 // Doesn't check that the result is a string, even in debug mode. This is
8886 // useful during GC where the mark bits confuse the checks.
8887 inline Object* unchecked_first();
8888 inline void set_first(String* first,
8889 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8891 // Second string of the cons cell.
8892 inline String* second();
8893 // Doesn't check that the result is a string, even in debug mode. This is
8894 // useful during GC where the mark bits confuse the checks.
8895 inline Object* unchecked_second();
8896 inline void set_second(String* second,
8897 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8899 // Dispatched behavior.
8900 uint16_t ConsStringGet(int index);
8902 DECLARE_CAST(ConsString)
8904 // Layout description.
8905 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
8906 static const int kSecondOffset = kFirstOffset + kPointerSize;
8907 static const int kSize = kSecondOffset + kPointerSize;
8909 // Minimum length for a cons string.
8910 static const int kMinLength = 13;
8912 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
8915 DECLARE_VERIFIER(ConsString)
8918 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
8922 // The Sliced String class describes strings that are substrings of another
8923 // sequential string. The motivation is to save time and memory when creating
8924 // a substring. A Sliced String is described as a pointer to the parent,
8925 // the offset from the start of the parent string and the length. Using
8926 // a Sliced String therefore requires unpacking of the parent string and
8927 // adding the offset to the start address. A substring of a Sliced String
8928 // are not nested since the double indirection is simplified when creating
8929 // such a substring.
8930 // Currently missing features are:
8931 // - handling externalized parent strings
8932 // - external strings as parent
8933 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
8934 class SlicedString: public String {
8936 inline String* parent();
8937 inline void set_parent(String* parent,
8938 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8939 inline int offset() const;
8940 inline void set_offset(int offset);
8942 // Dispatched behavior.
8943 uint16_t SlicedStringGet(int index);
8945 DECLARE_CAST(SlicedString)
8947 // Layout description.
8948 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
8949 static const int kOffsetOffset = kParentOffset + kPointerSize;
8950 static const int kSize = kOffsetOffset + kPointerSize;
8952 // Minimum length for a sliced string.
8953 static const int kMinLength = 13;
8955 typedef FixedBodyDescriptor<kParentOffset,
8956 kOffsetOffset + kPointerSize, kSize>
8959 DECLARE_VERIFIER(SlicedString)
8962 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
8966 // The ExternalString class describes string values that are backed by
8967 // a string resource that lies outside the V8 heap. ExternalStrings
8968 // consist of the length field common to all strings, a pointer to the
8969 // external resource. It is important to ensure (externally) that the
8970 // resource is not deallocated while the ExternalString is live in the
8973 // The API expects that all ExternalStrings are created through the
8974 // API. Therefore, ExternalStrings should not be used internally.
8975 class ExternalString: public String {
8977 DECLARE_CAST(ExternalString)
8979 // Layout description.
8980 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
8981 static const int kShortSize = kResourceOffset + kPointerSize;
8982 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
8983 static const int kSize = kResourceDataOffset + kPointerSize;
8985 static const int kMaxShortLength =
8986 (kShortSize - SeqString::kHeaderSize) / kCharSize;
8988 // Return whether external string is short (data pointer is not cached).
8989 inline bool is_short();
8991 STATIC_ASSERT(kResourceOffset == Internals::kStringResourceOffset);
8994 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
8998 // The ExternalOneByteString class is an external string backed by an
9000 class ExternalOneByteString : public ExternalString {
9002 static const bool kHasOneByteEncoding = true;
9004 typedef v8::String::ExternalOneByteStringResource Resource;
9006 // The underlying resource.
9007 inline const Resource* resource();
9008 inline void set_resource(const Resource* buffer);
9010 // Update the pointer cache to the external character array.
9011 // The cached pointer is always valid, as the external character array does =
9012 // not move during lifetime. Deserialization is the only exception, after
9013 // which the pointer cache has to be refreshed.
9014 inline void update_data_cache();
9016 inline const uint8_t* GetChars();
9018 // Dispatched behavior.
9019 inline uint16_t ExternalOneByteStringGet(int index);
9021 DECLARE_CAST(ExternalOneByteString)
9023 // Garbage collection support.
9024 inline void ExternalOneByteStringIterateBody(ObjectVisitor* v);
9026 template <typename StaticVisitor>
9027 inline void ExternalOneByteStringIterateBody();
9030 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalOneByteString);
9034 // The ExternalTwoByteString class is an external string backed by a UTF-16
9036 class ExternalTwoByteString: public ExternalString {
9038 static const bool kHasOneByteEncoding = false;
9040 typedef v8::String::ExternalStringResource Resource;
9042 // The underlying string resource.
9043 inline const Resource* resource();
9044 inline void set_resource(const Resource* buffer);
9046 // Update the pointer cache to the external character array.
9047 // The cached pointer is always valid, as the external character array does =
9048 // not move during lifetime. Deserialization is the only exception, after
9049 // which the pointer cache has to be refreshed.
9050 inline void update_data_cache();
9052 inline const uint16_t* GetChars();
9054 // Dispatched behavior.
9055 inline uint16_t ExternalTwoByteStringGet(int index);
9058 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
9060 DECLARE_CAST(ExternalTwoByteString)
9062 // Garbage collection support.
9063 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
9065 template<typename StaticVisitor>
9066 inline void ExternalTwoByteStringIterateBody();
9069 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
9073 // Utility superclass for stack-allocated objects that must be updated
9074 // on gc. It provides two ways for the gc to update instances, either
9075 // iterating or updating after gc.
9076 class Relocatable BASE_EMBEDDED {
9078 explicit inline Relocatable(Isolate* isolate);
9079 inline virtual ~Relocatable();
9080 virtual void IterateInstance(ObjectVisitor* v) { }
9081 virtual void PostGarbageCollection() { }
9083 static void PostGarbageCollectionProcessing(Isolate* isolate);
9084 static int ArchiveSpacePerThread();
9085 static char* ArchiveState(Isolate* isolate, char* to);
9086 static char* RestoreState(Isolate* isolate, char* from);
9087 static void Iterate(Isolate* isolate, ObjectVisitor* v);
9088 static void Iterate(ObjectVisitor* v, Relocatable* top);
9089 static char* Iterate(ObjectVisitor* v, char* t);
9097 // A flat string reader provides random access to the contents of a
9098 // string independent of the character width of the string. The handle
9099 // must be valid as long as the reader is being used.
9100 class FlatStringReader : public Relocatable {
9102 FlatStringReader(Isolate* isolate, Handle<String> str);
9103 FlatStringReader(Isolate* isolate, Vector<const char> input);
9104 void PostGarbageCollection();
9105 inline uc32 Get(int index);
9106 template <typename Char>
9107 inline Char Get(int index);
9108 int length() { return length_; }
9117 // This maintains an off-stack representation of the stack frames required
9118 // to traverse a ConsString, allowing an entirely iterative and restartable
9119 // traversal of the entire string
9120 class ConsStringIterator {
9122 inline ConsStringIterator() {}
9123 inline explicit ConsStringIterator(ConsString* cons_string, int offset = 0) {
9124 Reset(cons_string, offset);
9126 inline void Reset(ConsString* cons_string, int offset = 0) {
9128 // Next will always return NULL.
9129 if (cons_string == NULL) return;
9130 Initialize(cons_string, offset);
9132 // Returns NULL when complete.
9133 inline String* Next(int* offset_out) {
9135 if (depth_ == 0) return NULL;
9136 return Continue(offset_out);
9140 static const int kStackSize = 32;
9141 // Use a mask instead of doing modulo operations for stack wrapping.
9142 static const int kDepthMask = kStackSize-1;
9143 STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
9144 static inline int OffsetForDepth(int depth);
9146 inline void PushLeft(ConsString* string);
9147 inline void PushRight(ConsString* string);
9148 inline void AdjustMaximumDepth();
9150 inline bool StackBlown() { return maximum_depth_ - depth_ == kStackSize; }
9151 void Initialize(ConsString* cons_string, int offset);
9152 String* Continue(int* offset_out);
9153 String* NextLeaf(bool* blew_stack);
9154 String* Search(int* offset_out);
9156 // Stack must always contain only frames for which right traversal
9157 // has not yet been performed.
9158 ConsString* frames_[kStackSize];
9163 DISALLOW_COPY_AND_ASSIGN(ConsStringIterator);
9167 class StringCharacterStream {
9169 inline StringCharacterStream(String* string,
9171 inline uint16_t GetNext();
9172 inline bool HasMore();
9173 inline void Reset(String* string, int offset = 0);
9174 inline void VisitOneByteString(const uint8_t* chars, int length);
9175 inline void VisitTwoByteString(const uint16_t* chars, int length);
9178 ConsStringIterator iter_;
9181 const uint8_t* buffer8_;
9182 const uint16_t* buffer16_;
9184 const uint8_t* end_;
9185 DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
9189 template <typename T>
9190 class VectorIterator {
9192 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
9193 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
9194 T GetNext() { return data_[index_++]; }
9195 bool has_more() { return index_ < data_.length(); }
9197 Vector<const T> data_;
9202 // The Oddball describes objects null, undefined, true, and false.
9203 class Oddball: public HeapObject {
9205 // [to_string]: Cached to_string computed at startup.
9206 DECL_ACCESSORS(to_string, String)
9208 // [to_number]: Cached to_number computed at startup.
9209 DECL_ACCESSORS(to_number, Object)
9211 inline byte kind() const;
9212 inline void set_kind(byte kind);
9214 DECLARE_CAST(Oddball)
9216 // Dispatched behavior.
9217 DECLARE_VERIFIER(Oddball)
9219 // Initialize the fields.
9220 static void Initialize(Isolate* isolate,
9221 Handle<Oddball> oddball,
9222 const char* to_string,
9223 Handle<Object> to_number,
9226 // Layout description.
9227 static const int kToStringOffset = HeapObject::kHeaderSize;
9228 static const int kToNumberOffset = kToStringOffset + kPointerSize;
9229 static const int kKindOffset = kToNumberOffset + kPointerSize;
9230 static const int kSize = kKindOffset + kPointerSize;
9232 static const byte kFalse = 0;
9233 static const byte kTrue = 1;
9234 static const byte kNotBooleanMask = ~1;
9235 static const byte kTheHole = 2;
9236 static const byte kNull = 3;
9237 static const byte kArgumentMarker = 4;
9238 static const byte kUndefined = 5;
9239 static const byte kUninitialized = 6;
9240 static const byte kOther = 7;
9241 static const byte kException = 8;
9243 typedef FixedBodyDescriptor<kToStringOffset,
9244 kToNumberOffset + kPointerSize,
9245 kSize> BodyDescriptor;
9247 STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset);
9248 STATIC_ASSERT(kNull == Internals::kNullOddballKind);
9249 STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind);
9252 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
9256 class Cell: public HeapObject {
9258 // [value]: value of the cell.
9259 DECL_ACCESSORS(value, Object)
9263 static inline Cell* FromValueAddress(Address value) {
9264 Object* result = FromAddress(value - kValueOffset);
9265 return static_cast<Cell*>(result);
9268 inline Address ValueAddress() {
9269 return address() + kValueOffset;
9272 // Dispatched behavior.
9273 DECLARE_PRINTER(Cell)
9274 DECLARE_VERIFIER(Cell)
9276 // Layout description.
9277 static const int kValueOffset = HeapObject::kHeaderSize;
9278 static const int kSize = kValueOffset + kPointerSize;
9280 typedef FixedBodyDescriptor<kValueOffset,
9281 kValueOffset + kPointerSize,
9282 kSize> BodyDescriptor;
9285 DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9289 class PropertyCell : public HeapObject {
9291 // [property_details]: details of the global property.
9292 DECL_ACCESSORS(property_details_raw, Object)
9293 // [value]: value of the global property.
9294 DECL_ACCESSORS(value, Object)
9295 // [dependent_code]: dependent code that depends on the type of the global
9297 DECL_ACCESSORS(dependent_code, DependentCode)
9299 PropertyDetails property_details() {
9300 return PropertyDetails(Smi::cast(property_details_raw()));
9303 void set_property_details(PropertyDetails details) {
9304 set_property_details_raw(details.AsSmi());
9307 PropertyCellConstantType GetConstantType();
9309 // Computes the new type of the cell's contents for the given value, but
9310 // without actually modifying the details.
9311 static PropertyCellType UpdatedType(Handle<PropertyCell> cell,
9312 Handle<Object> value,
9313 PropertyDetails details);
9314 static void UpdateCell(Handle<GlobalDictionary> dictionary, int entry,
9315 Handle<Object> value, PropertyDetails details);
9317 static Handle<PropertyCell> InvalidateEntry(
9318 Handle<GlobalDictionary> dictionary, int entry);
9320 static void SetValueWithInvalidation(Handle<PropertyCell> cell,
9321 Handle<Object> new_value);
9323 DECLARE_CAST(PropertyCell)
9325 // Dispatched behavior.
9326 DECLARE_PRINTER(PropertyCell)
9327 DECLARE_VERIFIER(PropertyCell)
9329 // Layout description.
9330 static const int kDetailsOffset = HeapObject::kHeaderSize;
9331 static const int kValueOffset = kDetailsOffset + kPointerSize;
9332 static const int kDependentCodeOffset = kValueOffset + kPointerSize;
9333 static const int kSize = kDependentCodeOffset + kPointerSize;
9335 static const int kPointerFieldsBeginOffset = kValueOffset;
9336 static const int kPointerFieldsEndOffset = kSize;
9338 typedef FixedBodyDescriptor<kValueOffset,
9340 kSize> BodyDescriptor;
9343 DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9347 class WeakCell : public HeapObject {
9349 inline Object* value() const;
9351 // This should not be called by anyone except GC.
9352 inline void clear();
9354 // This should not be called by anyone except allocator.
9355 inline void initialize(HeapObject* value);
9357 inline bool cleared() const;
9359 DECL_ACCESSORS(next, Object)
9361 inline void clear_next(Heap* heap);
9363 inline bool next_cleared();
9365 DECLARE_CAST(WeakCell)
9367 DECLARE_PRINTER(WeakCell)
9368 DECLARE_VERIFIER(WeakCell)
9370 // Layout description.
9371 static const int kValueOffset = HeapObject::kHeaderSize;
9372 static const int kNextOffset = kValueOffset + kPointerSize;
9373 static const int kSize = kNextOffset + kPointerSize;
9375 typedef FixedBodyDescriptor<kValueOffset, kSize, kSize> BodyDescriptor;
9378 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakCell);
9382 // The JSProxy describes EcmaScript Harmony proxies
9383 class JSProxy: public JSReceiver {
9385 // [handler]: The handler property.
9386 DECL_ACCESSORS(handler, Object)
9388 // [hash]: The hash code property (undefined if not initialized yet).
9389 DECL_ACCESSORS(hash, Object)
9391 DECLARE_CAST(JSProxy)
9393 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithHandler(
9394 Handle<JSProxy> proxy,
9395 Handle<Object> receiver,
9398 // If the handler defines an accessor property with a setter, invoke it.
9399 // If it defines an accessor property without a setter, or a data property
9400 // that is read-only, throw. In all these cases set '*done' to true,
9401 // otherwise set it to false.
9403 static MaybeHandle<Object> SetPropertyViaPrototypesWithHandler(
9404 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9405 Handle<Object> value, LanguageMode language_mode, bool* done);
9407 MUST_USE_RESULT static Maybe<PropertyAttributes>
9408 GetPropertyAttributesWithHandler(Handle<JSProxy> proxy,
9409 Handle<Object> receiver,
9411 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithHandler(
9412 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9413 Handle<Object> value, LanguageMode language_mode);
9415 // Turn the proxy into an (empty) JSObject.
9416 static void Fix(Handle<JSProxy> proxy);
9418 // Initializes the body after the handler slot.
9419 inline void InitializeBody(int object_size, Object* value);
9421 // Invoke a trap by name. If the trap does not exist on this's handler,
9422 // but derived_trap is non-NULL, invoke that instead. May cause GC.
9423 MUST_USE_RESULT static MaybeHandle<Object> CallTrap(
9424 Handle<JSProxy> proxy,
9426 Handle<Object> derived_trap,
9428 Handle<Object> args[]);
9430 // Dispatched behavior.
9431 DECLARE_PRINTER(JSProxy)
9432 DECLARE_VERIFIER(JSProxy)
9434 // Layout description. We add padding so that a proxy has the same
9435 // size as a virgin JSObject. This is essential for becoming a JSObject
9437 static const int kHandlerOffset = HeapObject::kHeaderSize;
9438 static const int kHashOffset = kHandlerOffset + kPointerSize;
9439 static const int kPaddingOffset = kHashOffset + kPointerSize;
9440 static const int kSize = JSObject::kHeaderSize;
9441 static const int kHeaderSize = kPaddingOffset;
9442 static const int kPaddingSize = kSize - kPaddingOffset;
9444 STATIC_ASSERT(kPaddingSize >= 0);
9446 typedef FixedBodyDescriptor<kHandlerOffset,
9448 kSize> BodyDescriptor;
9451 friend class JSReceiver;
9453 MUST_USE_RESULT static Maybe<bool> HasPropertyWithHandler(
9454 Handle<JSProxy> proxy, Handle<Name> name);
9456 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithHandler(
9457 Handle<JSProxy> proxy, Handle<Name> name, LanguageMode language_mode);
9459 MUST_USE_RESULT Object* GetIdentityHash();
9461 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
9463 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
9467 class JSFunctionProxy: public JSProxy {
9469 // [call_trap]: The call trap.
9470 DECL_ACCESSORS(call_trap, Object)
9472 // [construct_trap]: The construct trap.
9473 DECL_ACCESSORS(construct_trap, Object)
9475 DECLARE_CAST(JSFunctionProxy)
9477 // Dispatched behavior.
9478 DECLARE_PRINTER(JSFunctionProxy)
9479 DECLARE_VERIFIER(JSFunctionProxy)
9481 // Layout description.
9482 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
9483 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
9484 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
9485 static const int kSize = JSFunction::kSize;
9486 static const int kPaddingSize = kSize - kPaddingOffset;
9488 STATIC_ASSERT(kPaddingSize >= 0);
9490 typedef FixedBodyDescriptor<kHandlerOffset,
9491 kConstructTrapOffset + kPointerSize,
9492 kSize> BodyDescriptor;
9495 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
9499 class JSCollection : public JSObject {
9501 // [table]: the backing hash table
9502 DECL_ACCESSORS(table, Object)
9504 static const int kTableOffset = JSObject::kHeaderSize;
9505 static const int kSize = kTableOffset + kPointerSize;
9508 DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollection);
9512 // The JSSet describes EcmaScript Harmony sets
9513 class JSSet : public JSCollection {
9517 // Dispatched behavior.
9518 DECLARE_PRINTER(JSSet)
9519 DECLARE_VERIFIER(JSSet)
9522 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
9526 // The JSMap describes EcmaScript Harmony maps
9527 class JSMap : public JSCollection {
9531 // Dispatched behavior.
9532 DECLARE_PRINTER(JSMap)
9533 DECLARE_VERIFIER(JSMap)
9536 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
9540 // OrderedHashTableIterator is an iterator that iterates over the keys and
9541 // values of an OrderedHashTable.
9543 // The iterator has a reference to the underlying OrderedHashTable data,
9544 // [table], as well as the current [index] the iterator is at.
9546 // When the OrderedHashTable is rehashed it adds a reference from the old table
9547 // to the new table as well as storing enough data about the changes so that the
9548 // iterator [index] can be adjusted accordingly.
9550 // When the [Next] result from the iterator is requested, the iterator checks if
9551 // there is a newer table that it needs to transition to.
9552 template<class Derived, class TableType>
9553 class OrderedHashTableIterator: public JSObject {
9555 // [table]: the backing hash table mapping keys to values.
9556 DECL_ACCESSORS(table, Object)
9558 // [index]: The index into the data table.
9559 DECL_ACCESSORS(index, Object)
9561 // [kind]: The kind of iteration this is. One of the [Kind] enum values.
9562 DECL_ACCESSORS(kind, Object)
9565 void OrderedHashTableIteratorPrint(std::ostream& os); // NOLINT
9568 static const int kTableOffset = JSObject::kHeaderSize;
9569 static const int kIndexOffset = kTableOffset + kPointerSize;
9570 static const int kKindOffset = kIndexOffset + kPointerSize;
9571 static const int kSize = kKindOffset + kPointerSize;
9579 // Whether the iterator has more elements. This needs to be called before
9580 // calling |CurrentKey| and/or |CurrentValue|.
9583 // Move the index forward one.
9585 set_index(Smi::FromInt(Smi::cast(index())->value() + 1));
9588 // Populates the array with the next key and value and then moves the iterator
9590 // This returns the |kind| or 0 if the iterator is already at the end.
9591 Smi* Next(JSArray* value_array);
9593 // Returns the current key of the iterator. This should only be called when
9594 // |HasMore| returns true.
9595 inline Object* CurrentKey();
9598 // Transitions the iterator to the non obsolete backing store. This is a NOP
9599 // if the [table] is not obsolete.
9602 DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
9606 class JSSetIterator: public OrderedHashTableIterator<JSSetIterator,
9609 // Dispatched behavior.
9610 DECLARE_PRINTER(JSSetIterator)
9611 DECLARE_VERIFIER(JSSetIterator)
9613 DECLARE_CAST(JSSetIterator)
9615 // Called by |Next| to populate the array. This allows the subclasses to
9616 // populate the array differently.
9617 inline void PopulateValueArray(FixedArray* array);
9620 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSetIterator);
9624 class JSMapIterator: public OrderedHashTableIterator<JSMapIterator,
9627 // Dispatched behavior.
9628 DECLARE_PRINTER(JSMapIterator)
9629 DECLARE_VERIFIER(JSMapIterator)
9631 DECLARE_CAST(JSMapIterator)
9633 // Called by |Next| to populate the array. This allows the subclasses to
9634 // populate the array differently.
9635 inline void PopulateValueArray(FixedArray* array);
9638 // Returns the current value of the iterator. This should only be called when
9639 // |HasMore| returns true.
9640 inline Object* CurrentValue();
9642 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMapIterator);
9646 // Base class for both JSWeakMap and JSWeakSet
9647 class JSWeakCollection: public JSObject {
9649 // [table]: the backing hash table mapping keys to values.
9650 DECL_ACCESSORS(table, Object)
9652 // [next]: linked list of encountered weak maps during GC.
9653 DECL_ACCESSORS(next, Object)
9655 static const int kTableOffset = JSObject::kHeaderSize;
9656 static const int kNextOffset = kTableOffset + kPointerSize;
9657 static const int kSize = kNextOffset + kPointerSize;
9660 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
9664 // The JSWeakMap describes EcmaScript Harmony weak maps
9665 class JSWeakMap: public JSWeakCollection {
9667 DECLARE_CAST(JSWeakMap)
9669 // Dispatched behavior.
9670 DECLARE_PRINTER(JSWeakMap)
9671 DECLARE_VERIFIER(JSWeakMap)
9674 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
9678 // The JSWeakSet describes EcmaScript Harmony weak sets
9679 class JSWeakSet: public JSWeakCollection {
9681 DECLARE_CAST(JSWeakSet)
9683 // Dispatched behavior.
9684 DECLARE_PRINTER(JSWeakSet)
9685 DECLARE_VERIFIER(JSWeakSet)
9688 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
9692 // Whether a JSArrayBuffer is a SharedArrayBuffer or not.
9693 enum class SharedFlag { kNotShared, kShared };
9696 class JSArrayBuffer: public JSObject {
9698 // [backing_store]: backing memory for this array
9699 DECL_ACCESSORS(backing_store, void)
9701 // [byte_length]: length in bytes
9702 DECL_ACCESSORS(byte_length, Object)
9704 inline uint32_t bit_field() const;
9705 inline void set_bit_field(uint32_t bits);
9707 inline bool is_external();
9708 inline void set_is_external(bool value);
9710 inline bool is_neuterable();
9711 inline void set_is_neuterable(bool value);
9713 inline bool was_neutered();
9714 inline void set_was_neutered(bool value);
9716 inline bool is_shared();
9717 inline void set_is_shared(bool value);
9719 DECLARE_CAST(JSArrayBuffer)
9723 // Dispatched behavior.
9724 DECLARE_PRINTER(JSArrayBuffer)
9725 DECLARE_VERIFIER(JSArrayBuffer)
9727 static const int kBackingStoreOffset = JSObject::kHeaderSize;
9728 static const int kByteLengthOffset = kBackingStoreOffset + kPointerSize;
9729 static const int kBitFieldSlot = kByteLengthOffset + kPointerSize;
9730 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
9731 static const int kBitFieldOffset = kBitFieldSlot;
9733 static const int kBitFieldOffset = kBitFieldSlot + kIntSize;
9735 static const int kSize = kBitFieldSlot + kPointerSize;
9737 static const int kSizeWithInternalFields =
9738 kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
9740 class IsExternal : public BitField<bool, 1, 1> {};
9741 class IsNeuterable : public BitField<bool, 2, 1> {};
9742 class WasNeutered : public BitField<bool, 3, 1> {};
9743 class IsShared : public BitField<bool, 4, 1> {};
9746 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
9750 class JSArrayBufferView: public JSObject {
9752 // [buffer]: ArrayBuffer that this typed array views.
9753 DECL_ACCESSORS(buffer, Object)
9755 // [byte_offset]: offset of typed array in bytes.
9756 DECL_ACCESSORS(byte_offset, Object)
9758 // [byte_length]: length of typed array in bytes.
9759 DECL_ACCESSORS(byte_length, Object)
9761 DECLARE_CAST(JSArrayBufferView)
9763 DECLARE_VERIFIER(JSArrayBufferView)
9765 inline bool WasNeutered() const;
9767 static const int kBufferOffset = JSObject::kHeaderSize;
9768 static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
9769 static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
9770 static const int kViewSize = kByteLengthOffset + kPointerSize;
9774 DECL_ACCESSORS(raw_byte_offset, Object)
9775 DECL_ACCESSORS(raw_byte_length, Object)
9778 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
9782 class JSTypedArray: public JSArrayBufferView {
9784 // [length]: length of typed array in elements.
9785 DECL_ACCESSORS(length, Object)
9786 inline uint32_t length_value() const;
9788 DECLARE_CAST(JSTypedArray)
9790 ExternalArrayType type();
9791 size_t element_size();
9793 Handle<JSArrayBuffer> GetBuffer();
9795 // Dispatched behavior.
9796 DECLARE_PRINTER(JSTypedArray)
9797 DECLARE_VERIFIER(JSTypedArray)
9799 static const int kLengthOffset = kViewSize + kPointerSize;
9800 static const int kSize = kLengthOffset + kPointerSize;
9802 static const int kSizeWithInternalFields =
9803 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9806 static Handle<JSArrayBuffer> MaterializeArrayBuffer(
9807 Handle<JSTypedArray> typed_array);
9809 DECL_ACCESSORS(raw_length, Object)
9812 DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
9816 class JSDataView: public JSArrayBufferView {
9818 DECLARE_CAST(JSDataView)
9820 // Dispatched behavior.
9821 DECLARE_PRINTER(JSDataView)
9822 DECLARE_VERIFIER(JSDataView)
9824 static const int kSize = kViewSize;
9826 static const int kSizeWithInternalFields =
9827 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9830 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
9834 // Foreign describes objects pointing from JavaScript to C structures.
9835 class Foreign: public HeapObject {
9837 // [address]: field containing the address.
9838 inline Address foreign_address();
9839 inline void set_foreign_address(Address value);
9841 DECLARE_CAST(Foreign)
9843 // Dispatched behavior.
9844 inline void ForeignIterateBody(ObjectVisitor* v);
9846 template<typename StaticVisitor>
9847 inline void ForeignIterateBody();
9849 // Dispatched behavior.
9850 DECLARE_PRINTER(Foreign)
9851 DECLARE_VERIFIER(Foreign)
9853 // Layout description.
9855 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
9856 static const int kSize = kForeignAddressOffset + kPointerSize;
9858 STATIC_ASSERT(kForeignAddressOffset == Internals::kForeignAddressOffset);
9861 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
9865 // The JSArray describes JavaScript Arrays
9866 // Such an array can be in one of two modes:
9867 // - fast, backing storage is a FixedArray and length <= elements.length();
9868 // Please note: push and pop can be used to grow and shrink the array.
9869 // - slow, backing storage is a HashTable with numbers as keys.
9870 class JSArray: public JSObject {
9872 // [length]: The length property.
9873 DECL_ACCESSORS(length, Object)
9875 // Overload the length setter to skip write barrier when the length
9876 // is set to a smi. This matches the set function on FixedArray.
9877 inline void set_length(Smi* length);
9879 static bool HasReadOnlyLength(Handle<JSArray> array);
9880 static bool WouldChangeReadOnlyLength(Handle<JSArray> array, uint32_t index);
9881 static MaybeHandle<Object> ReadOnlyLengthError(Handle<JSArray> array);
9883 // Initialize the array with the given capacity. The function may
9884 // fail due to out-of-memory situations, but only if the requested
9885 // capacity is non-zero.
9886 static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
9888 // If the JSArray has fast elements, and new_length would result in
9889 // normalization, returns true.
9890 bool SetLengthWouldNormalize(uint32_t new_length);
9891 static inline bool SetLengthWouldNormalize(Heap* heap, uint32_t new_length);
9893 // Initializes the array to a certain length.
9894 inline bool AllowsSetLength();
9896 static void SetLength(Handle<JSArray> array, uint32_t length);
9897 // Same as above but will also queue splice records if |array| is observed.
9898 static MaybeHandle<Object> ObservableSetLength(Handle<JSArray> array,
9901 // Set the content of the array to the content of storage.
9902 static inline void SetContent(Handle<JSArray> array,
9903 Handle<FixedArrayBase> storage);
9905 DECLARE_CAST(JSArray)
9907 // Dispatched behavior.
9908 DECLARE_PRINTER(JSArray)
9909 DECLARE_VERIFIER(JSArray)
9911 // Number of element slots to pre-allocate for an empty array.
9912 static const int kPreallocatedArrayElements = 4;
9914 // Layout description.
9915 static const int kLengthOffset = JSObject::kHeaderSize;
9916 static const int kSize = kLengthOffset + kPointerSize;
9919 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
9923 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
9924 Handle<Map> initial_map);
9927 // JSRegExpResult is just a JSArray with a specific initial map.
9928 // This initial map adds in-object properties for "index" and "input"
9929 // properties, as assigned by RegExp.prototype.exec, which allows
9930 // faster creation of RegExp exec results.
9931 // This class just holds constants used when creating the result.
9932 // After creation the result must be treated as a JSArray in all regards.
9933 class JSRegExpResult: public JSArray {
9935 // Offsets of object fields.
9936 static const int kIndexOffset = JSArray::kSize;
9937 static const int kInputOffset = kIndexOffset + kPointerSize;
9938 static const int kSize = kInputOffset + kPointerSize;
9939 // Indices of in-object properties.
9940 static const int kIndexIndex = 0;
9941 static const int kInputIndex = 1;
9943 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
9947 class AccessorInfo: public Struct {
9949 DECL_ACCESSORS(name, Object)
9950 DECL_ACCESSORS(flag, Smi)
9951 DECL_ACCESSORS(expected_receiver_type, Object)
9953 inline bool all_can_read();
9954 inline void set_all_can_read(bool value);
9956 inline bool all_can_write();
9957 inline void set_all_can_write(bool value);
9959 inline bool is_special_data_property();
9960 inline void set_is_special_data_property(bool value);
9962 inline PropertyAttributes property_attributes();
9963 inline void set_property_attributes(PropertyAttributes attributes);
9965 // Checks whether the given receiver is compatible with this accessor.
9966 static bool IsCompatibleReceiverMap(Isolate* isolate,
9967 Handle<AccessorInfo> info,
9969 inline bool IsCompatibleReceiver(Object* receiver);
9971 DECLARE_CAST(AccessorInfo)
9973 // Dispatched behavior.
9974 DECLARE_VERIFIER(AccessorInfo)
9976 // Append all descriptors to the array that are not already there.
9977 // Return number added.
9978 static int AppendUnique(Handle<Object> descriptors,
9979 Handle<FixedArray> array,
9980 int valid_descriptors);
9982 static const int kNameOffset = HeapObject::kHeaderSize;
9983 static const int kFlagOffset = kNameOffset + kPointerSize;
9984 static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
9985 static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
9988 inline bool HasExpectedReceiverType() {
9989 return expected_receiver_type()->IsFunctionTemplateInfo();
9991 // Bit positions in flag.
9992 static const int kAllCanReadBit = 0;
9993 static const int kAllCanWriteBit = 1;
9994 static const int kSpecialDataProperty = 2;
9995 class AttributesField : public BitField<PropertyAttributes, 3, 3> {};
9997 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
10001 // An accessor must have a getter, but can have no setter.
10003 // When setting a property, V8 searches accessors in prototypes.
10004 // If an accessor was found and it does not have a setter,
10005 // the request is ignored.
10007 // If the accessor in the prototype has the READ_ONLY property attribute, then
10008 // a new value is added to the derived object when the property is set.
10009 // This shadows the accessor in the prototype.
10010 class ExecutableAccessorInfo: public AccessorInfo {
10012 DECL_ACCESSORS(getter, Object)
10013 DECL_ACCESSORS(setter, Object)
10014 DECL_ACCESSORS(data, Object)
10016 DECLARE_CAST(ExecutableAccessorInfo)
10018 // Dispatched behavior.
10019 DECLARE_PRINTER(ExecutableAccessorInfo)
10020 DECLARE_VERIFIER(ExecutableAccessorInfo)
10022 static const int kGetterOffset = AccessorInfo::kSize;
10023 static const int kSetterOffset = kGetterOffset + kPointerSize;
10024 static const int kDataOffset = kSetterOffset + kPointerSize;
10025 static const int kSize = kDataOffset + kPointerSize;
10027 static void ClearSetter(Handle<ExecutableAccessorInfo> info);
10030 DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
10034 // Support for JavaScript accessors: A pair of a getter and a setter. Each
10035 // accessor can either be
10036 // * a pointer to a JavaScript function or proxy: a real accessor
10037 // * undefined: considered an accessor by the spec, too, strangely enough
10038 // * the hole: an accessor which has not been set
10039 // * a pointer to a map: a transition used to ensure map sharing
10040 class AccessorPair: public Struct {
10042 DECL_ACCESSORS(getter, Object)
10043 DECL_ACCESSORS(setter, Object)
10045 DECLARE_CAST(AccessorPair)
10047 static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
10049 Object* get(AccessorComponent component) {
10050 return component == ACCESSOR_GETTER ? getter() : setter();
10053 void set(AccessorComponent component, Object* value) {
10054 if (component == ACCESSOR_GETTER) {
10061 // Note: Returns undefined instead in case of a hole.
10062 Object* GetComponent(AccessorComponent component);
10064 // Set both components, skipping arguments which are a JavaScript null.
10065 void SetComponents(Object* getter, Object* setter) {
10066 if (!getter->IsNull()) set_getter(getter);
10067 if (!setter->IsNull()) set_setter(setter);
10070 bool Equals(AccessorPair* pair) {
10071 return (this == pair) || pair->Equals(getter(), setter());
10074 bool Equals(Object* getter_value, Object* setter_value) {
10075 return (getter() == getter_value) && (setter() == setter_value);
10078 bool ContainsAccessor() {
10079 return IsJSAccessor(getter()) || IsJSAccessor(setter());
10082 // Dispatched behavior.
10083 DECLARE_PRINTER(AccessorPair)
10084 DECLARE_VERIFIER(AccessorPair)
10086 static const int kGetterOffset = HeapObject::kHeaderSize;
10087 static const int kSetterOffset = kGetterOffset + kPointerSize;
10088 static const int kSize = kSetterOffset + kPointerSize;
10091 // Strangely enough, in addition to functions and harmony proxies, the spec
10092 // requires us to consider undefined as a kind of accessor, too:
10094 // Object.defineProperty(obj, "foo", {get: undefined});
10095 // assertTrue("foo" in obj);
10096 bool IsJSAccessor(Object* obj) {
10097 return obj->IsSpecFunction() || obj->IsUndefined();
10100 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
10104 class AccessCheckInfo: public Struct {
10106 DECL_ACCESSORS(named_callback, Object)
10107 DECL_ACCESSORS(indexed_callback, Object)
10108 DECL_ACCESSORS(data, Object)
10110 DECLARE_CAST(AccessCheckInfo)
10112 // Dispatched behavior.
10113 DECLARE_PRINTER(AccessCheckInfo)
10114 DECLARE_VERIFIER(AccessCheckInfo)
10116 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
10117 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
10118 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
10119 static const int kSize = kDataOffset + kPointerSize;
10122 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
10126 class InterceptorInfo: public Struct {
10128 DECL_ACCESSORS(getter, Object)
10129 DECL_ACCESSORS(setter, Object)
10130 DECL_ACCESSORS(query, Object)
10131 DECL_ACCESSORS(deleter, Object)
10132 DECL_ACCESSORS(enumerator, Object)
10133 DECL_ACCESSORS(data, Object)
10134 DECL_BOOLEAN_ACCESSORS(can_intercept_symbols)
10135 DECL_BOOLEAN_ACCESSORS(all_can_read)
10136 DECL_BOOLEAN_ACCESSORS(non_masking)
10138 inline int flags() const;
10139 inline void set_flags(int flags);
10141 DECLARE_CAST(InterceptorInfo)
10143 // Dispatched behavior.
10144 DECLARE_PRINTER(InterceptorInfo)
10145 DECLARE_VERIFIER(InterceptorInfo)
10147 static const int kGetterOffset = HeapObject::kHeaderSize;
10148 static const int kSetterOffset = kGetterOffset + kPointerSize;
10149 static const int kQueryOffset = kSetterOffset + kPointerSize;
10150 static const int kDeleterOffset = kQueryOffset + kPointerSize;
10151 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
10152 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
10153 static const int kFlagsOffset = kDataOffset + kPointerSize;
10154 static const int kSize = kFlagsOffset + kPointerSize;
10156 static const int kCanInterceptSymbolsBit = 0;
10157 static const int kAllCanReadBit = 1;
10158 static const int kNonMasking = 2;
10161 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
10165 class CallHandlerInfo: public Struct {
10167 DECL_ACCESSORS(callback, Object)
10168 DECL_ACCESSORS(data, Object)
10170 DECLARE_CAST(CallHandlerInfo)
10172 // Dispatched behavior.
10173 DECLARE_PRINTER(CallHandlerInfo)
10174 DECLARE_VERIFIER(CallHandlerInfo)
10176 static const int kCallbackOffset = HeapObject::kHeaderSize;
10177 static const int kDataOffset = kCallbackOffset + kPointerSize;
10178 static const int kSize = kDataOffset + kPointerSize;
10181 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
10185 class TemplateInfo: public Struct {
10187 DECL_ACCESSORS(tag, Object)
10188 inline int number_of_properties() const;
10189 inline void set_number_of_properties(int value);
10190 DECL_ACCESSORS(property_list, Object)
10191 DECL_ACCESSORS(property_accessors, Object)
10193 DECLARE_VERIFIER(TemplateInfo)
10195 static const int kTagOffset = HeapObject::kHeaderSize;
10196 static const int kNumberOfProperties = kTagOffset + kPointerSize;
10197 static const int kPropertyListOffset = kNumberOfProperties + kPointerSize;
10198 static const int kPropertyAccessorsOffset =
10199 kPropertyListOffset + kPointerSize;
10200 static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
10203 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
10207 class FunctionTemplateInfo: public TemplateInfo {
10209 DECL_ACCESSORS(serial_number, Object)
10210 DECL_ACCESSORS(call_code, Object)
10211 DECL_ACCESSORS(prototype_template, Object)
10212 DECL_ACCESSORS(parent_template, Object)
10213 DECL_ACCESSORS(named_property_handler, Object)
10214 DECL_ACCESSORS(indexed_property_handler, Object)
10215 DECL_ACCESSORS(instance_template, Object)
10216 DECL_ACCESSORS(class_name, Object)
10217 DECL_ACCESSORS(signature, Object)
10218 DECL_ACCESSORS(instance_call_handler, Object)
10219 DECL_ACCESSORS(access_check_info, Object)
10220 DECL_ACCESSORS(flag, Smi)
10222 inline int length() const;
10223 inline void set_length(int value);
10225 // Following properties use flag bits.
10226 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
10227 DECL_BOOLEAN_ACCESSORS(undetectable)
10228 // If the bit is set, object instances created by this function
10229 // requires access check.
10230 DECL_BOOLEAN_ACCESSORS(needs_access_check)
10231 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
10232 DECL_BOOLEAN_ACCESSORS(remove_prototype)
10233 DECL_BOOLEAN_ACCESSORS(do_not_cache)
10234 DECL_BOOLEAN_ACCESSORS(instantiated)
10235 DECL_BOOLEAN_ACCESSORS(accept_any_receiver)
10237 DECLARE_CAST(FunctionTemplateInfo)
10239 // Dispatched behavior.
10240 DECLARE_PRINTER(FunctionTemplateInfo)
10241 DECLARE_VERIFIER(FunctionTemplateInfo)
10243 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
10244 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
10245 static const int kPrototypeTemplateOffset =
10246 kCallCodeOffset + kPointerSize;
10247 static const int kParentTemplateOffset =
10248 kPrototypeTemplateOffset + kPointerSize;
10249 static const int kNamedPropertyHandlerOffset =
10250 kParentTemplateOffset + kPointerSize;
10251 static const int kIndexedPropertyHandlerOffset =
10252 kNamedPropertyHandlerOffset + kPointerSize;
10253 static const int kInstanceTemplateOffset =
10254 kIndexedPropertyHandlerOffset + kPointerSize;
10255 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
10256 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
10257 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
10258 static const int kAccessCheckInfoOffset =
10259 kInstanceCallHandlerOffset + kPointerSize;
10260 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
10261 static const int kLengthOffset = kFlagOffset + kPointerSize;
10262 static const int kSize = kLengthOffset + kPointerSize;
10264 // Returns true if |object| is an instance of this function template.
10265 bool IsTemplateFor(Object* object);
10266 bool IsTemplateFor(Map* map);
10268 // Returns the holder JSObject if the function can legally be called with this
10269 // receiver. Returns Heap::null_value() if the call is illegal.
10270 Object* GetCompatibleReceiver(Isolate* isolate, Object* receiver);
10273 // Bit position in the flag, from least significant bit position.
10274 static const int kHiddenPrototypeBit = 0;
10275 static const int kUndetectableBit = 1;
10276 static const int kNeedsAccessCheckBit = 2;
10277 static const int kReadOnlyPrototypeBit = 3;
10278 static const int kRemovePrototypeBit = 4;
10279 static const int kDoNotCacheBit = 5;
10280 static const int kInstantiatedBit = 6;
10281 static const int kAcceptAnyReceiver = 7;
10283 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
10287 class ObjectTemplateInfo: public TemplateInfo {
10289 DECL_ACCESSORS(constructor, Object)
10290 DECL_ACCESSORS(internal_field_count, Object)
10292 DECLARE_CAST(ObjectTemplateInfo)
10294 // Dispatched behavior.
10295 DECLARE_PRINTER(ObjectTemplateInfo)
10296 DECLARE_VERIFIER(ObjectTemplateInfo)
10298 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10299 static const int kInternalFieldCountOffset =
10300 kConstructorOffset + kPointerSize;
10301 static const int kSize = kInternalFieldCountOffset + kPointerSize;
10305 class TypeSwitchInfo: public Struct {
10307 DECL_ACCESSORS(types, Object)
10309 DECLARE_CAST(TypeSwitchInfo)
10311 // Dispatched behavior.
10312 DECLARE_PRINTER(TypeSwitchInfo)
10313 DECLARE_VERIFIER(TypeSwitchInfo)
10315 static const int kTypesOffset = Struct::kHeaderSize;
10316 static const int kSize = kTypesOffset + kPointerSize;
10320 // The DebugInfo class holds additional information for a function being
10322 class DebugInfo: public Struct {
10324 // The shared function info for the source being debugged.
10325 DECL_ACCESSORS(shared, SharedFunctionInfo)
10326 // Code object for the patched code. This code object is the code object
10327 // currently active for the function.
10328 DECL_ACCESSORS(code, Code)
10329 // Fixed array holding status information for each active break point.
10330 DECL_ACCESSORS(break_points, FixedArray)
10332 // Check if there is a break point at a code position.
10333 bool HasBreakPoint(int code_position);
10334 // Get the break point info object for a code position.
10335 Object* GetBreakPointInfo(int code_position);
10336 // Clear a break point.
10337 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
10339 Handle<Object> break_point_object);
10340 // Set a break point.
10341 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
10342 int source_position, int statement_position,
10343 Handle<Object> break_point_object);
10344 // Get the break point objects for a code position.
10345 Handle<Object> GetBreakPointObjects(int code_position);
10346 // Find the break point info holding this break point object.
10347 static Handle<Object> FindBreakPointInfo(Handle<DebugInfo> debug_info,
10348 Handle<Object> break_point_object);
10349 // Get the number of break points for this function.
10350 int GetBreakPointCount();
10352 DECLARE_CAST(DebugInfo)
10354 // Dispatched behavior.
10355 DECLARE_PRINTER(DebugInfo)
10356 DECLARE_VERIFIER(DebugInfo)
10358 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
10359 static const int kCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
10360 static const int kBreakPointsStateIndex = kCodeIndex + kPointerSize;
10361 static const int kSize = kBreakPointsStateIndex + kPointerSize;
10363 static const int kEstimatedNofBreakPointsInFunction = 16;
10366 static const int kNoBreakPointInfo = -1;
10368 // Lookup the index in the break_points array for a code position.
10369 int GetBreakPointInfoIndex(int code_position);
10371 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
10375 // The BreakPointInfo class holds information for break points set in a
10376 // function. The DebugInfo object holds a BreakPointInfo object for each code
10377 // position with one or more break points.
10378 class BreakPointInfo: public Struct {
10380 // The position in the code for the break point.
10381 DECL_ACCESSORS(code_position, Smi)
10382 // The position in the source for the break position.
10383 DECL_ACCESSORS(source_position, Smi)
10384 // The position in the source for the last statement before this break
10386 DECL_ACCESSORS(statement_position, Smi)
10387 // List of related JavaScript break points.
10388 DECL_ACCESSORS(break_point_objects, Object)
10390 // Removes a break point.
10391 static void ClearBreakPoint(Handle<BreakPointInfo> info,
10392 Handle<Object> break_point_object);
10393 // Set a break point.
10394 static void SetBreakPoint(Handle<BreakPointInfo> info,
10395 Handle<Object> break_point_object);
10396 // Check if break point info has this break point object.
10397 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
10398 Handle<Object> break_point_object);
10399 // Get the number of break points for this code position.
10400 int GetBreakPointCount();
10402 DECLARE_CAST(BreakPointInfo)
10404 // Dispatched behavior.
10405 DECLARE_PRINTER(BreakPointInfo)
10406 DECLARE_VERIFIER(BreakPointInfo)
10408 static const int kCodePositionIndex = Struct::kHeaderSize;
10409 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
10410 static const int kStatementPositionIndex =
10411 kSourcePositionIndex + kPointerSize;
10412 static const int kBreakPointObjectsIndex =
10413 kStatementPositionIndex + kPointerSize;
10414 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
10417 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
10421 #undef DECL_BOOLEAN_ACCESSORS
10422 #undef DECL_ACCESSORS
10423 #undef DECLARE_CAST
10424 #undef DECLARE_VERIFIER
10426 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
10427 V(kStringTable, "string_table", "(Internalized strings)") \
10428 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
10429 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
10430 V(kSmiRootList, "smi_root_list", "(Smi roots)") \
10431 V(kInternalizedString, "internalized_string", "(Internal string)") \
10432 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
10433 V(kTop, "top", "(Isolate)") \
10434 V(kRelocatable, "relocatable", "(Relocatable)") \
10435 V(kDebug, "debug", "(Debugger)") \
10436 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
10437 V(kHandleScope, "handlescope", "(Handle scope)") \
10438 V(kBuiltins, "builtins", "(Builtins)") \
10439 V(kGlobalHandles, "globalhandles", "(Global handles)") \
10440 V(kEternalHandles, "eternalhandles", "(Eternal handles)") \
10441 V(kThreadManager, "threadmanager", "(Thread manager)") \
10442 V(kStrongRoots, "strong roots", "(Strong roots)") \
10443 V(kExtensions, "Extensions", "(Extensions)")
10445 class VisitorSynchronization : public AllStatic {
10447 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
10449 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
10452 #undef DECLARE_ENUM
10454 static const char* const kTags[kNumberOfSyncTags];
10455 static const char* const kTagNames[kNumberOfSyncTags];
10458 // Abstract base class for visiting, and optionally modifying, the
10459 // pointers contained in Objects. Used in GC and serialization/deserialization.
10460 class ObjectVisitor BASE_EMBEDDED {
10462 virtual ~ObjectVisitor() {}
10464 // Visits a contiguous arrays of pointers in the half-open range
10465 // [start, end). Any or all of the values may be modified on return.
10466 virtual void VisitPointers(Object** start, Object** end) = 0;
10468 // Handy shorthand for visiting a single pointer.
10469 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
10471 // Visit weak next_code_link in Code object.
10472 virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
10474 // To allow lazy clearing of inline caches the visitor has
10475 // a rich interface for iterating over Code objects..
10477 // Visits a code target in the instruction stream.
10478 virtual void VisitCodeTarget(RelocInfo* rinfo);
10480 // Visits a code entry in a JS function.
10481 virtual void VisitCodeEntry(Address entry_address);
10483 // Visits a global property cell reference in the instruction stream.
10484 virtual void VisitCell(RelocInfo* rinfo);
10486 // Visits a runtime entry in the instruction stream.
10487 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
10489 // Visits the resource of an one-byte or two-byte string.
10490 virtual void VisitExternalOneByteString(
10491 v8::String::ExternalOneByteStringResource** resource) {}
10492 virtual void VisitExternalTwoByteString(
10493 v8::String::ExternalStringResource** resource) {}
10495 // Visits a debug call target in the instruction stream.
10496 virtual void VisitDebugTarget(RelocInfo* rinfo);
10498 // Visits the byte sequence in a function's prologue that contains information
10499 // about the code's age.
10500 virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
10502 // Visit pointer embedded into a code object.
10503 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
10505 // Visits an external reference embedded into a code object.
10506 virtual void VisitExternalReference(RelocInfo* rinfo);
10508 // Visits an external reference.
10509 virtual void VisitExternalReference(Address* p) {}
10511 // Visits an (encoded) internal reference.
10512 virtual void VisitInternalReference(RelocInfo* rinfo) {}
10514 // Visits a handle that has an embedder-assigned class ID.
10515 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
10517 // Intended for serialization/deserialization checking: insert, or
10518 // check for the presence of, a tag at this position in the stream.
10519 // Also used for marking up GC roots in heap snapshots.
10520 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
10524 class StructBodyDescriptor : public
10525 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
10527 static inline int SizeOf(Map* map, HeapObject* object) {
10528 return map->instance_size();
10533 // BooleanBit is a helper class for setting and getting a bit in an
10535 class BooleanBit : public AllStatic {
10537 static inline bool get(Smi* smi, int bit_position) {
10538 return get(smi->value(), bit_position);
10541 static inline bool get(int value, int bit_position) {
10542 return (value & (1 << bit_position)) != 0;
10545 static inline Smi* set(Smi* smi, int bit_position, bool v) {
10546 return Smi::FromInt(set(smi->value(), bit_position, v));
10549 static inline int set(int value, int bit_position, bool v) {
10551 value |= (1 << bit_position);
10553 value &= ~(1 << bit_position);
10559 } } // namespace v8::internal
10561 #endif // V8_OBJECTS_H_