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
90 // - JSFunctionResultCache
93 // - ScriptContextTable
100 // - SeqTwoByteString
104 // - ExternalOneByteString
105 // - ExternalTwoByteString
106 // - InternalizedString
107 // - SeqInternalizedString
108 // - SeqOneByteInternalizedString
109 // - SeqTwoByteInternalizedString
110 // - ConsInternalizedString
111 // - ExternalInternalizedString
112 // - ExternalOneByteInternalizedString
113 // - ExternalTwoByteInternalizedString
123 // - SharedFunctionInfo
127 // - ExecutableAccessorInfo
133 // - FunctionTemplateInfo
134 // - ObjectTemplateInfo
143 // Formats of Object*:
144 // Smi: [31 bit signed int] 0
145 // HeapObject: [32 bit direct pointer] (4 byte aligned) | 01
150 enum KeyedAccessStoreMode {
152 STORE_TRANSITION_SMI_TO_OBJECT,
153 STORE_TRANSITION_SMI_TO_DOUBLE,
154 STORE_TRANSITION_DOUBLE_TO_OBJECT,
155 STORE_TRANSITION_HOLEY_SMI_TO_OBJECT,
156 STORE_TRANSITION_HOLEY_SMI_TO_DOUBLE,
157 STORE_TRANSITION_HOLEY_DOUBLE_TO_OBJECT,
158 STORE_AND_GROW_NO_TRANSITION,
159 STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT,
160 STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE,
161 STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT,
162 STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_OBJECT,
163 STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_DOUBLE,
164 STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT,
165 STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS,
166 STORE_NO_TRANSITION_HANDLE_COW
170 enum TypeofMode { INSIDE_TYPEOF, NOT_INSIDE_TYPEOF };
179 enum ExternalArrayType {
180 kExternalInt8Array = 1,
183 kExternalUint16Array,
185 kExternalUint32Array,
186 kExternalFloat32Array,
187 kExternalFloat64Array,
188 kExternalUint8ClampedArray,
192 static const int kGrowICDelta = STORE_AND_GROW_NO_TRANSITION -
194 STATIC_ASSERT(STANDARD_STORE == 0);
195 STATIC_ASSERT(kGrowICDelta ==
196 STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT -
197 STORE_TRANSITION_SMI_TO_OBJECT);
198 STATIC_ASSERT(kGrowICDelta ==
199 STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE -
200 STORE_TRANSITION_SMI_TO_DOUBLE);
201 STATIC_ASSERT(kGrowICDelta ==
202 STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT -
203 STORE_TRANSITION_DOUBLE_TO_OBJECT);
206 static inline KeyedAccessStoreMode GetGrowStoreMode(
207 KeyedAccessStoreMode store_mode) {
208 if (store_mode < STORE_AND_GROW_NO_TRANSITION) {
209 store_mode = static_cast<KeyedAccessStoreMode>(
210 static_cast<int>(store_mode) + kGrowICDelta);
216 static inline bool IsTransitionStoreMode(KeyedAccessStoreMode store_mode) {
217 return store_mode > STANDARD_STORE &&
218 store_mode <= STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT &&
219 store_mode != STORE_AND_GROW_NO_TRANSITION;
223 static inline KeyedAccessStoreMode GetNonTransitioningStoreMode(
224 KeyedAccessStoreMode store_mode) {
225 if (store_mode >= STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS) {
228 if (store_mode >= STORE_AND_GROW_NO_TRANSITION) {
229 return STORE_AND_GROW_NO_TRANSITION;
231 return STANDARD_STORE;
235 static inline bool IsGrowStoreMode(KeyedAccessStoreMode store_mode) {
236 return store_mode >= STORE_AND_GROW_NO_TRANSITION &&
237 store_mode <= STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT;
241 enum IcCheckType { ELEMENT, PROPERTY };
244 // SKIP_WRITE_BARRIER skips the write barrier.
245 // UPDATE_WEAK_WRITE_BARRIER skips the marking part of the write barrier and
246 // only performs the generational part.
247 // UPDATE_WRITE_BARRIER is doing the full barrier, marking and generational.
248 enum WriteBarrierMode {
250 UPDATE_WEAK_WRITE_BARRIER,
255 // Indicates whether a value can be loaded as a constant.
256 enum StoreMode { ALLOW_IN_DESCRIPTOR, FORCE_FIELD };
259 // PropertyNormalizationMode is used to specify whether to keep
260 // inobject properties when normalizing properties of a JSObject.
261 enum PropertyNormalizationMode {
262 CLEAR_INOBJECT_PROPERTIES,
263 KEEP_INOBJECT_PROPERTIES
267 // Indicates how aggressively the prototype should be optimized. FAST_PROTOTYPE
268 // will give the fastest result by tailoring the map to the prototype, but that
269 // will cause polymorphism with other objects. REGULAR_PROTOTYPE is to be used
270 // (at least for now) when dynamically modifying the prototype chain of an
271 // object using __proto__ or Object.setPrototypeOf.
272 enum PrototypeOptimizationMode { REGULAR_PROTOTYPE, FAST_PROTOTYPE };
275 // Indicates whether transitions can be added to a source map or not.
276 enum TransitionFlag {
282 // Indicates whether the transition is simple: the target map of the transition
283 // either extends the current map with a new property, or it modifies the
284 // property that was added last to the current map.
285 enum SimpleTransitionFlag {
286 SIMPLE_PROPERTY_TRANSITION,
292 // Indicates whether we are only interested in the descriptors of a particular
293 // map, or in all descriptors in the descriptor array.
294 enum DescriptorFlag {
299 // The GC maintains a bit of information, the MarkingParity, which toggles
300 // from odd to even and back every time marking is completed. Incremental
301 // marking can visit an object twice during a marking phase, so algorithms that
302 // that piggy-back on marking can use the parity to ensure that they only
303 // perform an operation on an object once per marking phase: they record the
304 // MarkingParity when they visit an object, and only re-visit the object when it
305 // is marked again and the MarkingParity changes.
312 // ICs store extra state in a Code object. The default extra state is
314 typedef int ExtraICState;
315 static const ExtraICState kNoExtraICState = 0;
317 // Instance size sentinel for objects of variable size.
318 const int kVariableSizeSentinel = 0;
320 // We may store the unsigned bit field as signed Smi value and do not
322 const int kStubMajorKeyBits = 7;
323 const int kStubMinorKeyBits = kSmiValueSize - kStubMajorKeyBits - 1;
325 // All Maps have a field instance_type containing a InstanceType.
326 // It describes the type of the instances.
328 // As an example, a JavaScript object is a heap object and its map
329 // instance_type is JS_OBJECT_TYPE.
331 // The names of the string instance types are intended to systematically
332 // mirror their encoding in the instance_type field of the map. The default
333 // encoding is considered TWO_BYTE. It is not mentioned in the name. ONE_BYTE
334 // encoding is mentioned explicitly in the name. Likewise, the default
335 // representation is considered sequential. It is not mentioned in the
336 // name. The other representations (e.g. CONS, EXTERNAL) are explicitly
337 // mentioned. Finally, the string is either a STRING_TYPE (if it is a normal
338 // string) or a INTERNALIZED_STRING_TYPE (if it is a internalized string).
340 // NOTE: The following things are some that depend on the string types having
341 // instance_types that are less than those of all other types:
342 // HeapObject::Size, HeapObject::IterateBody, the typeof operator, and
345 // NOTE: Everything following JS_VALUE_TYPE is considered a
346 // JSObject for GC purposes. The first four entries here have typeof
347 // 'object', whereas JS_FUNCTION_TYPE has typeof 'function'.
348 #define INSTANCE_TYPE_LIST(V) \
350 V(ONE_BYTE_STRING_TYPE) \
351 V(CONS_STRING_TYPE) \
352 V(CONS_ONE_BYTE_STRING_TYPE) \
353 V(SLICED_STRING_TYPE) \
354 V(SLICED_ONE_BYTE_STRING_TYPE) \
355 V(EXTERNAL_STRING_TYPE) \
356 V(EXTERNAL_ONE_BYTE_STRING_TYPE) \
357 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
358 V(SHORT_EXTERNAL_STRING_TYPE) \
359 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE) \
360 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
362 V(INTERNALIZED_STRING_TYPE) \
363 V(ONE_BYTE_INTERNALIZED_STRING_TYPE) \
364 V(EXTERNAL_INTERNALIZED_STRING_TYPE) \
365 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
366 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
367 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE) \
368 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
369 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
378 V(PROPERTY_CELL_TYPE) \
380 V(HEAP_NUMBER_TYPE) \
381 V(MUTABLE_HEAP_NUMBER_TYPE) \
384 V(BYTECODE_ARRAY_TYPE) \
387 V(FIXED_INT8_ARRAY_TYPE) \
388 V(FIXED_UINT8_ARRAY_TYPE) \
389 V(FIXED_INT16_ARRAY_TYPE) \
390 V(FIXED_UINT16_ARRAY_TYPE) \
391 V(FIXED_INT32_ARRAY_TYPE) \
392 V(FIXED_UINT32_ARRAY_TYPE) \
393 V(FIXED_FLOAT32_ARRAY_TYPE) \
394 V(FIXED_FLOAT64_ARRAY_TYPE) \
395 V(FIXED_UINT8_CLAMPED_ARRAY_TYPE) \
399 V(DECLARED_ACCESSOR_DESCRIPTOR_TYPE) \
400 V(DECLARED_ACCESSOR_INFO_TYPE) \
401 V(EXECUTABLE_ACCESSOR_INFO_TYPE) \
402 V(ACCESSOR_PAIR_TYPE) \
403 V(ACCESS_CHECK_INFO_TYPE) \
404 V(INTERCEPTOR_INFO_TYPE) \
405 V(CALL_HANDLER_INFO_TYPE) \
406 V(FUNCTION_TEMPLATE_INFO_TYPE) \
407 V(OBJECT_TEMPLATE_INFO_TYPE) \
408 V(SIGNATURE_INFO_TYPE) \
409 V(TYPE_SWITCH_INFO_TYPE) \
410 V(ALLOCATION_MEMENTO_TYPE) \
411 V(ALLOCATION_SITE_TYPE) \
414 V(POLYMORPHIC_CODE_CACHE_TYPE) \
415 V(TYPE_FEEDBACK_INFO_TYPE) \
416 V(ALIASED_ARGUMENTS_ENTRY_TYPE) \
418 V(PROTOTYPE_INFO_TYPE) \
420 V(FIXED_ARRAY_TYPE) \
421 V(FIXED_DOUBLE_ARRAY_TYPE) \
422 V(SHARED_FUNCTION_INFO_TYPE) \
425 V(JS_MESSAGE_OBJECT_TYPE) \
430 V(JS_CONTEXT_EXTENSION_OBJECT_TYPE) \
431 V(JS_GENERATOR_OBJECT_TYPE) \
433 V(JS_GLOBAL_OBJECT_TYPE) \
434 V(JS_BUILTINS_OBJECT_TYPE) \
435 V(JS_GLOBAL_PROXY_TYPE) \
437 V(JS_ARRAY_BUFFER_TYPE) \
438 V(JS_TYPED_ARRAY_TYPE) \
439 V(JS_DATA_VIEW_TYPE) \
443 V(JS_SET_ITERATOR_TYPE) \
444 V(JS_MAP_ITERATOR_TYPE) \
445 V(JS_WEAK_MAP_TYPE) \
446 V(JS_WEAK_SET_TYPE) \
449 V(JS_FUNCTION_TYPE) \
450 V(JS_FUNCTION_PROXY_TYPE) \
452 V(BREAK_POINT_INFO_TYPE)
455 // Since string types are not consecutive, this macro is used to
456 // iterate over them.
457 #define STRING_TYPE_LIST(V) \
458 V(STRING_TYPE, kVariableSizeSentinel, string, String) \
459 V(ONE_BYTE_STRING_TYPE, kVariableSizeSentinel, one_byte_string, \
461 V(CONS_STRING_TYPE, ConsString::kSize, cons_string, ConsString) \
462 V(CONS_ONE_BYTE_STRING_TYPE, ConsString::kSize, cons_one_byte_string, \
464 V(SLICED_STRING_TYPE, SlicedString::kSize, sliced_string, SlicedString) \
465 V(SLICED_ONE_BYTE_STRING_TYPE, SlicedString::kSize, sliced_one_byte_string, \
466 SlicedOneByteString) \
467 V(EXTERNAL_STRING_TYPE, ExternalTwoByteString::kSize, external_string, \
469 V(EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kSize, \
470 external_one_byte_string, ExternalOneByteString) \
471 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, ExternalTwoByteString::kSize, \
472 external_string_with_one_byte_data, ExternalStringWithOneByteData) \
473 V(SHORT_EXTERNAL_STRING_TYPE, ExternalTwoByteString::kShortSize, \
474 short_external_string, ShortExternalString) \
475 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kShortSize, \
476 short_external_one_byte_string, ShortExternalOneByteString) \
477 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, \
478 ExternalTwoByteString::kShortSize, \
479 short_external_string_with_one_byte_data, \
480 ShortExternalStringWithOneByteData) \
482 V(INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, internalized_string, \
483 InternalizedString) \
484 V(ONE_BYTE_INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, \
485 one_byte_internalized_string, OneByteInternalizedString) \
486 V(EXTERNAL_INTERNALIZED_STRING_TYPE, ExternalTwoByteString::kSize, \
487 external_internalized_string, ExternalInternalizedString) \
488 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, ExternalOneByteString::kSize, \
489 external_one_byte_internalized_string, ExternalOneByteInternalizedString) \
490 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
491 ExternalTwoByteString::kSize, \
492 external_internalized_string_with_one_byte_data, \
493 ExternalInternalizedStringWithOneByteData) \
494 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE, \
495 ExternalTwoByteString::kShortSize, short_external_internalized_string, \
496 ShortExternalInternalizedString) \
497 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, \
498 ExternalOneByteString::kShortSize, \
499 short_external_one_byte_internalized_string, \
500 ShortExternalOneByteInternalizedString) \
501 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
502 ExternalTwoByteString::kShortSize, \
503 short_external_internalized_string_with_one_byte_data, \
504 ShortExternalInternalizedStringWithOneByteData)
506 // A struct is a simple object a set of object-valued fields. Including an
507 // object type in this causes the compiler to generate most of the boilerplate
508 // code for the class including allocation and garbage collection routines,
509 // casts and predicates. All you need to define is the class, methods and
510 // object verification routines. Easy, no?
512 // Note that for subtle reasons related to the ordering or numerical values of
513 // type tags, elements in this list have to be added to the INSTANCE_TYPE_LIST
515 #define STRUCT_LIST(V) \
517 V(EXECUTABLE_ACCESSOR_INFO, ExecutableAccessorInfo, \
518 executable_accessor_info) \
519 V(ACCESSOR_PAIR, AccessorPair, accessor_pair) \
520 V(ACCESS_CHECK_INFO, AccessCheckInfo, access_check_info) \
521 V(INTERCEPTOR_INFO, InterceptorInfo, interceptor_info) \
522 V(CALL_HANDLER_INFO, CallHandlerInfo, call_handler_info) \
523 V(FUNCTION_TEMPLATE_INFO, FunctionTemplateInfo, function_template_info) \
524 V(OBJECT_TEMPLATE_INFO, ObjectTemplateInfo, object_template_info) \
525 V(TYPE_SWITCH_INFO, TypeSwitchInfo, type_switch_info) \
526 V(SCRIPT, Script, script) \
527 V(ALLOCATION_SITE, AllocationSite, allocation_site) \
528 V(ALLOCATION_MEMENTO, AllocationMemento, allocation_memento) \
529 V(CODE_CACHE, CodeCache, code_cache) \
530 V(POLYMORPHIC_CODE_CACHE, PolymorphicCodeCache, polymorphic_code_cache) \
531 V(TYPE_FEEDBACK_INFO, TypeFeedbackInfo, type_feedback_info) \
532 V(ALIASED_ARGUMENTS_ENTRY, AliasedArgumentsEntry, aliased_arguments_entry) \
533 V(DEBUG_INFO, DebugInfo, debug_info) \
534 V(BREAK_POINT_INFO, BreakPointInfo, break_point_info) \
535 V(PROTOTYPE_INFO, PrototypeInfo, prototype_info)
537 // We use the full 8 bits of the instance_type field to encode heap object
538 // instance types. The high-order bit (bit 7) is set if the object is not a
539 // string, and cleared if it is a string.
540 const uint32_t kIsNotStringMask = 0x80;
541 const uint32_t kStringTag = 0x0;
542 const uint32_t kNotStringTag = 0x80;
544 // Bit 6 indicates that the object is an internalized string (if set) or not.
545 // Bit 7 has to be clear as well.
546 const uint32_t kIsNotInternalizedMask = 0x40;
547 const uint32_t kNotInternalizedTag = 0x40;
548 const uint32_t kInternalizedTag = 0x0;
550 // If bit 7 is clear then bit 2 indicates whether the string consists of
551 // two-byte characters or one-byte characters.
552 const uint32_t kStringEncodingMask = 0x4;
553 const uint32_t kTwoByteStringTag = 0x0;
554 const uint32_t kOneByteStringTag = 0x4;
556 // If bit 7 is clear, the low-order 2 bits indicate the representation
558 const uint32_t kStringRepresentationMask = 0x03;
559 enum StringRepresentationTag {
561 kConsStringTag = 0x1,
562 kExternalStringTag = 0x2,
563 kSlicedStringTag = 0x3
565 const uint32_t kIsIndirectStringMask = 0x1;
566 const uint32_t kIsIndirectStringTag = 0x1;
567 STATIC_ASSERT((kSeqStringTag & kIsIndirectStringMask) == 0); // NOLINT
568 STATIC_ASSERT((kExternalStringTag & kIsIndirectStringMask) == 0); // NOLINT
569 STATIC_ASSERT((kConsStringTag &
570 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
571 STATIC_ASSERT((kSlicedStringTag &
572 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
574 // Use this mask to distinguish between cons and slice only after making
575 // sure that the string is one of the two (an indirect string).
576 const uint32_t kSlicedNotConsMask = kSlicedStringTag & ~kConsStringTag;
577 STATIC_ASSERT(IS_POWER_OF_TWO(kSlicedNotConsMask));
579 // If bit 7 is clear, then bit 3 indicates whether this two-byte
580 // string actually contains one byte data.
581 const uint32_t kOneByteDataHintMask = 0x08;
582 const uint32_t kOneByteDataHintTag = 0x08;
584 // If bit 7 is clear and string representation indicates an external string,
585 // then bit 4 indicates whether the data pointer is cached.
586 const uint32_t kShortExternalStringMask = 0x10;
587 const uint32_t kShortExternalStringTag = 0x10;
590 // A ConsString with an empty string as the right side is a candidate
591 // for being shortcut by the garbage collector. We don't allocate any
592 // non-flat internalized strings, so we do not shortcut them thereby
593 // avoiding turning internalized strings into strings. The bit-masks
594 // below contain the internalized bit as additional safety.
595 // See heap.cc, mark-compact.cc and objects-visiting.cc.
596 const uint32_t kShortcutTypeMask =
598 kIsNotInternalizedMask |
599 kStringRepresentationMask;
600 const uint32_t kShortcutTypeTag = kConsStringTag | kNotInternalizedTag;
602 static inline bool IsShortcutCandidate(int type) {
603 return ((type & kShortcutTypeMask) == kShortcutTypeTag);
609 INTERNALIZED_STRING_TYPE =
610 kTwoByteStringTag | kSeqStringTag | kInternalizedTag,
611 ONE_BYTE_INTERNALIZED_STRING_TYPE =
612 kOneByteStringTag | kSeqStringTag | kInternalizedTag,
613 EXTERNAL_INTERNALIZED_STRING_TYPE =
614 kTwoByteStringTag | kExternalStringTag | kInternalizedTag,
615 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
616 kOneByteStringTag | kExternalStringTag | kInternalizedTag,
617 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
618 EXTERNAL_INTERNALIZED_STRING_TYPE | kOneByteDataHintTag |
620 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE = EXTERNAL_INTERNALIZED_STRING_TYPE |
621 kShortExternalStringTag |
623 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
624 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kShortExternalStringTag |
626 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
627 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
628 kShortExternalStringTag | kInternalizedTag,
629 STRING_TYPE = INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
630 ONE_BYTE_STRING_TYPE =
631 ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
632 CONS_STRING_TYPE = kTwoByteStringTag | kConsStringTag | kNotInternalizedTag,
633 CONS_ONE_BYTE_STRING_TYPE =
634 kOneByteStringTag | kConsStringTag | kNotInternalizedTag,
636 kTwoByteStringTag | kSlicedStringTag | kNotInternalizedTag,
637 SLICED_ONE_BYTE_STRING_TYPE =
638 kOneByteStringTag | kSlicedStringTag | kNotInternalizedTag,
639 EXTERNAL_STRING_TYPE =
640 EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
641 EXTERNAL_ONE_BYTE_STRING_TYPE =
642 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
643 EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
644 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
646 SHORT_EXTERNAL_STRING_TYPE =
647 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
648 SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE =
649 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
650 SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
651 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
655 SYMBOL_TYPE = kNotStringTag, // FIRST_NONSTRING_TYPE, LAST_NAME_TYPE
657 // Objects allocated in their own spaces (never in new space).
662 // "Data", objects that cannot contain non-map-word pointers to heap
665 MUTABLE_HEAP_NUMBER_TYPE,
666 FLOAT32X4_TYPE, // FIRST_SIMD_TYPE, LAST_SIMD_TYPE
671 FIXED_INT8_ARRAY_TYPE, // FIRST_FIXED_TYPED_ARRAY_TYPE
672 FIXED_UINT8_ARRAY_TYPE,
673 FIXED_INT16_ARRAY_TYPE,
674 FIXED_UINT16_ARRAY_TYPE,
675 FIXED_INT32_ARRAY_TYPE,
676 FIXED_UINT32_ARRAY_TYPE,
677 FIXED_FLOAT32_ARRAY_TYPE,
678 FIXED_FLOAT64_ARRAY_TYPE,
679 FIXED_UINT8_CLAMPED_ARRAY_TYPE, // LAST_FIXED_TYPED_ARRAY_TYPE
680 FIXED_DOUBLE_ARRAY_TYPE,
681 FILLER_TYPE, // LAST_DATA_TYPE
684 DECLARED_ACCESSOR_DESCRIPTOR_TYPE,
685 DECLARED_ACCESSOR_INFO_TYPE,
686 EXECUTABLE_ACCESSOR_INFO_TYPE,
688 ACCESS_CHECK_INFO_TYPE,
689 INTERCEPTOR_INFO_TYPE,
690 CALL_HANDLER_INFO_TYPE,
691 FUNCTION_TEMPLATE_INFO_TYPE,
692 OBJECT_TEMPLATE_INFO_TYPE,
694 TYPE_SWITCH_INFO_TYPE,
695 ALLOCATION_SITE_TYPE,
696 ALLOCATION_MEMENTO_TYPE,
699 POLYMORPHIC_CODE_CACHE_TYPE,
700 TYPE_FEEDBACK_INFO_TYPE,
701 ALIASED_ARGUMENTS_ENTRY_TYPE,
704 BREAK_POINT_INFO_TYPE,
706 SHARED_FUNCTION_INFO_TYPE,
712 // All the following types are subtypes of JSReceiver, which corresponds to
713 // objects in the JS sense. The first and the last type in this range are
714 // the two forms of function. This organization enables using the same
715 // compares for checking the JS_RECEIVER/SPEC_OBJECT range and the
716 // NONCALLABLE_JS_OBJECT range.
717 JS_FUNCTION_PROXY_TYPE, // FIRST_JS_RECEIVER_TYPE, FIRST_JS_PROXY_TYPE
718 JS_PROXY_TYPE, // LAST_JS_PROXY_TYPE
719 JS_VALUE_TYPE, // FIRST_JS_OBJECT_TYPE
720 JS_MESSAGE_OBJECT_TYPE,
723 JS_CONTEXT_EXTENSION_OBJECT_TYPE,
724 JS_GENERATOR_OBJECT_TYPE,
726 JS_GLOBAL_OBJECT_TYPE,
727 JS_BUILTINS_OBJECT_TYPE,
728 JS_GLOBAL_PROXY_TYPE,
730 JS_ARRAY_BUFFER_TYPE,
735 JS_SET_ITERATOR_TYPE,
736 JS_MAP_ITERATOR_TYPE,
740 JS_FUNCTION_TYPE, // LAST_JS_OBJECT_TYPE, LAST_JS_RECEIVER_TYPE
744 LAST_TYPE = JS_FUNCTION_TYPE,
745 FIRST_NAME_TYPE = FIRST_TYPE,
746 LAST_NAME_TYPE = SYMBOL_TYPE,
747 FIRST_UNIQUE_NAME_TYPE = INTERNALIZED_STRING_TYPE,
748 LAST_UNIQUE_NAME_TYPE = SYMBOL_TYPE,
749 FIRST_NONSTRING_TYPE = SYMBOL_TYPE,
750 // Boundaries for testing for a SIMD type.
751 FIRST_SIMD_TYPE = FLOAT32X4_TYPE,
752 LAST_SIMD_TYPE = FLOAT32X4_TYPE,
753 // Boundaries for testing for a fixed typed array.
754 FIRST_FIXED_TYPED_ARRAY_TYPE = FIXED_INT8_ARRAY_TYPE,
755 LAST_FIXED_TYPED_ARRAY_TYPE = FIXED_UINT8_CLAMPED_ARRAY_TYPE,
756 // Boundary for promotion to old space.
757 LAST_DATA_TYPE = FILLER_TYPE,
758 // Boundary for objects represented as JSReceiver (i.e. JSObject or JSProxy).
759 // Note that there is no range for JSObject or JSProxy, since their subtypes
760 // are not continuous in this enum! The enum ranges instead reflect the
761 // external class names, where proxies are treated as either ordinary objects,
763 FIRST_JS_RECEIVER_TYPE = JS_FUNCTION_PROXY_TYPE,
764 LAST_JS_RECEIVER_TYPE = LAST_TYPE,
765 // Boundaries for testing the types represented as JSObject
766 FIRST_JS_OBJECT_TYPE = JS_VALUE_TYPE,
767 LAST_JS_OBJECT_TYPE = LAST_TYPE,
768 // Boundaries for testing the types represented as JSProxy
769 FIRST_JS_PROXY_TYPE = JS_FUNCTION_PROXY_TYPE,
770 LAST_JS_PROXY_TYPE = JS_PROXY_TYPE,
771 // Boundaries for testing whether the type is a JavaScript object.
772 FIRST_SPEC_OBJECT_TYPE = FIRST_JS_RECEIVER_TYPE,
773 LAST_SPEC_OBJECT_TYPE = LAST_JS_RECEIVER_TYPE,
774 // Boundaries for testing the types for which typeof is "object".
775 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_PROXY_TYPE,
776 LAST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_REGEXP_TYPE,
777 // Note that the types for which typeof is "function" are not continuous.
778 // Define this so that we can put assertions on discrete checks.
779 NUM_OF_CALLABLE_SPEC_OBJECT_TYPES = 2
782 STATIC_ASSERT(JS_OBJECT_TYPE == Internals::kJSObjectType);
783 STATIC_ASSERT(FIRST_NONSTRING_TYPE == Internals::kFirstNonstringType);
784 STATIC_ASSERT(ODDBALL_TYPE == Internals::kOddballType);
785 STATIC_ASSERT(FOREIGN_TYPE == Internals::kForeignType);
788 #define FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(V) \
789 V(FAST_ELEMENTS_SUB_TYPE) \
790 V(DICTIONARY_ELEMENTS_SUB_TYPE) \
791 V(FAST_PROPERTIES_SUB_TYPE) \
792 V(DICTIONARY_PROPERTIES_SUB_TYPE) \
793 V(MAP_CODE_CACHE_SUB_TYPE) \
794 V(SCOPE_INFO_SUB_TYPE) \
795 V(STRING_TABLE_SUB_TYPE) \
796 V(DESCRIPTOR_ARRAY_SUB_TYPE) \
797 V(TRANSITION_ARRAY_SUB_TYPE)
799 enum FixedArraySubInstanceType {
800 #define DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE(name) name,
801 FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE)
802 #undef DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE
803 LAST_FIXED_ARRAY_SUB_TYPE = TRANSITION_ARRAY_SUB_TYPE
816 #define DECL_BOOLEAN_ACCESSORS(name) \
817 inline bool name() const; \
818 inline void set_##name(bool value); \
821 #define DECL_ACCESSORS(name, type) \
822 inline type* name() const; \
823 inline void set_##name(type* value, \
824 WriteBarrierMode mode = UPDATE_WRITE_BARRIER); \
827 #define DECLARE_CAST(type) \
828 INLINE(static type* cast(Object* object)); \
829 INLINE(static const type* cast(const Object* object));
833 class AllocationSite;
834 class AllocationSiteCreationContext;
835 class AllocationSiteUsageContext;
838 class ElementsAccessor;
839 class FixedArrayBase;
840 class FunctionLiteral;
842 class JSBuiltinsObject;
843 class LayoutDescriptor;
844 class LookupIterator;
845 class ObjectHashTable;
848 class SafepointEntry;
849 class SharedFunctionInfo;
851 class TypeFeedbackInfo;
852 class TypeFeedbackVector;
855 // We cannot just say "class HeapType;" if it is created from a template... =8-?
856 template<class> class TypeImpl;
857 struct HeapTypeConfig;
858 typedef TypeImpl<HeapTypeConfig> HeapType;
861 // A template-ized version of the IsXXX functions.
862 template <class C> inline bool Is(Object* obj);
865 #define DECLARE_VERIFIER(Name) void Name##Verify();
867 #define DECLARE_VERIFIER(Name)
871 #define DECLARE_PRINTER(Name) void Name##Print(std::ostream& os); // NOLINT
873 #define DECLARE_PRINTER(Name)
877 #define OBJECT_TYPE_LIST(V) \
882 #define HEAP_OBJECT_TYPE_LIST(V) \
884 V(MutableHeapNumber) \
893 V(ExternalTwoByteString) \
894 V(ExternalOneByteString) \
895 V(SeqTwoByteString) \
896 V(SeqOneByteString) \
897 V(InternalizedString) \
900 V(FixedTypedArrayBase) \
903 V(FixedUint16Array) \
905 V(FixedUint32Array) \
907 V(FixedFloat32Array) \
908 V(FixedFloat64Array) \
909 V(FixedUint8ClampedArray) \
915 V(JSContextExtensionObject) \
916 V(JSGeneratorObject) \
918 V(LayoutDescriptor) \
922 V(TypeFeedbackVector) \
923 V(DeoptimizationInputData) \
924 V(DeoptimizationOutputData) \
928 V(FixedDoubleArray) \
932 V(ScriptContextTable) \
938 V(SharedFunctionInfo) \
947 V(JSArrayBufferView) \
956 V(JSWeakCollection) \
963 V(JSFunctionResultCache) \
964 V(NormalizedMapCache) \
965 V(CompilationCacheTable) \
966 V(CodeCacheHashTable) \
967 V(PolymorphicCodeCacheHashTable) \
972 V(JSBuiltinsObject) \
974 V(UndetectableObject) \
975 V(AccessCheckNeeded) \
981 V(WeakValueHashTable) \
984 // Object is the abstract superclass for all classes in the
986 // Object does not use any virtual functions to avoid the
987 // allocation of the C++ vtable.
988 // Since both Smi and HeapObject are subclasses of Object no
989 // data members can be present in Object.
993 bool IsObject() const { return true; }
995 #define IS_TYPE_FUNCTION_DECL(type_) INLINE(bool Is##type_() const);
996 OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
997 HEAP_OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
998 #undef IS_TYPE_FUNCTION_DECL
1000 // A non-keyed store is of the form a.x = foo or a["x"] = foo whereas
1001 // a keyed store is of the form a[expression] = foo.
1002 enum StoreFromKeyed {
1003 MAY_BE_STORE_FROM_KEYED,
1004 CERTAINLY_NOT_STORE_FROM_KEYED
1007 INLINE(bool IsFixedArrayBase() const);
1008 INLINE(bool IsExternal() const);
1009 INLINE(bool IsAccessorInfo() const);
1011 INLINE(bool IsStruct() const);
1012 #define DECLARE_STRUCT_PREDICATE(NAME, Name, name) \
1013 INLINE(bool Is##Name() const);
1014 STRUCT_LIST(DECLARE_STRUCT_PREDICATE)
1015 #undef DECLARE_STRUCT_PREDICATE
1017 INLINE(bool IsSpecObject()) const;
1018 INLINE(bool IsSpecFunction()) const;
1019 INLINE(bool IsTemplateInfo()) const;
1020 INLINE(bool IsNameDictionary() const);
1021 INLINE(bool IsGlobalDictionary() const);
1022 INLINE(bool IsSeededNumberDictionary() const);
1023 INLINE(bool IsUnseededNumberDictionary() const);
1024 INLINE(bool IsOrderedHashSet() const);
1025 INLINE(bool IsOrderedHashMap() const);
1026 bool IsCallable() const;
1027 static bool IsPromise(Handle<Object> object);
1030 INLINE(bool IsUndefined() const);
1031 INLINE(bool IsNull() const);
1032 INLINE(bool IsTheHole() const);
1033 INLINE(bool IsException() const);
1034 INLINE(bool IsUninitialized() const);
1035 INLINE(bool IsTrue() const);
1036 INLINE(bool IsFalse() const);
1037 INLINE(bool IsArgumentsMarker() const);
1039 // Filler objects (fillers and free space objects).
1040 INLINE(bool IsFiller() const);
1042 // Extract the number.
1043 inline double Number();
1044 INLINE(bool IsNaN() const);
1045 INLINE(bool IsMinusZero() const);
1046 bool ToInt32(int32_t* value);
1047 bool ToUint32(uint32_t* value);
1049 inline Representation OptimalRepresentation() {
1050 if (!FLAG_track_fields) return Representation::Tagged();
1052 return Representation::Smi();
1053 } else if (FLAG_track_double_fields && IsHeapNumber()) {
1054 return Representation::Double();
1055 } else if (FLAG_track_computed_fields && IsUninitialized()) {
1056 return Representation::None();
1057 } else if (FLAG_track_heap_object_fields) {
1058 DCHECK(IsHeapObject());
1059 return Representation::HeapObject();
1061 return Representation::Tagged();
1065 inline ElementsKind OptimalElementsKind() {
1066 if (IsSmi()) return FAST_SMI_ELEMENTS;
1067 if (IsNumber()) return FAST_DOUBLE_ELEMENTS;
1068 return FAST_ELEMENTS;
1071 inline bool FitsRepresentation(Representation representation) {
1072 if (FLAG_track_fields && representation.IsNone()) {
1074 } else if (FLAG_track_fields && representation.IsSmi()) {
1076 } else if (FLAG_track_double_fields && representation.IsDouble()) {
1077 return IsMutableHeapNumber() || IsNumber();
1078 } else if (FLAG_track_heap_object_fields && representation.IsHeapObject()) {
1079 return IsHeapObject();
1084 // Checks whether two valid primitive encodings of a property name resolve to
1085 // the same logical property. E.g., the smi 1, the string "1" and the double
1086 // 1 all refer to the same property, so this helper will return true.
1087 inline bool KeyEquals(Object* other);
1089 Handle<HeapType> OptimalType(Isolate* isolate, Representation representation);
1091 inline static Handle<Object> NewStorageFor(Isolate* isolate,
1092 Handle<Object> object,
1093 Representation representation);
1095 inline static Handle<Object> WrapForRead(Isolate* isolate,
1096 Handle<Object> object,
1097 Representation representation);
1099 // Returns true if the object is of the correct type to be used as a
1100 // implementation of a JSObject's elements.
1101 inline bool HasValidElements();
1103 inline bool HasSpecificClassOf(String* name);
1105 bool BooleanValue(); // ECMA-262 9.2.
1107 // Convert to a JSObject if needed.
1108 // native_context is used when creating wrapper object.
1109 static inline MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1110 Handle<Object> object);
1111 static MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1112 Handle<Object> object,
1113 Handle<Context> context);
1115 MUST_USE_RESULT static MaybeHandle<Object> GetProperty(
1116 LookupIterator* it, LanguageMode language_mode = SLOPPY);
1118 // Implementation of [[Put]], ECMA-262 5th edition, section 8.12.5.
1119 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1120 Handle<Object> object, Handle<Name> name, Handle<Object> value,
1121 LanguageMode language_mode,
1122 StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
1124 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1125 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1126 StoreFromKeyed store_mode);
1128 MUST_USE_RESULT static MaybeHandle<Object> SetSuperProperty(
1129 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1130 StoreFromKeyed store_mode);
1132 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1133 LookupIterator* it, LanguageMode language_mode);
1134 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1135 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1136 LanguageMode language_mode);
1137 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1138 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1139 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1140 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1141 Handle<Object> value, LanguageMode language_mode);
1142 MUST_USE_RESULT static MaybeHandle<Object> RedefineNonconfigurableProperty(
1143 Isolate* isolate, Handle<Object> name, Handle<Object> value,
1144 LanguageMode language_mode);
1145 MUST_USE_RESULT static MaybeHandle<Object> SetDataProperty(
1146 LookupIterator* it, Handle<Object> value);
1147 MUST_USE_RESULT static MaybeHandle<Object> AddDataProperty(
1148 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1149 LanguageMode language_mode, StoreFromKeyed store_mode);
1150 MUST_USE_RESULT static inline MaybeHandle<Object> GetPropertyOrElement(
1151 Handle<Object> object, Handle<Name> name,
1152 LanguageMode language_mode = SLOPPY);
1153 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1154 Isolate* isolate, Handle<Object> object, const char* key,
1155 LanguageMode language_mode = SLOPPY);
1156 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1157 Handle<Object> object, Handle<Name> name,
1158 LanguageMode language_mode = SLOPPY);
1160 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithAccessor(
1161 LookupIterator* it, LanguageMode language_mode);
1162 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithAccessor(
1163 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1165 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithDefinedGetter(
1166 Handle<Object> receiver,
1167 Handle<JSReceiver> getter);
1168 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithDefinedSetter(
1169 Handle<Object> receiver,
1170 Handle<JSReceiver> setter,
1171 Handle<Object> value);
1173 MUST_USE_RESULT static inline MaybeHandle<Object> GetElement(
1174 Isolate* isolate, Handle<Object> object, uint32_t index,
1175 LanguageMode language_mode = SLOPPY);
1177 MUST_USE_RESULT static inline MaybeHandle<Object> SetElement(
1178 Isolate* isolate, Handle<Object> object, uint32_t index,
1179 Handle<Object> value, LanguageMode language_mode);
1181 static inline Handle<Object> GetPrototypeSkipHiddenPrototypes(
1182 Isolate* isolate, Handle<Object> receiver);
1184 // Returns the permanent hash code associated with this object. May return
1185 // undefined if not yet created.
1188 // Returns undefined for JSObjects, but returns the hash code for simple
1189 // objects. This avoids a double lookup in the cases where we know we will
1190 // add the hash to the JSObject if it does not already exist.
1191 Object* GetSimpleHash();
1193 // Returns the permanent hash code associated with this object depending on
1194 // the actual object type. May create and store a hash code if needed and none
1196 static Handle<Smi> GetOrCreateHash(Isolate* isolate, Handle<Object> object);
1198 // Checks whether this object has the same value as the given one. This
1199 // function is implemented according to ES5, section 9.12 and can be used
1200 // to implement the Harmony "egal" function.
1201 bool SameValue(Object* other);
1203 // Checks whether this object has the same value as the given one.
1204 // +0 and -0 are treated equal. Everything else is the same as SameValue.
1205 // This function is implemented according to ES6, section 7.2.4 and is used
1206 // by ES6 Map and Set.
1207 bool SameValueZero(Object* other);
1209 // Tries to convert an object to an array length. Returns true and sets the
1210 // output parameter if it succeeds.
1211 inline bool ToArrayLength(uint32_t* index);
1213 // Tries to convert an object to an array index. Returns true and sets the
1214 // output parameter if it succeeds. Equivalent to ToArrayLength, but does not
1215 // allow kMaxUInt32.
1216 inline bool ToArrayIndex(uint32_t* index);
1218 // Returns true if this is a JSValue containing a string and the index is
1219 // < the length of the string. Used to implement [] on strings.
1220 inline bool IsStringObjectWithCharacterAt(uint32_t index);
1222 DECLARE_VERIFIER(Object)
1224 // Verify a pointer is a valid object pointer.
1225 static void VerifyPointer(Object* p);
1228 inline void VerifyApiCallResultType();
1230 // Prints this object without details.
1231 void ShortPrint(FILE* out = stdout);
1233 // Prints this object without details to a message accumulator.
1234 void ShortPrint(StringStream* accumulator);
1236 void ShortPrint(std::ostream& os); // NOLINT
1238 DECLARE_CAST(Object)
1240 // Layout description.
1241 static const int kHeaderSize = 0; // Object does not take up any space.
1244 // For our gdb macros, we should perhaps change these in the future.
1247 // Prints this object with details.
1248 void Print(std::ostream& os); // NOLINT
1250 void Print() { ShortPrint(); }
1251 void Print(std::ostream& os) { ShortPrint(os); } // NOLINT
1255 friend class LookupIterator;
1256 friend class PrototypeIterator;
1258 // Return the map of the root of object's prototype chain.
1259 Map* GetRootMap(Isolate* isolate);
1261 // Helper for SetProperty and SetSuperProperty.
1262 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyInternal(
1263 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1264 StoreFromKeyed store_mode, bool* found);
1266 DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
1271 explicit Brief(const Object* const v) : value(v) {}
1272 const Object* value;
1276 std::ostream& operator<<(std::ostream& os, const Brief& v);
1279 // Smi represents integer Numbers that can be stored in 31 bits.
1280 // Smis are immediate which means they are NOT allocated in the heap.
1281 // The this pointer has the following format: [31 bit signed int] 0
1282 // For long smis it has the following format:
1283 // [32 bit signed int] [31 bits zero padding] 0
1284 // Smi stands for small integer.
1285 class Smi: public Object {
1287 // Returns the integer value.
1288 inline int value() const;
1290 // Convert a value to a Smi object.
1291 static inline Smi* FromInt(int value);
1293 static inline Smi* FromIntptr(intptr_t value);
1295 // Returns whether value can be represented in a Smi.
1296 static inline bool IsValid(intptr_t value);
1300 // Dispatched behavior.
1301 void SmiPrint(std::ostream& os) const; // NOLINT
1302 DECLARE_VERIFIER(Smi)
1304 static const int kMinValue =
1305 (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1306 static const int kMaxValue = -(kMinValue + 1);
1309 DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1313 // Heap objects typically have a map pointer in their first word. However,
1314 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1315 // encoded in the first word. The class MapWord is an abstraction of the
1316 // value in a heap object's first word.
1317 class MapWord BASE_EMBEDDED {
1319 // Normal state: the map word contains a map pointer.
1321 // Create a map word from a map pointer.
1322 static inline MapWord FromMap(const Map* map);
1324 // View this map word as a map pointer.
1325 inline Map* ToMap();
1328 // Scavenge collection: the map word of live objects in the from space
1329 // contains a forwarding address (a heap object pointer in the to space).
1331 // True if this map word is a forwarding address for a scavenge
1332 // collection. Only valid during a scavenge collection (specifically,
1333 // when all map words are heap object pointers, i.e. not during a full GC).
1334 inline bool IsForwardingAddress();
1336 // Create a map word from a forwarding address.
1337 static inline MapWord FromForwardingAddress(HeapObject* object);
1339 // View this map word as a forwarding address.
1340 inline HeapObject* ToForwardingAddress();
1342 static inline MapWord FromRawValue(uintptr_t value) {
1343 return MapWord(value);
1346 inline uintptr_t ToRawValue() {
1351 // HeapObject calls the private constructor and directly reads the value.
1352 friend class HeapObject;
1354 explicit MapWord(uintptr_t value) : value_(value) {}
1360 // The content of an heap object (except for the map pointer). kTaggedValues
1361 // objects can contain both heap pointers and Smis, kMixedValues can contain
1362 // heap pointers, Smis, and raw values (e.g. doubles or strings), and kRawValues
1363 // objects can contain raw values and Smis.
1364 enum class HeapObjectContents { kTaggedValues, kMixedValues, kRawValues };
1367 // HeapObject is the superclass for all classes describing heap allocated
1369 class HeapObject: public Object {
1371 // [map]: Contains a map which contains the object's reflective
1373 inline Map* map() const;
1374 inline void set_map(Map* value);
1375 // The no-write-barrier version. This is OK if the object is white and in
1376 // new space, or if the value is an immortal immutable object, like the maps
1377 // of primitive (non-JS) objects like strings, heap numbers etc.
1378 inline void set_map_no_write_barrier(Map* value);
1380 // Get the map using acquire load.
1381 inline Map* synchronized_map();
1382 inline MapWord synchronized_map_word() const;
1384 // Set the map using release store
1385 inline void synchronized_set_map(Map* value);
1386 inline void synchronized_set_map_no_write_barrier(Map* value);
1387 inline void synchronized_set_map_word(MapWord map_word);
1389 // During garbage collection, the map word of a heap object does not
1390 // necessarily contain a map pointer.
1391 inline MapWord map_word() const;
1392 inline void set_map_word(MapWord map_word);
1394 // The Heap the object was allocated in. Used also to access Isolate.
1395 inline Heap* GetHeap() const;
1397 // Convenience method to get current isolate.
1398 inline Isolate* GetIsolate() const;
1400 // Converts an address to a HeapObject pointer.
1401 static inline HeapObject* FromAddress(Address address);
1403 // Returns the address of this HeapObject.
1404 inline Address address();
1406 // Iterates over pointers contained in the object (including the Map)
1407 void Iterate(ObjectVisitor* v);
1409 // Iterates over all pointers contained in the object except the
1410 // first map pointer. The object type is given in the first
1411 // parameter. This function does not access the map pointer in the
1412 // object, and so is safe to call while the map pointer is modified.
1413 void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1415 // Returns the heap object's size in bytes
1418 // Indicates what type of values this heap object may contain.
1419 inline HeapObjectContents ContentType();
1421 // Given a heap object's map pointer, returns the heap size in bytes
1422 // Useful when the map pointer field is used for other purposes.
1424 inline int SizeFromMap(Map* map);
1426 // Returns the field at offset in obj, as a read/write Object* reference.
1427 // Does no checking, and is safe to use during GC, while maps are invalid.
1428 // Does not invoke write barrier, so should only be assigned to
1429 // during marking GC.
1430 static inline Object** RawField(HeapObject* obj, int offset);
1432 // Adds the |code| object related to |name| to the code cache of this map. If
1433 // this map is a dictionary map that is shared, the map copied and installed
1435 static void UpdateMapCodeCache(Handle<HeapObject> object,
1439 DECLARE_CAST(HeapObject)
1441 // Return the write barrier mode for this. Callers of this function
1442 // must be able to present a reference to an DisallowHeapAllocation
1443 // object as a sign that they are not going to use this function
1444 // from code that allocates and thus invalidates the returned write
1446 inline WriteBarrierMode GetWriteBarrierMode(
1447 const DisallowHeapAllocation& promise);
1449 // Dispatched behavior.
1450 void HeapObjectShortPrint(std::ostream& os); // NOLINT
1452 void PrintHeader(std::ostream& os, const char* id); // NOLINT
1454 DECLARE_PRINTER(HeapObject)
1455 DECLARE_VERIFIER(HeapObject)
1457 inline void VerifyObjectField(int offset);
1458 inline void VerifySmiField(int offset);
1460 // Verify a pointer is a valid HeapObject pointer that points to object
1461 // areas in the heap.
1462 static void VerifyHeapPointer(Object* p);
1465 inline AllocationAlignment RequiredAlignment();
1467 // Layout description.
1468 // First field in a heap object is map.
1469 static const int kMapOffset = Object::kHeaderSize;
1470 static const int kHeaderSize = kMapOffset + kPointerSize;
1472 STATIC_ASSERT(kMapOffset == Internals::kHeapObjectMapOffset);
1475 // helpers for calling an ObjectVisitor to iterate over pointers in the
1476 // half-open range [start, end) specified as integer offsets
1477 inline void IteratePointers(ObjectVisitor* v, int start, int end);
1478 // as above, for the single element at "offset"
1479 inline void IteratePointer(ObjectVisitor* v, int offset);
1480 // as above, for the next code link of a code object.
1481 inline void IterateNextCodeLink(ObjectVisitor* v, int offset);
1484 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1488 // This class describes a body of an object of a fixed size
1489 // in which all pointer fields are located in the [start_offset, end_offset)
1491 template<int start_offset, int end_offset, int size>
1492 class FixedBodyDescriptor {
1494 static const int kStartOffset = start_offset;
1495 static const int kEndOffset = end_offset;
1496 static const int kSize = size;
1498 static inline void IterateBody(HeapObject* obj, ObjectVisitor* v);
1500 template<typename StaticVisitor>
1501 static inline void IterateBody(HeapObject* obj) {
1502 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1503 HeapObject::RawField(obj, end_offset));
1508 // This class describes a body of an object of a variable size
1509 // in which all pointer fields are located in the [start_offset, object_size)
1511 template<int start_offset>
1512 class FlexibleBodyDescriptor {
1514 static const int kStartOffset = start_offset;
1516 static inline void IterateBody(HeapObject* obj,
1520 template<typename StaticVisitor>
1521 static inline void IterateBody(HeapObject* obj, int object_size) {
1522 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1523 HeapObject::RawField(obj, object_size));
1528 // The HeapNumber class describes heap allocated numbers that cannot be
1529 // represented in a Smi (small integer)
1530 class HeapNumber: public HeapObject {
1532 // [value]: number value.
1533 inline double value() const;
1534 inline void set_value(double value);
1536 DECLARE_CAST(HeapNumber)
1538 // Dispatched behavior.
1539 bool HeapNumberBooleanValue();
1541 void HeapNumberPrint(std::ostream& os); // NOLINT
1542 DECLARE_VERIFIER(HeapNumber)
1544 inline int get_exponent();
1545 inline int get_sign();
1547 // Layout description.
1548 static const int kValueOffset = HeapObject::kHeaderSize;
1549 // IEEE doubles are two 32 bit words. The first is just mantissa, the second
1550 // is a mixture of sign, exponent and mantissa. The offsets of two 32 bit
1551 // words within double numbers are endian dependent and they are set
1553 #if defined(V8_TARGET_LITTLE_ENDIAN)
1554 static const int kMantissaOffset = kValueOffset;
1555 static const int kExponentOffset = kValueOffset + 4;
1556 #elif defined(V8_TARGET_BIG_ENDIAN)
1557 static const int kMantissaOffset = kValueOffset + 4;
1558 static const int kExponentOffset = kValueOffset;
1560 #error Unknown byte ordering
1563 static const int kSize = kValueOffset + kDoubleSize;
1564 static const uint32_t kSignMask = 0x80000000u;
1565 static const uint32_t kExponentMask = 0x7ff00000u;
1566 static const uint32_t kMantissaMask = 0xfffffu;
1567 static const int kMantissaBits = 52;
1568 static const int kExponentBits = 11;
1569 static const int kExponentBias = 1023;
1570 static const int kExponentShift = 20;
1571 static const int kInfinityOrNanExponent =
1572 (kExponentMask >> kExponentShift) - kExponentBias;
1573 static const int kMantissaBitsInTopWord = 20;
1574 static const int kNonMantissaBitsInTopWord = 12;
1577 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
1581 // The Float32x4 class describes heap allocated SIMD values holding 4 32-bit
1583 class Float32x4 : public HeapObject {
1585 inline float get_lane(int lane) const;
1586 inline void set_lane(int lane, float value);
1588 DECLARE_CAST(Float32x4)
1590 // Dispatched behavior.
1591 void Float32x4Print(std::ostream& os); // NOLINT
1592 DECLARE_VERIFIER(Float32x4)
1594 // Layout description.
1595 static const int kValueOffset = HeapObject::kHeaderSize;
1596 static const int kSize = kValueOffset + kSimd128Size;
1599 DISALLOW_IMPLICIT_CONSTRUCTORS(Float32x4);
1603 enum EnsureElementsMode {
1604 DONT_ALLOW_DOUBLE_ELEMENTS,
1605 ALLOW_COPIED_DOUBLE_ELEMENTS,
1606 ALLOW_CONVERTED_DOUBLE_ELEMENTS
1610 // Indicator for one component of an AccessorPair.
1611 enum AccessorComponent {
1617 // JSReceiver includes types on which properties can be defined, i.e.,
1618 // JSObject and JSProxy.
1619 class JSReceiver: public HeapObject {
1621 DECLARE_CAST(JSReceiver)
1623 // Implementation of [[HasProperty]], ECMA-262 5th edition, section 8.12.6.
1624 MUST_USE_RESULT static inline Maybe<bool> HasProperty(
1625 Handle<JSReceiver> object, Handle<Name> name);
1626 MUST_USE_RESULT static inline Maybe<bool> HasOwnProperty(Handle<JSReceiver>,
1628 MUST_USE_RESULT static inline Maybe<bool> HasElement(
1629 Handle<JSReceiver> object, uint32_t index);
1630 MUST_USE_RESULT static inline Maybe<bool> HasOwnElement(
1631 Handle<JSReceiver> object, uint32_t index);
1633 // Implementation of [[Delete]], ECMA-262 5th edition, section 8.12.7.
1634 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyOrElement(
1635 Handle<JSReceiver> object, Handle<Name> name,
1636 LanguageMode language_mode = SLOPPY);
1637 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1638 Handle<JSReceiver> object, Handle<Name> name,
1639 LanguageMode language_mode = SLOPPY);
1640 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1641 LookupIterator* it, LanguageMode language_mode);
1642 MUST_USE_RESULT static MaybeHandle<Object> DeleteElement(
1643 Handle<JSReceiver> object, uint32_t index,
1644 LanguageMode language_mode = SLOPPY);
1646 // Tests for the fast common case for property enumeration.
1647 bool IsSimpleEnum();
1649 // Returns the class name ([[Class]] property in the specification).
1650 String* class_name();
1652 // Returns the constructor name (the name (possibly, inferred name) of the
1653 // function that was used to instantiate the object).
1654 String* constructor_name();
1656 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetPropertyAttributes(
1657 Handle<JSReceiver> object, Handle<Name> name);
1658 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1659 GetOwnPropertyAttributes(Handle<JSReceiver> object, Handle<Name> name);
1661 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetElementAttributes(
1662 Handle<JSReceiver> object, uint32_t index);
1663 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1664 GetOwnElementAttributes(Handle<JSReceiver> object, uint32_t index);
1666 MUST_USE_RESULT static Maybe<PropertyAttributes> GetPropertyAttributes(
1667 LookupIterator* it);
1670 static Handle<Object> GetDataProperty(Handle<JSReceiver> object,
1672 static Handle<Object> GetDataProperty(LookupIterator* it);
1675 // Retrieves a permanent object identity hash code. The undefined value might
1676 // be returned in case no hash was created yet.
1677 inline Object* GetIdentityHash();
1679 // Retrieves a permanent object identity hash code. May create and store a
1680 // hash code if needed and none exists.
1681 inline static Handle<Smi> GetOrCreateIdentityHash(
1682 Handle<JSReceiver> object);
1684 enum KeyCollectionType { OWN_ONLY, INCLUDE_PROTOS };
1686 // Computes the enumerable keys for a JSObject. Used for implementing
1687 // "for (n in object) { }".
1688 MUST_USE_RESULT static MaybeHandle<FixedArray> GetKeys(
1689 Handle<JSReceiver> object,
1690 KeyCollectionType type);
1693 DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
1697 // The JSObject describes real heap allocated JavaScript objects with
1699 // Note that the map of JSObject changes during execution to enable inline
1701 class JSObject: public JSReceiver {
1703 // [properties]: Backing storage for properties.
1704 // properties is a FixedArray in the fast case and a Dictionary in the
1706 DECL_ACCESSORS(properties, FixedArray) // Get and set fast properties.
1707 inline void initialize_properties();
1708 inline bool HasFastProperties();
1709 // Gets slow properties for non-global objects.
1710 inline NameDictionary* property_dictionary();
1711 // Gets global object properties.
1712 inline GlobalDictionary* global_dictionary();
1714 // [elements]: The elements (properties with names that are integers).
1716 // Elements can be in two general modes: fast and slow. Each mode
1717 // corrensponds to a set of object representations of elements that
1718 // have something in common.
1720 // In the fast mode elements is a FixedArray and so each element can
1721 // be quickly accessed. This fact is used in the generated code. The
1722 // elements array can have one of three maps in this mode:
1723 // fixed_array_map, sloppy_arguments_elements_map or
1724 // fixed_cow_array_map (for copy-on-write arrays). In the latter case
1725 // the elements array may be shared by a few objects and so before
1726 // writing to any element the array must be copied. Use
1727 // EnsureWritableFastElements in this case.
1729 // In the slow mode the elements is either a NumberDictionary, a
1730 // FixedArray parameter map for a (sloppy) arguments object.
1731 DECL_ACCESSORS(elements, FixedArrayBase)
1732 inline void initialize_elements();
1733 static void ResetElements(Handle<JSObject> object);
1734 static inline void SetMapAndElements(Handle<JSObject> object,
1736 Handle<FixedArrayBase> elements);
1737 inline ElementsKind GetElementsKind();
1738 ElementsAccessor* GetElementsAccessor();
1739 // Returns true if an object has elements of FAST_SMI_ELEMENTS ElementsKind.
1740 inline bool HasFastSmiElements();
1741 // Returns true if an object has elements of FAST_ELEMENTS ElementsKind.
1742 inline bool HasFastObjectElements();
1743 // Returns true if an object has elements of FAST_ELEMENTS or
1744 // FAST_SMI_ONLY_ELEMENTS.
1745 inline bool HasFastSmiOrObjectElements();
1746 // Returns true if an object has any of the fast elements kinds.
1747 inline bool HasFastElements();
1748 // Returns true if an object has elements of FAST_DOUBLE_ELEMENTS
1750 inline bool HasFastDoubleElements();
1751 // Returns true if an object has elements of FAST_HOLEY_*_ELEMENTS
1753 inline bool HasFastHoleyElements();
1754 inline bool HasSloppyArgumentsElements();
1755 inline bool HasDictionaryElements();
1757 inline bool HasFixedTypedArrayElements();
1759 inline bool HasFixedUint8ClampedElements();
1760 inline bool HasFixedArrayElements();
1761 inline bool HasFixedInt8Elements();
1762 inline bool HasFixedUint8Elements();
1763 inline bool HasFixedInt16Elements();
1764 inline bool HasFixedUint16Elements();
1765 inline bool HasFixedInt32Elements();
1766 inline bool HasFixedUint32Elements();
1767 inline bool HasFixedFloat32Elements();
1768 inline bool HasFixedFloat64Elements();
1770 inline bool HasFastArgumentsElements();
1771 inline bool HasSlowArgumentsElements();
1772 inline SeededNumberDictionary* element_dictionary(); // Gets slow elements.
1774 // Requires: HasFastElements().
1775 static Handle<FixedArray> EnsureWritableFastElements(
1776 Handle<JSObject> object);
1778 // Collects elements starting at index 0.
1779 // Undefined values are placed after non-undefined values.
1780 // Returns the number of non-undefined values.
1781 static Handle<Object> PrepareElementsForSort(Handle<JSObject> object,
1783 // As PrepareElementsForSort, but only on objects where elements is
1784 // a dictionary, and it will stay a dictionary. Collates undefined and
1785 // unexisting elements below limit from position zero of the elements.
1786 static Handle<Object> PrepareSlowElementsForSort(Handle<JSObject> object,
1789 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithInterceptor(
1790 LookupIterator* it, Handle<Object> value);
1792 // SetLocalPropertyIgnoreAttributes converts callbacks to fields. We need to
1793 // grant an exemption to ExecutableAccessor callbacks in some cases.
1794 enum ExecutableAccessorInfoHandling { DEFAULT_HANDLING, DONT_FORCE_FIELD };
1796 MUST_USE_RESULT static MaybeHandle<Object> DefineOwnPropertyIgnoreAttributes(
1797 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1798 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1800 MUST_USE_RESULT static MaybeHandle<Object> SetOwnPropertyIgnoreAttributes(
1801 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1802 PropertyAttributes attributes,
1803 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1805 MUST_USE_RESULT static MaybeHandle<Object> SetOwnElementIgnoreAttributes(
1806 Handle<JSObject> object, uint32_t index, Handle<Object> value,
1807 PropertyAttributes attributes,
1808 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1810 // Equivalent to one of the above depending on whether |name| can be converted
1811 // to an array index.
1812 MUST_USE_RESULT static MaybeHandle<Object>
1813 DefinePropertyOrElementIgnoreAttributes(
1814 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1815 PropertyAttributes attributes = NONE,
1816 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1818 // Adds or reconfigures a property to attributes NONE. It will fail when it
1820 MUST_USE_RESULT static Maybe<bool> CreateDataProperty(LookupIterator* it,
1821 Handle<Object> value);
1823 static void AddProperty(Handle<JSObject> object, Handle<Name> name,
1824 Handle<Object> value, PropertyAttributes attributes);
1826 MUST_USE_RESULT static MaybeHandle<Object> AddDataElement(
1827 Handle<JSObject> receiver, uint32_t index, Handle<Object> value,
1828 PropertyAttributes attributes);
1830 // Extend the receiver with a single fast property appeared first in the
1831 // passed map. This also extends the property backing store if necessary.
1832 static void AllocateStorageForMap(Handle<JSObject> object, Handle<Map> map);
1834 // Migrates the given object to a map whose field representations are the
1835 // lowest upper bound of all known representations for that field.
1836 static void MigrateInstance(Handle<JSObject> instance);
1838 // Migrates the given object only if the target map is already available,
1839 // or returns false if such a map is not yet available.
1840 static bool TryMigrateInstance(Handle<JSObject> instance);
1842 // Sets the property value in a normalized object given (key, value, details).
1843 // Handles the special representation of JS global objects.
1844 static void SetNormalizedProperty(Handle<JSObject> object, Handle<Name> name,
1845 Handle<Object> value,
1846 PropertyDetails details);
1847 static void SetDictionaryElement(Handle<JSObject> object, uint32_t index,
1848 Handle<Object> value,
1849 PropertyAttributes attributes);
1850 static void SetDictionaryArgumentsElement(Handle<JSObject> object,
1852 Handle<Object> value,
1853 PropertyAttributes attributes);
1855 static void OptimizeAsPrototype(Handle<JSObject> object,
1856 PrototypeOptimizationMode mode);
1857 static void ReoptimizeIfPrototype(Handle<JSObject> object);
1858 static void LazyRegisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1859 static bool RegisterPrototypeUserIfNotRegistered(Handle<JSObject> prototype,
1860 Handle<HeapObject> user,
1862 static bool UnregisterPrototypeUser(Handle<JSObject> prototype,
1863 Handle<HeapObject> user);
1864 static void InvalidatePrototypeChains(Map* map);
1866 // Retrieve interceptors.
1867 InterceptorInfo* GetNamedInterceptor();
1868 InterceptorInfo* GetIndexedInterceptor();
1870 // Used from JSReceiver.
1871 MUST_USE_RESULT static Maybe<PropertyAttributes>
1872 GetPropertyAttributesWithInterceptor(LookupIterator* it);
1873 MUST_USE_RESULT static Maybe<PropertyAttributes>
1874 GetPropertyAttributesWithFailedAccessCheck(LookupIterator* it);
1876 // Retrieves an AccessorPair property from the given object. Might return
1877 // undefined if the property doesn't exist or is of a different kind.
1878 MUST_USE_RESULT static MaybeHandle<Object> GetAccessor(
1879 Handle<JSObject> object,
1881 AccessorComponent component);
1883 // Defines an AccessorPair property on the given object.
1884 // TODO(mstarzinger): Rename to SetAccessor().
1885 static MaybeHandle<Object> DefineAccessor(Handle<JSObject> object,
1887 Handle<Object> getter,
1888 Handle<Object> setter,
1889 PropertyAttributes attributes);
1891 // Defines an AccessorInfo property on the given object.
1892 MUST_USE_RESULT static MaybeHandle<Object> SetAccessor(
1893 Handle<JSObject> object,
1894 Handle<AccessorInfo> info);
1896 // The result must be checked first for exceptions. If there's no exception,
1897 // the output parameter |done| indicates whether the interceptor has a result
1899 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithInterceptor(
1900 LookupIterator* it, bool* done);
1902 // Accessors for hidden properties object.
1904 // Hidden properties are not own properties of the object itself.
1905 // Instead they are stored in an auxiliary structure kept as an own
1906 // property with a special name Heap::hidden_string(). But if the
1907 // receiver is a JSGlobalProxy then the auxiliary object is a property
1908 // of its prototype, and if it's a detached proxy, then you can't have
1909 // hidden properties.
1911 // Sets a hidden property on this object. Returns this object if successful,
1912 // undefined if called on a detached proxy.
1913 static Handle<Object> SetHiddenProperty(Handle<JSObject> object,
1915 Handle<Object> value);
1916 // Gets the value of a hidden property with the given key. Returns the hole
1917 // if the property doesn't exist (or if called on a detached proxy),
1918 // otherwise returns the value set for the key.
1919 Object* GetHiddenProperty(Handle<Name> key);
1920 // Deletes a hidden property. Deleting a non-existing property is
1921 // considered successful.
1922 static void DeleteHiddenProperty(Handle<JSObject> object,
1924 // Returns true if the object has a property with the hidden string as name.
1925 static bool HasHiddenProperties(Handle<JSObject> object);
1927 static void SetIdentityHash(Handle<JSObject> object, Handle<Smi> hash);
1929 static void ValidateElements(Handle<JSObject> object);
1931 // Makes sure that this object can contain HeapObject as elements.
1932 static inline void EnsureCanContainHeapObjectElements(Handle<JSObject> obj);
1934 // Makes sure that this object can contain the specified elements.
1935 static inline void EnsureCanContainElements(
1936 Handle<JSObject> object,
1939 EnsureElementsMode mode);
1940 static inline void EnsureCanContainElements(
1941 Handle<JSObject> object,
1942 Handle<FixedArrayBase> elements,
1944 EnsureElementsMode mode);
1945 static void EnsureCanContainElements(
1946 Handle<JSObject> object,
1947 Arguments* arguments,
1950 EnsureElementsMode mode);
1952 // Would we convert a fast elements array to dictionary mode given
1953 // an access at key?
1954 bool WouldConvertToSlowElements(uint32_t index);
1956 // Computes the new capacity when expanding the elements of a JSObject.
1957 static uint32_t NewElementsCapacity(uint32_t old_capacity) {
1958 // (old_capacity + 50%) + 16
1959 return old_capacity + (old_capacity >> 1) + 16;
1962 // These methods do not perform access checks!
1963 static void UpdateAllocationSite(Handle<JSObject> object,
1964 ElementsKind to_kind);
1966 // Lookup interceptors are used for handling properties controlled by host
1968 inline bool HasNamedInterceptor();
1969 inline bool HasIndexedInterceptor();
1971 // Computes the enumerable keys from interceptors. Used for debug mirrors and
1972 // by JSReceiver::GetKeys.
1973 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForNamedInterceptor(
1974 Handle<JSObject> object,
1975 Handle<JSReceiver> receiver);
1976 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForIndexedInterceptor(
1977 Handle<JSObject> object,
1978 Handle<JSReceiver> receiver);
1980 // Support functions for v8 api (needed for correct interceptor behavior).
1981 MUST_USE_RESULT static Maybe<bool> HasRealNamedProperty(
1982 Handle<JSObject> object, Handle<Name> name);
1983 MUST_USE_RESULT static Maybe<bool> HasRealElementProperty(
1984 Handle<JSObject> object, uint32_t index);
1985 MUST_USE_RESULT static Maybe<bool> HasRealNamedCallbackProperty(
1986 Handle<JSObject> object, Handle<Name> name);
1988 // Get the header size for a JSObject. Used to compute the index of
1989 // internal fields as well as the number of internal fields.
1990 inline int GetHeaderSize();
1992 inline int GetInternalFieldCount();
1993 inline int GetInternalFieldOffset(int index);
1994 inline Object* GetInternalField(int index);
1995 inline void SetInternalField(int index, Object* value);
1996 inline void SetInternalField(int index, Smi* value);
1998 // Returns the number of properties on this object filtering out properties
1999 // with the specified attributes (ignoring interceptors).
2000 int NumberOfOwnProperties(PropertyAttributes filter = NONE);
2001 // Fill in details for properties into storage starting at the specified
2002 // index. Returns the number of properties added.
2003 int GetOwnPropertyNames(FixedArray* storage, int index,
2004 PropertyAttributes filter = NONE);
2006 // Returns the number of properties on this object filtering out properties
2007 // with the specified attributes (ignoring interceptors).
2008 int NumberOfOwnElements(PropertyAttributes filter);
2009 // Returns the number of enumerable elements (ignoring interceptors).
2010 int NumberOfEnumElements();
2011 // Returns the number of elements on this object filtering out elements
2012 // with the specified attributes (ignoring interceptors).
2013 int GetOwnElementKeys(FixedArray* storage, PropertyAttributes filter);
2014 // Count and fill in the enumerable elements into storage.
2015 // (storage->length() == NumberOfEnumElements()).
2016 // If storage is NULL, will count the elements without adding
2017 // them to any storage.
2018 // Returns the number of enumerable elements.
2019 int GetEnumElementKeys(FixedArray* storage);
2021 static Handle<FixedArray> GetEnumPropertyKeys(Handle<JSObject> object,
2024 // Returns a new map with all transitions dropped from the object's current
2025 // map and the ElementsKind set.
2026 static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
2027 ElementsKind to_kind);
2028 static void TransitionElementsKind(Handle<JSObject> object,
2029 ElementsKind to_kind);
2031 // Always use this to migrate an object to a new map.
2032 // |expected_additional_properties| is only used for fast-to-slow transitions
2033 // and ignored otherwise.
2034 static void MigrateToMap(Handle<JSObject> object, Handle<Map> new_map,
2035 int expected_additional_properties = 0);
2037 // Convert the object to use the canonical dictionary
2038 // representation. If the object is expected to have additional properties
2039 // added this number can be indicated to have the backing store allocated to
2040 // an initial capacity for holding these properties.
2041 static void NormalizeProperties(Handle<JSObject> object,
2042 PropertyNormalizationMode mode,
2043 int expected_additional_properties,
2044 const char* reason);
2046 // Convert and update the elements backing store to be a
2047 // SeededNumberDictionary dictionary. Returns the backing after conversion.
2048 static Handle<SeededNumberDictionary> NormalizeElements(
2049 Handle<JSObject> object);
2051 void RequireSlowElements(SeededNumberDictionary* dictionary);
2053 // Transform slow named properties to fast variants.
2054 static void MigrateSlowToFast(Handle<JSObject> object,
2055 int unused_property_fields, const char* reason);
2057 inline bool IsUnboxedDoubleField(FieldIndex index);
2059 // Access fast-case object properties at index.
2060 static Handle<Object> FastPropertyAt(Handle<JSObject> object,
2061 Representation representation,
2063 inline Object* RawFastPropertyAt(FieldIndex index);
2064 inline double RawFastDoublePropertyAt(FieldIndex index);
2066 inline void FastPropertyAtPut(FieldIndex index, Object* value);
2067 inline void RawFastPropertyAtPut(FieldIndex index, Object* value);
2068 inline void RawFastDoublePropertyAtPut(FieldIndex index, double value);
2069 inline void WriteToField(int descriptor, Object* value);
2071 // Access to in object properties.
2072 inline int GetInObjectPropertyOffset(int index);
2073 inline Object* InObjectPropertyAt(int index);
2074 inline Object* InObjectPropertyAtPut(int index,
2076 WriteBarrierMode mode
2077 = UPDATE_WRITE_BARRIER);
2079 // Set the object's prototype (only JSReceiver and null are allowed values).
2080 MUST_USE_RESULT static MaybeHandle<Object> SetPrototype(
2081 Handle<JSObject> object, Handle<Object> value, bool from_javascript);
2083 // Initializes the body after properties slot, properties slot is
2084 // initialized by set_properties. Fill the pre-allocated fields with
2085 // pre_allocated_value and the rest with filler_value.
2086 // Note: this call does not update write barrier, the caller is responsible
2087 // to ensure that |filler_value| can be collected without WB here.
2088 inline void InitializeBody(Map* map,
2089 Object* pre_allocated_value,
2090 Object* filler_value);
2092 // Check whether this object references another object
2093 bool ReferencesObject(Object* obj);
2095 // Disalow further properties to be added to the oject.
2096 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensions(
2097 Handle<JSObject> object);
2099 bool IsExtensible();
2102 MUST_USE_RESULT static MaybeHandle<Object> Seal(Handle<JSObject> object);
2104 // ES5 Object.freeze
2105 MUST_USE_RESULT static MaybeHandle<Object> Freeze(Handle<JSObject> object);
2107 // Called the first time an object is observed with ES7 Object.observe.
2108 static void SetObserved(Handle<JSObject> object);
2111 enum DeepCopyHints { kNoHints = 0, kObjectIsShallow = 1 };
2113 MUST_USE_RESULT static MaybeHandle<JSObject> DeepCopy(
2114 Handle<JSObject> object,
2115 AllocationSiteUsageContext* site_context,
2116 DeepCopyHints hints = kNoHints);
2117 MUST_USE_RESULT static MaybeHandle<JSObject> DeepWalk(
2118 Handle<JSObject> object,
2119 AllocationSiteCreationContext* site_context);
2121 DECLARE_CAST(JSObject)
2123 // Dispatched behavior.
2124 void JSObjectShortPrint(StringStream* accumulator);
2125 DECLARE_PRINTER(JSObject)
2126 DECLARE_VERIFIER(JSObject)
2128 void PrintProperties(std::ostream& os); // NOLINT
2129 void PrintElements(std::ostream& os); // NOLINT
2131 #if defined(DEBUG) || defined(OBJECT_PRINT)
2132 void PrintTransitions(std::ostream& os); // NOLINT
2135 static void PrintElementsTransition(
2136 FILE* file, Handle<JSObject> object,
2137 ElementsKind from_kind, Handle<FixedArrayBase> from_elements,
2138 ElementsKind to_kind, Handle<FixedArrayBase> to_elements);
2140 void PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map);
2143 // Structure for collecting spill information about JSObjects.
2144 class SpillInformation {
2148 int number_of_objects_;
2149 int number_of_objects_with_fast_properties_;
2150 int number_of_objects_with_fast_elements_;
2151 int number_of_fast_used_fields_;
2152 int number_of_fast_unused_fields_;
2153 int number_of_slow_used_properties_;
2154 int number_of_slow_unused_properties_;
2155 int number_of_fast_used_elements_;
2156 int number_of_fast_unused_elements_;
2157 int number_of_slow_used_elements_;
2158 int number_of_slow_unused_elements_;
2161 void IncrementSpillStatistics(SpillInformation* info);
2165 // If a GC was caused while constructing this object, the elements pointer
2166 // may point to a one pointer filler map. The object won't be rooted, but
2167 // our heap verification code could stumble across it.
2168 bool ElementsAreSafeToExamine();
2171 Object* SlowReverseLookup(Object* value);
2173 // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2174 // Also maximal value of JSArray's length property.
2175 static const uint32_t kMaxElementCount = 0xffffffffu;
2177 // Constants for heuristics controlling conversion of fast elements
2178 // to slow elements.
2180 // Maximal gap that can be introduced by adding an element beyond
2181 // the current elements length.
2182 static const uint32_t kMaxGap = 1024;
2184 // Maximal length of fast elements array that won't be checked for
2185 // being dense enough on expansion.
2186 static const int kMaxUncheckedFastElementsLength = 5000;
2188 // Same as above but for old arrays. This limit is more strict. We
2189 // don't want to be wasteful with long lived objects.
2190 static const int kMaxUncheckedOldFastElementsLength = 500;
2192 // Note that Page::kMaxRegularHeapObjectSize puts a limit on
2193 // permissible values (see the DCHECK in heap.cc).
2194 static const int kInitialMaxFastElementArray = 100000;
2196 // This constant applies only to the initial map of "global.Object" and
2197 // not to arbitrary other JSObject maps.
2198 static const int kInitialGlobalObjectUnusedPropertiesCount = 4;
2200 static const int kMaxInstanceSize = 255 * kPointerSize;
2201 // When extending the backing storage for property values, we increase
2202 // its size by more than the 1 entry necessary, so sequentially adding fields
2203 // to the same object requires fewer allocations and copies.
2204 static const int kFieldsAdded = 3;
2206 // Layout description.
2207 static const int kPropertiesOffset = HeapObject::kHeaderSize;
2208 static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2209 static const int kHeaderSize = kElementsOffset + kPointerSize;
2211 STATIC_ASSERT(kHeaderSize == Internals::kJSObjectHeaderSize);
2213 class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2215 static inline int SizeOf(Map* map, HeapObject* object);
2218 Context* GetCreationContext();
2220 // Enqueue change record for Object.observe. May cause GC.
2221 MUST_USE_RESULT static MaybeHandle<Object> EnqueueChangeRecord(
2222 Handle<JSObject> object, const char* type, Handle<Name> name,
2223 Handle<Object> old_value);
2225 // Gets the number of currently used elements.
2226 int GetFastElementsUsage();
2228 // Deletes an existing named property in a normalized object.
2229 static void DeleteNormalizedProperty(Handle<JSObject> object,
2230 Handle<Name> name, int entry);
2232 static bool AllCanRead(LookupIterator* it);
2233 static bool AllCanWrite(LookupIterator* it);
2236 friend class JSReceiver;
2237 friend class Object;
2239 static void MigrateFastToFast(Handle<JSObject> object, Handle<Map> new_map);
2240 static void MigrateFastToSlow(Handle<JSObject> object,
2241 Handle<Map> new_map,
2242 int expected_additional_properties);
2244 // Used from Object::GetProperty().
2245 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithFailedAccessCheck(
2246 LookupIterator* it);
2248 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithFailedAccessCheck(
2249 LookupIterator* it, Handle<Object> value);
2251 // Add a property to a slow-case object.
2252 static void AddSlowProperty(Handle<JSObject> object,
2254 Handle<Object> value,
2255 PropertyAttributes attributes);
2257 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithInterceptor(
2258 LookupIterator* it);
2260 bool ReferencesObjectFromElements(FixedArray* elements,
2264 // Return the hash table backing store or the inline stored identity hash,
2265 // whatever is found.
2266 MUST_USE_RESULT Object* GetHiddenPropertiesHashTable();
2268 // Return the hash table backing store for hidden properties. If there is no
2269 // backing store, allocate one.
2270 static Handle<ObjectHashTable> GetOrCreateHiddenPropertiesHashtable(
2271 Handle<JSObject> object);
2273 // Set the hidden property backing store to either a hash table or
2274 // the inline-stored identity hash.
2275 static Handle<Object> SetHiddenPropertiesHashTable(
2276 Handle<JSObject> object,
2277 Handle<Object> value);
2279 MUST_USE_RESULT Object* GetIdentityHash();
2281 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSObject> object);
2283 static Handle<SeededNumberDictionary> GetNormalizedElementDictionary(
2284 Handle<JSObject> object, Handle<FixedArrayBase> elements);
2286 // Helper for fast versions of preventExtensions, seal, and freeze.
2287 // attrs is one of NONE, SEALED, or FROZEN (depending on the operation).
2288 template <PropertyAttributes attrs>
2289 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensionsWithTransition(
2290 Handle<JSObject> object);
2292 DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
2296 // Common superclass for FixedArrays that allow implementations to share
2297 // common accessors and some code paths.
2298 class FixedArrayBase: public HeapObject {
2300 // [length]: length of the array.
2301 inline int length() const;
2302 inline void set_length(int value);
2304 // Get and set the length using acquire loads and release stores.
2305 inline int synchronized_length() const;
2306 inline void synchronized_set_length(int value);
2308 DECLARE_CAST(FixedArrayBase)
2310 // Layout description.
2311 // Length is smi tagged when it is stored.
2312 static const int kLengthOffset = HeapObject::kHeaderSize;
2313 static const int kHeaderSize = kLengthOffset + kPointerSize;
2317 class FixedDoubleArray;
2318 class IncrementalMarking;
2321 // FixedArray describes fixed-sized arrays with element type Object*.
2322 class FixedArray: public FixedArrayBase {
2324 // Setter and getter for elements.
2325 inline Object* get(int index) const;
2326 void SetValue(uint32_t index, Object* value);
2327 static inline Handle<Object> get(Handle<FixedArray> array, int index);
2328 // Setter that uses write barrier.
2329 inline void set(int index, Object* value);
2330 inline bool is_the_hole(int index);
2332 // Setter that doesn't need write barrier.
2333 inline void set(int index, Smi* value);
2334 // Setter with explicit barrier mode.
2335 inline void set(int index, Object* value, WriteBarrierMode mode);
2337 // Setters for frequently used oddballs located in old space.
2338 inline void set_undefined(int index);
2339 inline void set_null(int index);
2340 inline void set_the_hole(int index);
2342 inline Object** GetFirstElementAddress();
2343 inline bool ContainsOnlySmisOrHoles();
2345 // Gives access to raw memory which stores the array's data.
2346 inline Object** data_start();
2348 inline void FillWithHoles(int from, int to);
2350 // Shrink length and insert filler objects.
2351 void Shrink(int length);
2354 static Handle<FixedArray> CopySize(Handle<FixedArray> array,
2356 PretenureFlag pretenure = NOT_TENURED);
2358 enum KeyFilter { ALL_KEYS, NON_SYMBOL_KEYS };
2360 // Add the elements of a JSArray to this FixedArray.
2361 MUST_USE_RESULT static MaybeHandle<FixedArray> AddKeysFromArrayLike(
2362 Handle<FixedArray> content, Handle<JSObject> array,
2363 KeyFilter filter = ALL_KEYS);
2365 // Computes the union of keys and return the result.
2366 // Used for implementing "for (n in object) { }"
2367 MUST_USE_RESULT static MaybeHandle<FixedArray> UnionOfKeys(
2368 Handle<FixedArray> first,
2369 Handle<FixedArray> second);
2371 // Copy a sub array from the receiver to dest.
2372 void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
2374 // Garbage collection support.
2375 static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
2377 // Code Generation support.
2378 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2380 // Garbage collection support.
2381 Object** RawFieldOfElementAt(int index) {
2382 return HeapObject::RawField(this, OffsetOfElementAt(index));
2385 DECLARE_CAST(FixedArray)
2387 // Maximal allowed size, in bytes, of a single FixedArray.
2388 // Prevents overflowing size computations, as well as extreme memory
2390 static const int kMaxSize = 128 * MB * kPointerSize;
2391 // Maximally allowed length of a FixedArray.
2392 static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
2394 // Dispatched behavior.
2395 DECLARE_PRINTER(FixedArray)
2396 DECLARE_VERIFIER(FixedArray)
2398 // Checks if two FixedArrays have identical contents.
2399 bool IsEqualTo(FixedArray* other);
2402 // Swap two elements in a pair of arrays. If this array and the
2403 // numbers array are the same object, the elements are only swapped
2405 void SwapPairs(FixedArray* numbers, int i, int j);
2407 // Sort prefix of this array and the numbers array as pairs wrt. the
2408 // numbers. If the numbers array and the this array are the same
2409 // object, the prefix of this array is sorted.
2410 void SortPairs(FixedArray* numbers, uint32_t len);
2412 class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
2414 static inline int SizeOf(Map* map, HeapObject* object) {
2416 reinterpret_cast<FixedArray*>(object)->synchronized_length());
2421 // Set operation on FixedArray without using write barriers. Can
2422 // only be used for storing old space objects or smis.
2423 static inline void NoWriteBarrierSet(FixedArray* array,
2427 // Set operation on FixedArray without incremental write barrier. Can
2428 // only be used if the object is guaranteed to be white (whiteness witness
2430 static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
2435 STATIC_ASSERT(kHeaderSize == Internals::kFixedArrayHeaderSize);
2437 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
2441 // FixedDoubleArray describes fixed-sized arrays with element type double.
2442 class FixedDoubleArray: public FixedArrayBase {
2444 // Setter and getter for elements.
2445 inline double get_scalar(int index);
2446 inline uint64_t get_representation(int index);
2447 static inline Handle<Object> get(Handle<FixedDoubleArray> array, int index);
2448 // This accessor has to get a Number as |value|.
2449 void SetValue(uint32_t index, Object* value);
2450 inline void set(int index, double value);
2451 inline void set_the_hole(int index);
2453 // Checking for the hole.
2454 inline bool is_the_hole(int index);
2456 // Garbage collection support.
2457 inline static int SizeFor(int length) {
2458 return kHeaderSize + length * kDoubleSize;
2461 // Gives access to raw memory which stores the array's data.
2462 inline double* data_start();
2464 inline void FillWithHoles(int from, int to);
2466 // Code Generation support.
2467 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2469 DECLARE_CAST(FixedDoubleArray)
2471 // Maximal allowed size, in bytes, of a single FixedDoubleArray.
2472 // Prevents overflowing size computations, as well as extreme memory
2474 static const int kMaxSize = 512 * MB;
2475 // Maximally allowed length of a FixedArray.
2476 static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
2478 // Dispatched behavior.
2479 DECLARE_PRINTER(FixedDoubleArray)
2480 DECLARE_VERIFIER(FixedDoubleArray)
2483 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
2487 class WeakFixedArray : public FixedArray {
2489 enum SearchForDuplicates { kAlwaysAdd, kAddIfNotFound };
2491 // If |maybe_array| is not a WeakFixedArray, a fresh one will be allocated.
2492 static Handle<WeakFixedArray> Add(
2493 Handle<Object> maybe_array, Handle<HeapObject> value,
2494 SearchForDuplicates search_for_duplicates = kAlwaysAdd,
2495 bool* was_present = NULL);
2497 // Returns true if an entry was found and removed.
2498 bool Remove(Handle<HeapObject> value);
2502 inline Object* Get(int index) const;
2503 inline void Clear(int index);
2504 inline int Length() const;
2506 inline bool IsEmptySlot(int index) const;
2507 static Object* Empty() { return Smi::FromInt(0); }
2509 DECLARE_CAST(WeakFixedArray)
2512 static const int kLastUsedIndexIndex = 0;
2513 static const int kFirstIndex = 1;
2515 static Handle<WeakFixedArray> Allocate(
2516 Isolate* isolate, int size, Handle<WeakFixedArray> initialize_from);
2518 static void Set(Handle<WeakFixedArray> array, int index,
2519 Handle<HeapObject> value);
2520 inline void clear(int index);
2522 inline int last_used_index() const;
2523 inline void set_last_used_index(int index);
2525 // Disallow inherited setters.
2526 void set(int index, Smi* value);
2527 void set(int index, Object* value);
2528 void set(int index, Object* value, WriteBarrierMode mode);
2529 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakFixedArray);
2533 // Generic array grows dynamically with O(1) amortized insertion.
2534 class ArrayList : public FixedArray {
2538 // Use this if GC can delete elements from the array.
2539 kReloadLengthAfterAllocation,
2541 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj,
2542 AddMode mode = kNone);
2543 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj1,
2544 Handle<Object> obj2, AddMode = kNone);
2545 inline int Length();
2546 inline void SetLength(int length);
2547 inline Object* Get(int index);
2548 inline Object** Slot(int index);
2549 inline void Set(int index, Object* obj);
2550 inline void Clear(int index, Object* undefined);
2551 DECLARE_CAST(ArrayList)
2554 static Handle<ArrayList> EnsureSpace(Handle<ArrayList> array, int length);
2555 static const int kLengthIndex = 0;
2556 static const int kFirstIndex = 1;
2557 DISALLOW_IMPLICIT_CONSTRUCTORS(ArrayList);
2561 // DescriptorArrays are fixed arrays used to hold instance descriptors.
2562 // The format of the these objects is:
2563 // [0]: Number of descriptors
2564 // [1]: Either Smi(0) if uninitialized, or a pointer to small fixed array:
2565 // [0]: pointer to fixed array with enum cache
2566 // [1]: either Smi(0) or pointer to fixed array with indices
2568 // [2 + number of descriptors * kDescriptorSize]: start of slack
2569 class DescriptorArray: public FixedArray {
2571 // Returns true for both shared empty_descriptor_array and for smis, which the
2572 // map uses to encode additional bit fields when the descriptor array is not
2574 inline bool IsEmpty();
2576 // Returns the number of descriptors in the array.
2577 int number_of_descriptors() {
2578 DCHECK(length() >= kFirstIndex || IsEmpty());
2580 return len == 0 ? 0 : Smi::cast(get(kDescriptorLengthIndex))->value();
2583 int number_of_descriptors_storage() {
2585 return len == 0 ? 0 : (len - kFirstIndex) / kDescriptorSize;
2588 int NumberOfSlackDescriptors() {
2589 return number_of_descriptors_storage() - number_of_descriptors();
2592 inline void SetNumberOfDescriptors(int number_of_descriptors);
2593 inline int number_of_entries() { return number_of_descriptors(); }
2595 bool HasEnumCache() {
2596 return !IsEmpty() && !get(kEnumCacheIndex)->IsSmi();
2599 void CopyEnumCacheFrom(DescriptorArray* array) {
2600 set(kEnumCacheIndex, array->get(kEnumCacheIndex));
2603 FixedArray* GetEnumCache() {
2604 DCHECK(HasEnumCache());
2605 FixedArray* bridge = FixedArray::cast(get(kEnumCacheIndex));
2606 return FixedArray::cast(bridge->get(kEnumCacheBridgeCacheIndex));
2609 bool HasEnumIndicesCache() {
2610 if (IsEmpty()) return false;
2611 Object* object = get(kEnumCacheIndex);
2612 if (object->IsSmi()) return false;
2613 FixedArray* bridge = FixedArray::cast(object);
2614 return !bridge->get(kEnumCacheBridgeIndicesCacheIndex)->IsSmi();
2617 FixedArray* GetEnumIndicesCache() {
2618 DCHECK(HasEnumIndicesCache());
2619 FixedArray* bridge = FixedArray::cast(get(kEnumCacheIndex));
2620 return FixedArray::cast(bridge->get(kEnumCacheBridgeIndicesCacheIndex));
2623 Object** GetEnumCacheSlot() {
2624 DCHECK(HasEnumCache());
2625 return HeapObject::RawField(reinterpret_cast<HeapObject*>(this),
2629 void ClearEnumCache();
2631 // Initialize or change the enum cache,
2632 // using the supplied storage for the small "bridge".
2633 void SetEnumCache(FixedArray* bridge_storage,
2634 FixedArray* new_cache,
2635 Object* new_index_cache);
2637 bool CanHoldValue(int descriptor, Object* value);
2639 // Accessors for fetching instance descriptor at descriptor number.
2640 inline Name* GetKey(int descriptor_number);
2641 inline Object** GetKeySlot(int descriptor_number);
2642 inline Object* GetValue(int descriptor_number);
2643 inline void SetValue(int descriptor_number, Object* value);
2644 inline Object** GetValueSlot(int descriptor_number);
2645 static inline int GetValueOffset(int descriptor_number);
2646 inline Object** GetDescriptorStartSlot(int descriptor_number);
2647 inline Object** GetDescriptorEndSlot(int descriptor_number);
2648 inline PropertyDetails GetDetails(int descriptor_number);
2649 inline PropertyType GetType(int descriptor_number);
2650 inline int GetFieldIndex(int descriptor_number);
2651 inline HeapType* GetFieldType(int descriptor_number);
2652 inline Object* GetConstant(int descriptor_number);
2653 inline Object* GetCallbacksObject(int descriptor_number);
2654 inline AccessorDescriptor* GetCallbacks(int descriptor_number);
2656 inline Name* GetSortedKey(int descriptor_number);
2657 inline int GetSortedKeyIndex(int descriptor_number);
2658 inline void SetSortedKey(int pointer, int descriptor_number);
2659 inline void SetRepresentation(int descriptor_number,
2660 Representation representation);
2662 // Accessor for complete descriptor.
2663 inline void Get(int descriptor_number, Descriptor* desc);
2664 inline void Set(int descriptor_number, Descriptor* desc);
2665 void Replace(int descriptor_number, Descriptor* descriptor);
2667 // Append automatically sets the enumeration index. This should only be used
2668 // to add descriptors in bulk at the end, followed by sorting the descriptor
2670 inline void Append(Descriptor* desc);
2672 static Handle<DescriptorArray> CopyUpTo(Handle<DescriptorArray> desc,
2673 int enumeration_index,
2676 static Handle<DescriptorArray> CopyUpToAddAttributes(
2677 Handle<DescriptorArray> desc,
2678 int enumeration_index,
2679 PropertyAttributes attributes,
2682 // Sort the instance descriptors by the hash codes of their keys.
2685 // Search the instance descriptors for given name.
2686 INLINE(int Search(Name* name, int number_of_own_descriptors));
2688 // As the above, but uses DescriptorLookupCache and updates it when
2690 INLINE(int SearchWithCache(Name* name, Map* map));
2692 // Allocates a DescriptorArray, but returns the singleton
2693 // empty descriptor array object if number_of_descriptors is 0.
2694 static Handle<DescriptorArray> Allocate(Isolate* isolate,
2695 int number_of_descriptors,
2698 DECLARE_CAST(DescriptorArray)
2700 // Constant for denoting key was not found.
2701 static const int kNotFound = -1;
2703 static const int kDescriptorLengthIndex = 0;
2704 static const int kEnumCacheIndex = 1;
2705 static const int kFirstIndex = 2;
2707 // The length of the "bridge" to the enum cache.
2708 static const int kEnumCacheBridgeLength = 2;
2709 static const int kEnumCacheBridgeCacheIndex = 0;
2710 static const int kEnumCacheBridgeIndicesCacheIndex = 1;
2712 // Layout description.
2713 static const int kDescriptorLengthOffset = FixedArray::kHeaderSize;
2714 static const int kEnumCacheOffset = kDescriptorLengthOffset + kPointerSize;
2715 static const int kFirstOffset = kEnumCacheOffset + kPointerSize;
2717 // Layout description for the bridge array.
2718 static const int kEnumCacheBridgeCacheOffset = FixedArray::kHeaderSize;
2720 // Layout of descriptor.
2721 static const int kDescriptorKey = 0;
2722 static const int kDescriptorDetails = 1;
2723 static const int kDescriptorValue = 2;
2724 static const int kDescriptorSize = 3;
2726 #if defined(DEBUG) || defined(OBJECT_PRINT)
2727 // For our gdb macros, we should perhaps change these in the future.
2730 // Print all the descriptors.
2731 void PrintDescriptors(std::ostream& os); // NOLINT
2735 // Is the descriptor array sorted and without duplicates?
2736 bool IsSortedNoDuplicates(int valid_descriptors = -1);
2738 // Is the descriptor array consistent with the back pointers in targets?
2739 bool IsConsistentWithBackPointers(Map* current_map);
2741 // Are two DescriptorArrays equal?
2742 bool IsEqualTo(DescriptorArray* other);
2745 // Returns the fixed array length required to hold number_of_descriptors
2747 static int LengthFor(int number_of_descriptors) {
2748 return ToKeyIndex(number_of_descriptors);
2752 // WhitenessWitness is used to prove that a descriptor array is white
2753 // (unmarked), so incremental write barriers can be skipped because the
2754 // marking invariant cannot be broken and slots pointing into evacuation
2755 // candidates will be discovered when the object is scanned. A witness is
2756 // always stack-allocated right after creating an array. By allocating a
2757 // witness, incremental marking is globally disabled. The witness is then
2758 // passed along wherever needed to statically prove that the array is known to
2760 class WhitenessWitness {
2762 inline explicit WhitenessWitness(DescriptorArray* array);
2763 inline ~WhitenessWitness();
2766 IncrementalMarking* marking_;
2769 // An entry in a DescriptorArray, represented as an (array, index) pair.
2772 inline explicit Entry(DescriptorArray* descs, int index) :
2773 descs_(descs), index_(index) { }
2775 inline PropertyType type() { return descs_->GetType(index_); }
2776 inline Object* GetCallbackObject() { return descs_->GetValue(index_); }
2779 DescriptorArray* descs_;
2783 // Conversion from descriptor number to array indices.
2784 static int ToKeyIndex(int descriptor_number) {
2785 return kFirstIndex +
2786 (descriptor_number * kDescriptorSize) +
2790 static int ToDetailsIndex(int descriptor_number) {
2791 return kFirstIndex +
2792 (descriptor_number * kDescriptorSize) +
2796 static int ToValueIndex(int descriptor_number) {
2797 return kFirstIndex +
2798 (descriptor_number * kDescriptorSize) +
2802 // Transfer a complete descriptor from the src descriptor array to this
2803 // descriptor array.
2804 void CopyFrom(int index, DescriptorArray* src, const WhitenessWitness&);
2806 inline void Set(int descriptor_number,
2808 const WhitenessWitness&);
2810 // Swap first and second descriptor.
2811 inline void SwapSortedKeys(int first, int second);
2813 DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
2817 enum SearchMode { ALL_ENTRIES, VALID_ENTRIES };
2819 template <SearchMode search_mode, typename T>
2820 inline int Search(T* array, Name* name, int valid_entries = 0,
2821 int* out_insertion_index = NULL);
2824 // HashTable is a subclass of FixedArray that implements a hash table
2825 // that uses open addressing and quadratic probing.
2827 // In order for the quadratic probing to work, elements that have not
2828 // yet been used and elements that have been deleted are
2829 // distinguished. Probing continues when deleted elements are
2830 // encountered and stops when unused elements are encountered.
2832 // - Elements with key == undefined have not been used yet.
2833 // - Elements with key == the_hole have been deleted.
2835 // The hash table class is parameterized with a Shape and a Key.
2836 // Shape must be a class with the following interface:
2837 // class ExampleShape {
2839 // // Tells whether key matches other.
2840 // static bool IsMatch(Key key, Object* other);
2841 // // Returns the hash value for key.
2842 // static uint32_t Hash(Key key);
2843 // // Returns the hash value for object.
2844 // static uint32_t HashForObject(Key key, Object* object);
2845 // // Convert key to an object.
2846 // static inline Handle<Object> AsHandle(Isolate* isolate, Key key);
2847 // // The prefix size indicates number of elements in the beginning
2848 // // of the backing storage.
2849 // static const int kPrefixSize = ..;
2850 // // The Element size indicates number of elements per entry.
2851 // static const int kEntrySize = ..;
2853 // The prefix size indicates an amount of memory in the
2854 // beginning of the backing storage that can be used for non-element
2855 // information by subclasses.
2857 template<typename Key>
2860 static const bool UsesSeed = false;
2861 static uint32_t Hash(Key key) { return 0; }
2862 static uint32_t SeededHash(Key key, uint32_t seed) {
2866 static uint32_t HashForObject(Key key, Object* object) { return 0; }
2867 static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
2869 return HashForObject(key, object);
2874 class HashTableBase : public FixedArray {
2876 // Returns the number of elements in the hash table.
2877 int NumberOfElements() {
2878 return Smi::cast(get(kNumberOfElementsIndex))->value();
2881 // Returns the number of deleted elements in the hash table.
2882 int NumberOfDeletedElements() {
2883 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
2886 // Returns the capacity of the hash table.
2888 return Smi::cast(get(kCapacityIndex))->value();
2891 // ElementAdded should be called whenever an element is added to a
2893 void ElementAdded() { SetNumberOfElements(NumberOfElements() + 1); }
2895 // ElementRemoved should be called whenever an element is removed from
2897 void ElementRemoved() {
2898 SetNumberOfElements(NumberOfElements() - 1);
2899 SetNumberOfDeletedElements(NumberOfDeletedElements() + 1);
2901 void ElementsRemoved(int n) {
2902 SetNumberOfElements(NumberOfElements() - n);
2903 SetNumberOfDeletedElements(NumberOfDeletedElements() + n);
2906 // Computes the required capacity for a table holding the given
2907 // number of elements. May be more than HashTable::kMaxCapacity.
2908 static inline int ComputeCapacity(int at_least_space_for);
2910 // Use a different heuristic to compute capacity when serializing.
2911 static inline int ComputeCapacityForSerialization(int at_least_space_for);
2913 // Tells whether k is a real key. The hole and undefined are not allowed
2914 // as keys and can be used to indicate missing or deleted elements.
2915 bool IsKey(Object* k) {
2916 return !k->IsTheHole() && !k->IsUndefined();
2919 // Compute the probe offset (quadratic probing).
2920 INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
2921 return (n + n * n) >> 1;
2924 static const int kNumberOfElementsIndex = 0;
2925 static const int kNumberOfDeletedElementsIndex = 1;
2926 static const int kCapacityIndex = 2;
2927 static const int kPrefixStartIndex = 3;
2929 // Constant used for denoting a absent entry.
2930 static const int kNotFound = -1;
2933 // Update the number of elements in the hash table.
2934 void SetNumberOfElements(int nof) {
2935 set(kNumberOfElementsIndex, Smi::FromInt(nof));
2938 // Update the number of deleted elements in the hash table.
2939 void SetNumberOfDeletedElements(int nod) {
2940 set(kNumberOfDeletedElementsIndex, Smi::FromInt(nod));
2943 // Returns probe entry.
2944 static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
2945 DCHECK(base::bits::IsPowerOfTwo32(size));
2946 return (hash + GetProbeOffset(number)) & (size - 1);
2949 inline static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
2950 return hash & (size - 1);
2953 inline static uint32_t NextProbe(
2954 uint32_t last, uint32_t number, uint32_t size) {
2955 return (last + number) & (size - 1);
2960 template <typename Derived, typename Shape, typename Key>
2961 class HashTable : public HashTableBase {
2964 inline uint32_t Hash(Key key) {
2965 if (Shape::UsesSeed) {
2966 return Shape::SeededHash(key, GetHeap()->HashSeed());
2968 return Shape::Hash(key);
2972 inline uint32_t HashForObject(Key key, Object* object) {
2973 if (Shape::UsesSeed) {
2974 return Shape::SeededHashForObject(key, GetHeap()->HashSeed(), object);
2976 return Shape::HashForObject(key, object);
2980 // Returns a new HashTable object.
2981 MUST_USE_RESULT static Handle<Derived> New(
2982 Isolate* isolate, int at_least_space_for,
2983 MinimumCapacity capacity_option = USE_DEFAULT_MINIMUM_CAPACITY,
2984 PretenureFlag pretenure = NOT_TENURED);
2986 DECLARE_CAST(HashTable)
2988 // Garbage collection support.
2989 void IteratePrefix(ObjectVisitor* visitor);
2990 void IterateElements(ObjectVisitor* visitor);
2992 // Find entry for key otherwise return kNotFound.
2993 inline int FindEntry(Key key);
2994 inline int FindEntry(Isolate* isolate, Key key, int32_t hash);
2995 int FindEntry(Isolate* isolate, Key key);
2997 // Rehashes the table in-place.
2998 void Rehash(Key key);
3000 // Returns the key at entry.
3001 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3003 static const int kElementsStartIndex = kPrefixStartIndex + Shape::kPrefixSize;
3004 static const int kEntrySize = Shape::kEntrySize;
3005 static const int kElementsStartOffset =
3006 kHeaderSize + kElementsStartIndex * kPointerSize;
3007 static const int kCapacityOffset =
3008 kHeaderSize + kCapacityIndex * kPointerSize;
3010 // Returns the index for an entry (of the key)
3011 static inline int EntryToIndex(int entry) {
3012 return (entry * kEntrySize) + kElementsStartIndex;
3016 friend class ObjectHashTable;
3018 // Find the entry at which to insert element with the given key that
3019 // has the given hash value.
3020 uint32_t FindInsertionEntry(uint32_t hash);
3022 // Attempt to shrink hash table after removal of key.
3023 MUST_USE_RESULT static Handle<Derived> Shrink(Handle<Derived> table, Key key);
3025 // Ensure enough space for n additional elements.
3026 MUST_USE_RESULT static Handle<Derived> EnsureCapacity(
3027 Handle<Derived> table,
3030 PretenureFlag pretenure = NOT_TENURED);
3032 // Sets the capacity of the hash table.
3033 void SetCapacity(int capacity) {
3034 // To scale a computed hash code to fit within the hash table, we
3035 // use bit-wise AND with a mask, so the capacity must be positive
3037 DCHECK(capacity > 0);
3038 DCHECK(capacity <= kMaxCapacity);
3039 set(kCapacityIndex, Smi::FromInt(capacity));
3042 // Maximal capacity of HashTable. Based on maximal length of underlying
3043 // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
3045 static const int kMaxCapacity =
3046 (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
3049 // Returns _expected_ if one of entries given by the first _probe_ probes is
3050 // equal to _expected_. Otherwise, returns the entry given by the probe
3052 uint32_t EntryForProbe(Key key, Object* k, int probe, uint32_t expected);
3054 void Swap(uint32_t entry1, uint32_t entry2, WriteBarrierMode mode);
3056 // Rehashes this hash-table into the new table.
3057 void Rehash(Handle<Derived> new_table, Key key);
3061 // HashTableKey is an abstract superclass for virtual key behavior.
3062 class HashTableKey {
3064 // Returns whether the other object matches this key.
3065 virtual bool IsMatch(Object* other) = 0;
3066 // Returns the hash value for this key.
3067 virtual uint32_t Hash() = 0;
3068 // Returns the hash value for object.
3069 virtual uint32_t HashForObject(Object* key) = 0;
3070 // Returns the key object for storing into the hash table.
3071 MUST_USE_RESULT virtual Handle<Object> AsHandle(Isolate* isolate) = 0;
3073 virtual ~HashTableKey() {}
3077 class StringTableShape : public BaseShape<HashTableKey*> {
3079 static inline bool IsMatch(HashTableKey* key, Object* value) {
3080 return key->IsMatch(value);
3083 static inline uint32_t Hash(HashTableKey* key) {
3087 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3088 return key->HashForObject(object);
3091 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3093 static const int kPrefixSize = 0;
3094 static const int kEntrySize = 1;
3097 class SeqOneByteString;
3101 // No special elements in the prefix and the element size is 1
3102 // because only the string itself (the key) needs to be stored.
3103 class StringTable: public HashTable<StringTable,
3107 // Find string in the string table. If it is not there yet, it is
3108 // added. The return value is the string found.
3109 static Handle<String> LookupString(Isolate* isolate, Handle<String> key);
3110 static Handle<String> LookupKey(Isolate* isolate, HashTableKey* key);
3111 static String* LookupKeyIfExists(Isolate* isolate, HashTableKey* key);
3113 // Tries to internalize given string and returns string handle on success
3114 // or an empty handle otherwise.
3115 MUST_USE_RESULT static MaybeHandle<String> InternalizeStringIfExists(
3117 Handle<String> string);
3119 // Looks up a string that is equal to the given string and returns
3120 // string handle if it is found, or an empty handle otherwise.
3121 MUST_USE_RESULT static MaybeHandle<String> LookupStringIfExists(
3123 Handle<String> str);
3124 MUST_USE_RESULT static MaybeHandle<String> LookupTwoCharsStringIfExists(
3129 static void EnsureCapacityForDeserialization(Isolate* isolate, int expected);
3131 DECLARE_CAST(StringTable)
3134 template <bool seq_one_byte>
3135 friend class JsonParser;
3137 DISALLOW_IMPLICIT_CONSTRUCTORS(StringTable);
3141 template <typename Derived, typename Shape, typename Key>
3142 class Dictionary: public HashTable<Derived, Shape, Key> {
3143 typedef HashTable<Derived, Shape, Key> DerivedHashTable;
3146 // Returns the value at entry.
3147 Object* ValueAt(int entry) {
3148 return this->get(Derived::EntryToIndex(entry) + 1);
3151 // Set the value for entry.
3152 void ValueAtPut(int entry, Object* value) {
3153 this->set(Derived::EntryToIndex(entry) + 1, value);
3156 // Returns the property details for the property at entry.
3157 PropertyDetails DetailsAt(int entry) {
3158 return Shape::DetailsAt(static_cast<Derived*>(this), entry);
3161 // Set the details for entry.
3162 void DetailsAtPut(int entry, PropertyDetails value) {
3163 Shape::DetailsAtPut(static_cast<Derived*>(this), entry, value);
3166 // Returns true if property at given entry is deleted.
3167 bool IsDeleted(int entry) {
3168 return Shape::IsDeleted(static_cast<Derived*>(this), entry);
3171 // Delete a property from the dictionary.
3172 static Handle<Object> DeleteProperty(Handle<Derived> dictionary, int entry);
3174 // Attempt to shrink the dictionary after deletion of key.
3175 MUST_USE_RESULT static inline Handle<Derived> Shrink(
3176 Handle<Derived> dictionary,
3178 return DerivedHashTable::Shrink(dictionary, key);
3182 // TODO(dcarney): templatize or move to SeededNumberDictionary
3183 void CopyValuesTo(FixedArray* elements);
3185 // Returns the number of elements in the dictionary filtering out properties
3186 // with the specified attributes.
3187 int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3189 // Returns the number of enumerable elements in the dictionary.
3190 int NumberOfEnumElements() {
3191 return NumberOfElementsFilterAttributes(
3192 static_cast<PropertyAttributes>(DONT_ENUM | SYMBOLIC));
3195 // Returns true if the dictionary contains any elements that are non-writable,
3196 // non-configurable, non-enumerable, or have getters/setters.
3197 bool HasComplexElements();
3199 enum SortMode { UNSORTED, SORTED };
3201 // Fill in details for properties into storage.
3202 // Returns the number of properties added.
3203 int CopyKeysTo(FixedArray* storage, int index, PropertyAttributes filter,
3204 SortMode sort_mode);
3206 // Copies enumerable keys to preallocated fixed array.
3207 void CopyEnumKeysTo(FixedArray* storage);
3209 // Accessors for next enumeration index.
3210 void SetNextEnumerationIndex(int index) {
3212 this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
3215 int NextEnumerationIndex() {
3216 return Smi::cast(this->get(kNextEnumerationIndexIndex))->value();
3219 // Creates a new dictionary.
3220 MUST_USE_RESULT static Handle<Derived> New(
3222 int at_least_space_for,
3223 PretenureFlag pretenure = NOT_TENURED);
3225 // Ensure enough space for n additional elements.
3226 static Handle<Derived> EnsureCapacity(Handle<Derived> obj, int n, Key key);
3229 void Print(std::ostream& os); // NOLINT
3231 // Returns the key (slow).
3232 Object* SlowReverseLookup(Object* value);
3234 // Sets the entry to (key, value) pair.
3235 inline void SetEntry(int entry,
3237 Handle<Object> value);
3238 inline void SetEntry(int entry,
3240 Handle<Object> value,
3241 PropertyDetails details);
3243 MUST_USE_RESULT static Handle<Derived> Add(
3244 Handle<Derived> dictionary,
3246 Handle<Object> value,
3247 PropertyDetails details);
3249 // Returns iteration indices array for the |dictionary|.
3250 // Values are direct indices in the |HashTable| array.
3251 static Handle<FixedArray> BuildIterationIndicesArray(
3252 Handle<Derived> dictionary);
3255 // Generic at put operation.
3256 MUST_USE_RESULT static Handle<Derived> AtPut(
3257 Handle<Derived> dictionary,
3259 Handle<Object> value);
3261 // Add entry to dictionary.
3262 static void AddEntry(
3263 Handle<Derived> dictionary,
3265 Handle<Object> value,
3266 PropertyDetails details,
3269 // Generate new enumeration indices to avoid enumeration index overflow.
3270 // Returns iteration indices array for the |dictionary|.
3271 static Handle<FixedArray> GenerateNewEnumerationIndices(
3272 Handle<Derived> dictionary);
3273 static const int kMaxNumberKeyIndex = DerivedHashTable::kPrefixStartIndex;
3274 static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
3278 template <typename Derived, typename Shape>
3279 class NameDictionaryBase : public Dictionary<Derived, Shape, Handle<Name> > {
3280 typedef Dictionary<Derived, Shape, Handle<Name> > DerivedDictionary;
3283 // Find entry for key, otherwise return kNotFound. Optimized version of
3284 // HashTable::FindEntry.
3285 int FindEntry(Handle<Name> key);
3289 template <typename Key>
3290 class BaseDictionaryShape : public BaseShape<Key> {
3292 template <typename Dictionary>
3293 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry) {
3294 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3295 DCHECK(entry >= 0); // Not found is -1, which is not caught by get().
3296 return PropertyDetails(
3297 Smi::cast(dict->get(Dictionary::EntryToIndex(entry) + 2)));
3300 template <typename Dictionary>
3301 static inline void DetailsAtPut(Dictionary* dict, int entry,
3302 PropertyDetails value) {
3303 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3304 dict->set(Dictionary::EntryToIndex(entry) + 2, value.AsSmi());
3307 template <typename Dictionary>
3308 static bool IsDeleted(Dictionary* dict, int entry) {
3312 template <typename Dictionary>
3313 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3314 Handle<Object> value, PropertyDetails details);
3318 class NameDictionaryShape : public BaseDictionaryShape<Handle<Name> > {
3320 static inline bool IsMatch(Handle<Name> key, Object* other);
3321 static inline uint32_t Hash(Handle<Name> key);
3322 static inline uint32_t HashForObject(Handle<Name> key, Object* object);
3323 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Name> key);
3324 static const int kPrefixSize = 2;
3325 static const int kEntrySize = 3;
3326 static const bool kIsEnumerable = true;
3330 class NameDictionary
3331 : public NameDictionaryBase<NameDictionary, NameDictionaryShape> {
3332 typedef NameDictionaryBase<NameDictionary, NameDictionaryShape>
3336 DECLARE_CAST(NameDictionary)
3338 inline static Handle<FixedArray> DoGenerateNewEnumerationIndices(
3339 Handle<NameDictionary> dictionary);
3343 class GlobalDictionaryShape : public NameDictionaryShape {
3345 static const int kEntrySize = 2; // Overrides NameDictionaryShape::kEntrySize
3347 template <typename Dictionary>
3348 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry);
3350 template <typename Dictionary>
3351 static inline void DetailsAtPut(Dictionary* dict, int entry,
3352 PropertyDetails value);
3354 template <typename Dictionary>
3355 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 GlobalDictionary
3364 : public NameDictionaryBase<GlobalDictionary, GlobalDictionaryShape> {
3366 DECLARE_CAST(GlobalDictionary)
3370 class NumberDictionaryShape : public BaseDictionaryShape<uint32_t> {
3372 static inline bool IsMatch(uint32_t key, Object* other);
3373 static inline Handle<Object> AsHandle(Isolate* isolate, uint32_t key);
3374 static const int kEntrySize = 3;
3375 static const bool kIsEnumerable = false;
3379 class SeededNumberDictionaryShape : public NumberDictionaryShape {
3381 static const bool UsesSeed = true;
3382 static const int kPrefixSize = 2;
3384 static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
3385 static inline uint32_t SeededHashForObject(uint32_t key,
3391 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
3393 static const int kPrefixSize = 0;
3395 static inline uint32_t Hash(uint32_t key);
3396 static inline uint32_t HashForObject(uint32_t key, Object* object);
3400 class SeededNumberDictionary
3401 : public Dictionary<SeededNumberDictionary,
3402 SeededNumberDictionaryShape,
3405 DECLARE_CAST(SeededNumberDictionary)
3407 // Type specific at put (default NONE attributes is used when adding).
3408 MUST_USE_RESULT static Handle<SeededNumberDictionary> AtNumberPut(
3409 Handle<SeededNumberDictionary> dictionary,
3411 Handle<Object> value);
3412 MUST_USE_RESULT static Handle<SeededNumberDictionary> AddNumberEntry(
3413 Handle<SeededNumberDictionary> dictionary,
3415 Handle<Object> value,
3416 PropertyDetails details);
3418 // Set an existing entry or add a new one if needed.
3419 // Return the updated dictionary.
3420 MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
3421 Handle<SeededNumberDictionary> dictionary,
3423 Handle<Object> value,
3424 PropertyDetails details);
3426 void UpdateMaxNumberKey(uint32_t key);
3428 // If slow elements are required we will never go back to fast-case
3429 // for the elements kept in this dictionary. We require slow
3430 // elements if an element has been added at an index larger than
3431 // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
3432 // when defining a getter or setter with a number key.
3433 inline bool requires_slow_elements();
3434 inline void set_requires_slow_elements();
3436 // Get the value of the max number key that has been added to this
3437 // dictionary. max_number_key can only be called if
3438 // requires_slow_elements returns false.
3439 inline uint32_t max_number_key();
3442 static const int kRequiresSlowElementsMask = 1;
3443 static const int kRequiresSlowElementsTagSize = 1;
3444 static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
3448 class UnseededNumberDictionary
3449 : public Dictionary<UnseededNumberDictionary,
3450 UnseededNumberDictionaryShape,
3453 DECLARE_CAST(UnseededNumberDictionary)
3455 // Type specific at put (default NONE attributes is used when adding).
3456 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AtNumberPut(
3457 Handle<UnseededNumberDictionary> dictionary,
3459 Handle<Object> value);
3460 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AddNumberEntry(
3461 Handle<UnseededNumberDictionary> dictionary,
3463 Handle<Object> value);
3465 // Set an existing entry or add a new one if needed.
3466 // Return the updated dictionary.
3467 MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
3468 Handle<UnseededNumberDictionary> dictionary,
3470 Handle<Object> value);
3474 class ObjectHashTableShape : public BaseShape<Handle<Object> > {
3476 static inline bool IsMatch(Handle<Object> key, Object* other);
3477 static inline uint32_t Hash(Handle<Object> key);
3478 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3479 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3480 static const int kPrefixSize = 0;
3481 static const int kEntrySize = 2;
3485 // ObjectHashTable maps keys that are arbitrary objects to object values by
3486 // using the identity hash of the key for hashing purposes.
3487 class ObjectHashTable: public HashTable<ObjectHashTable,
3488 ObjectHashTableShape,
3491 ObjectHashTable, ObjectHashTableShape, Handle<Object> > DerivedHashTable;
3493 DECLARE_CAST(ObjectHashTable)
3495 // Attempt to shrink hash table after removal of key.
3496 MUST_USE_RESULT static inline Handle<ObjectHashTable> Shrink(
3497 Handle<ObjectHashTable> table,
3498 Handle<Object> key);
3500 // Looks up the value associated with the given key. The hole value is
3501 // returned in case the key is not present.
3502 Object* Lookup(Handle<Object> key);
3503 Object* Lookup(Handle<Object> key, int32_t hash);
3504 Object* Lookup(Isolate* isolate, Handle<Object> key, int32_t hash);
3506 // Adds (or overwrites) the value associated with the given key.
3507 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3509 Handle<Object> value);
3510 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3511 Handle<Object> key, Handle<Object> value,
3514 // Returns an ObjectHashTable (possibly |table|) where |key| has been removed.
3515 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3518 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3519 Handle<Object> key, bool* was_present,
3523 friend class MarkCompactCollector;
3525 void AddEntry(int entry, Object* key, Object* value);
3526 void RemoveEntry(int entry);
3528 // Returns the index to the value of an entry.
3529 static inline int EntryToValueIndex(int entry) {
3530 return EntryToIndex(entry) + 1;
3535 // OrderedHashTable is a HashTable with Object keys that preserves
3536 // insertion order. There are Map and Set interfaces (OrderedHashMap
3537 // and OrderedHashTable, below). It is meant to be used by JSMap/JSSet.
3539 // Only Object* keys are supported, with Object::SameValueZero() used as the
3540 // equality operator and Object::GetHash() for the hash function.
3542 // Based on the "Deterministic Hash Table" as described by Jason Orendorff at
3543 // https://wiki.mozilla.org/User:Jorend/Deterministic_hash_tables
3544 // Originally attributed to Tyler Close.
3547 // [0]: bucket count
3548 // [1]: element count
3549 // [2]: deleted element count
3550 // [3..(3 + NumberOfBuckets() - 1)]: "hash table", where each item is an
3551 // offset into the data table (see below) where the
3552 // first item in this bucket is stored.
3553 // [3 + NumberOfBuckets()..length]: "data table", an array of length
3554 // Capacity() * kEntrySize, where the first entrysize
3555 // items are handled by the derived class and the
3556 // item at kChainOffset is another entry into the
3557 // data table indicating the next entry in this hash
3560 // When we transition the table to a new version we obsolete it and reuse parts
3561 // of the memory to store information how to transition an iterator to the new
3564 // Memory layout for obsolete table:
3565 // [0]: bucket count
3566 // [1]: Next newer table
3567 // [2]: Number of removed holes or -1 when the table was cleared.
3568 // [3..(3 + NumberOfRemovedHoles() - 1)]: The indexes of the removed holes.
3569 // [3 + NumberOfRemovedHoles()..length]: Not used
3571 template<class Derived, class Iterator, int entrysize>
3572 class OrderedHashTable: public FixedArray {
3574 // Returns an OrderedHashTable with a capacity of at least |capacity|.
3575 static Handle<Derived> Allocate(
3576 Isolate* isolate, int capacity, PretenureFlag pretenure = NOT_TENURED);
3578 // Returns an OrderedHashTable (possibly |table|) with enough space
3579 // to add at least one new element.
3580 static Handle<Derived> EnsureGrowable(Handle<Derived> table);
3582 // Returns an OrderedHashTable (possibly |table|) that's shrunken
3584 static Handle<Derived> Shrink(Handle<Derived> table);
3586 // Returns a new empty OrderedHashTable and records the clearing so that
3587 // exisiting iterators can be updated.
3588 static Handle<Derived> Clear(Handle<Derived> table);
3590 int NumberOfElements() {
3591 return Smi::cast(get(kNumberOfElementsIndex))->value();
3594 int NumberOfDeletedElements() {
3595 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3598 int UsedCapacity() { return NumberOfElements() + NumberOfDeletedElements(); }
3600 int NumberOfBuckets() {
3601 return Smi::cast(get(kNumberOfBucketsIndex))->value();
3604 // Returns an index into |this| for the given entry.
3605 int EntryToIndex(int entry) {
3606 return kHashTableStartIndex + NumberOfBuckets() + (entry * kEntrySize);
3609 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3612 return !get(kNextTableIndex)->IsSmi();
3615 // The next newer table. This is only valid if the table is obsolete.
3616 Derived* NextTable() {
3617 return Derived::cast(get(kNextTableIndex));
3620 // When the table is obsolete we store the indexes of the removed holes.
3621 int RemovedIndexAt(int index) {
3622 return Smi::cast(get(kRemovedHolesIndex + index))->value();
3625 static const int kNotFound = -1;
3626 static const int kMinCapacity = 4;
3628 static const int kNumberOfBucketsIndex = 0;
3629 static const int kNumberOfElementsIndex = kNumberOfBucketsIndex + 1;
3630 static const int kNumberOfDeletedElementsIndex = kNumberOfElementsIndex + 1;
3631 static const int kHashTableStartIndex = kNumberOfDeletedElementsIndex + 1;
3632 static const int kNextTableIndex = kNumberOfElementsIndex;
3634 static const int kNumberOfBucketsOffset =
3635 kHeaderSize + kNumberOfBucketsIndex * kPointerSize;
3636 static const int kNumberOfElementsOffset =
3637 kHeaderSize + kNumberOfElementsIndex * kPointerSize;
3638 static const int kNumberOfDeletedElementsOffset =
3639 kHeaderSize + kNumberOfDeletedElementsIndex * kPointerSize;
3640 static const int kHashTableStartOffset =
3641 kHeaderSize + kHashTableStartIndex * kPointerSize;
3642 static const int kNextTableOffset =
3643 kHeaderSize + kNextTableIndex * kPointerSize;
3645 static const int kEntrySize = entrysize + 1;
3646 static const int kChainOffset = entrysize;
3648 static const int kLoadFactor = 2;
3650 // NumberOfDeletedElements is set to kClearedTableSentinel when
3651 // the table is cleared, which allows iterator transitions to
3652 // optimize that case.
3653 static const int kClearedTableSentinel = -1;
3656 static Handle<Derived> Rehash(Handle<Derived> table, int new_capacity);
3658 void SetNumberOfBuckets(int num) {
3659 set(kNumberOfBucketsIndex, Smi::FromInt(num));
3662 void SetNumberOfElements(int num) {
3663 set(kNumberOfElementsIndex, Smi::FromInt(num));
3666 void SetNumberOfDeletedElements(int num) {
3667 set(kNumberOfDeletedElementsIndex, Smi::FromInt(num));
3671 return NumberOfBuckets() * kLoadFactor;
3674 void SetNextTable(Derived* next_table) {
3675 set(kNextTableIndex, next_table);
3678 void SetRemovedIndexAt(int index, int removed_index) {
3679 return set(kRemovedHolesIndex + index, Smi::FromInt(removed_index));
3682 static const int kRemovedHolesIndex = kHashTableStartIndex;
3684 static const int kMaxCapacity =
3685 (FixedArray::kMaxLength - kHashTableStartIndex)
3686 / (1 + (kEntrySize * kLoadFactor));
3690 class JSSetIterator;
3693 class OrderedHashSet: public OrderedHashTable<
3694 OrderedHashSet, JSSetIterator, 1> {
3696 DECLARE_CAST(OrderedHashSet)
3700 class JSMapIterator;
3703 class OrderedHashMap
3704 : public OrderedHashTable<OrderedHashMap, JSMapIterator, 2> {
3706 DECLARE_CAST(OrderedHashMap)
3708 Object* ValueAt(int entry) {
3709 return get(EntryToIndex(entry) + kValueOffset);
3712 static const int kValueOffset = 1;
3716 template <int entrysize>
3717 class WeakHashTableShape : public BaseShape<Handle<Object> > {
3719 static inline bool IsMatch(Handle<Object> key, Object* other);
3720 static inline uint32_t Hash(Handle<Object> key);
3721 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3722 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3723 static const int kPrefixSize = 0;
3724 static const int kEntrySize = entrysize;
3728 // WeakHashTable maps keys that are arbitrary heap objects to heap object
3729 // values. The table wraps the keys in weak cells and store values directly.
3730 // Thus it references keys weakly and values strongly.
3731 class WeakHashTable: public HashTable<WeakHashTable,
3732 WeakHashTableShape<2>,
3735 WeakHashTable, WeakHashTableShape<2>, Handle<Object> > DerivedHashTable;
3737 DECLARE_CAST(WeakHashTable)
3739 // Looks up the value associated with the given key. The hole value is
3740 // returned in case the key is not present.
3741 Object* Lookup(Handle<HeapObject> key);
3743 // Adds (or overwrites) the value associated with the given key. Mapping a
3744 // key to the hole value causes removal of the whole entry.
3745 MUST_USE_RESULT static Handle<WeakHashTable> Put(Handle<WeakHashTable> table,
3746 Handle<HeapObject> key,
3747 Handle<HeapObject> value);
3749 static Handle<FixedArray> GetValues(Handle<WeakHashTable> table);
3752 friend class MarkCompactCollector;
3754 void AddEntry(int entry, Handle<WeakCell> key, Handle<HeapObject> value);
3756 // Returns the index to the value of an entry.
3757 static inline int EntryToValueIndex(int entry) {
3758 return EntryToIndex(entry) + 1;
3763 class WeakValueHashTable : public ObjectHashTable {
3765 DECLARE_CAST(WeakValueHashTable)
3768 // Looks up the value associated with the given key. The hole value is
3769 // returned in case the key is not present.
3770 Object* LookupWeak(Handle<Object> key);
3773 // Adds (or overwrites) the value associated with the given key. Mapping a
3774 // key to the hole value causes removal of the whole entry.
3775 MUST_USE_RESULT static Handle<WeakValueHashTable> PutWeak(
3776 Handle<WeakValueHashTable> table, Handle<Object> key,
3777 Handle<HeapObject> value);
3779 static Handle<FixedArray> GetWeakValues(Handle<WeakValueHashTable> table);
3783 // JSFunctionResultCache caches results of some JSFunction invocation.
3784 // It is a fixed array with fixed structure:
3785 // [0]: factory function
3786 // [1]: finger index
3787 // [2]: current cache size
3788 // [3]: dummy field.
3789 // The rest of array are key/value pairs.
3790 class JSFunctionResultCache : public FixedArray {
3792 static const int kFactoryIndex = 0;
3793 static const int kFingerIndex = kFactoryIndex + 1;
3794 static const int kCacheSizeIndex = kFingerIndex + 1;
3795 static const int kDummyIndex = kCacheSizeIndex + 1;
3796 static const int kEntriesIndex = kDummyIndex + 1;
3798 static const int kEntrySize = 2; // key + value
3800 static const int kFactoryOffset = kHeaderSize;
3801 static const int kFingerOffset = kFactoryOffset + kPointerSize;
3802 static const int kCacheSizeOffset = kFingerOffset + kPointerSize;
3804 inline void MakeZeroSize();
3805 inline void Clear();
3808 inline void set_size(int size);
3809 inline int finger_index();
3810 inline void set_finger_index(int finger_index);
3812 DECLARE_CAST(JSFunctionResultCache)
3814 DECLARE_VERIFIER(JSFunctionResultCache)
3818 // ScopeInfo represents information about different scopes of a source
3819 // program and the allocation of the scope's variables. Scope information
3820 // is stored in a compressed form in ScopeInfo objects and is used
3821 // at runtime (stack dumps, deoptimization, etc.).
3823 // This object provides quick access to scope info details for runtime
3825 class ScopeInfo : public FixedArray {
3827 DECLARE_CAST(ScopeInfo)
3829 // Return the type of this scope.
3830 ScopeType scope_type();
3832 // Does this scope call eval?
3835 // Return the language mode of this scope.
3836 LanguageMode language_mode();
3838 // Does this scope make a sloppy eval call?
3839 bool CallsSloppyEval() { return CallsEval() && is_sloppy(language_mode()); }
3841 // Return the total number of locals allocated on the stack and in the
3842 // context. This includes the parameters that are allocated in the context.
3845 // Return the number of stack slots for code. This number consists of two
3847 // 1. One stack slot per stack allocated local.
3848 // 2. One stack slot for the function name if it is stack allocated.
3849 int StackSlotCount();
3851 // Return the number of context slots for code if a context is allocated. This
3852 // number consists of three parts:
3853 // 1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
3854 // 2. One context slot per context allocated local.
3855 // 3. One context slot for the function name if it is context allocated.
3856 // Parameters allocated in the context count as context allocated locals. If
3857 // no contexts are allocated for this scope ContextLength returns 0.
3858 int ContextLength();
3860 // Does this scope declare a "this" binding?
3863 // Does this scope declare a "this" binding, and the "this" binding is stack-
3864 // or context-allocated?
3865 bool HasAllocatedReceiver();
3867 // Is this scope the scope of a named function expression?
3868 bool HasFunctionName();
3870 // Return if this has context allocated locals.
3871 bool HasHeapAllocatedLocals();
3873 // Return if contexts are allocated for this scope.
3876 // Return if this is a function scope with "use asm".
3877 bool IsAsmModule() { return AsmModuleField::decode(Flags()); }
3879 // Return if this is a nested function within an asm module scope.
3880 bool IsAsmFunction() { return AsmFunctionField::decode(Flags()); }
3882 bool IsSimpleParameterList() {
3883 return IsSimpleParameterListField::decode(Flags());
3886 // Return the function_name if present.
3887 String* FunctionName();
3889 // Return the name of the given parameter.
3890 String* ParameterName(int var);
3892 // Return the name of the given local.
3893 String* LocalName(int var);
3895 // Return the name of the given stack local.
3896 String* StackLocalName(int var);
3898 // Return the name of the given stack local.
3899 int StackLocalIndex(int var);
3901 // Return the name of the given context local.
3902 String* ContextLocalName(int var);
3904 // Return the mode of the given context local.
3905 VariableMode ContextLocalMode(int var);
3907 // Return the initialization flag of the given context local.
3908 InitializationFlag ContextLocalInitFlag(int var);
3910 // Return the initialization flag of the given context local.
3911 MaybeAssignedFlag ContextLocalMaybeAssignedFlag(int var);
3913 // Return true if this local was introduced by the compiler, and should not be
3914 // exposed to the user in a debugger.
3915 bool LocalIsSynthetic(int var);
3917 String* StrongModeFreeVariableName(int var);
3918 int StrongModeFreeVariableStartPosition(int var);
3919 int StrongModeFreeVariableEndPosition(int var);
3921 // Lookup support for serialized scope info. Returns the
3922 // the stack slot index for a given slot name if the slot is
3923 // present; otherwise returns a value < 0. The name must be an internalized
3925 int StackSlotIndex(String* name);
3927 // Lookup support for serialized scope info. Returns the
3928 // context slot index for a given slot name if the slot is present; otherwise
3929 // returns a value < 0. The name must be an internalized string.
3930 // If the slot is present and mode != NULL, sets *mode to the corresponding
3931 // mode for that variable.
3932 static int ContextSlotIndex(Handle<ScopeInfo> scope_info, Handle<String> name,
3933 VariableMode* mode, VariableLocation* location,
3934 InitializationFlag* init_flag,
3935 MaybeAssignedFlag* maybe_assigned_flag);
3937 // Lookup support for serialized scope info. Returns the
3938 // parameter index for a given parameter name if the parameter is present;
3939 // otherwise returns a value < 0. The name must be an internalized string.
3940 int ParameterIndex(String* name);
3942 // Lookup support for serialized scope info. Returns the function context
3943 // slot index if the function name is present and context-allocated (named
3944 // function expressions, only), otherwise returns a value < 0. The name
3945 // must be an internalized string.
3946 int FunctionContextSlotIndex(String* name, VariableMode* mode);
3948 // Lookup support for serialized scope info. Returns the receiver context
3949 // slot index if scope has a "this" binding, and the binding is
3950 // context-allocated. Otherwise returns a value < 0.
3951 int ReceiverContextSlotIndex();
3953 FunctionKind function_kind();
3955 // Copies all the context locals into an object used to materialize a scope.
3956 static void CopyContextLocalsToScopeObject(Handle<ScopeInfo> scope_info,
3957 Handle<Context> context,
3958 Handle<JSObject> scope_object);
3961 static Handle<ScopeInfo> Create(Isolate* isolate, Zone* zone, Scope* scope);
3962 static Handle<ScopeInfo> CreateGlobalThisBinding(Isolate* isolate);
3964 // Serializes empty scope info.
3965 static ScopeInfo* Empty(Isolate* isolate);
3971 // The layout of the static part of a ScopeInfo is as follows. Each entry is
3972 // numeric and occupies one array slot.
3973 // 1. A set of properties of the scope
3974 // 2. The number of parameters. This only applies to function scopes. For
3975 // non-function scopes this is 0.
3976 // 3. The number of non-parameter variables allocated on the stack.
3977 // 4. The number of non-parameter and parameter variables allocated in the
3979 #define FOR_EACH_NUMERIC_FIELD(V) \
3982 V(StackLocalCount) \
3983 V(ContextLocalCount) \
3984 V(ContextGlobalCount) \
3985 V(StrongModeFreeVariableCount)
3987 #define FIELD_ACCESSORS(name) \
3988 void Set##name(int value) { \
3989 set(k##name, Smi::FromInt(value)); \
3992 if (length() > 0) { \
3993 return Smi::cast(get(k##name))->value(); \
3998 FOR_EACH_NUMERIC_FIELD(FIELD_ACCESSORS)
3999 #undef FIELD_ACCESSORS
4003 #define DECL_INDEX(name) k##name,
4004 FOR_EACH_NUMERIC_FIELD(DECL_INDEX)
4006 #undef FOR_EACH_NUMERIC_FIELD
4010 // The layout of the variable part of a ScopeInfo is as follows:
4011 // 1. ParameterEntries:
4012 // This part stores the names of the parameters for function scopes. One
4013 // slot is used per parameter, so in total this part occupies
4014 // ParameterCount() slots in the array. For other scopes than function
4015 // scopes ParameterCount() is 0.
4016 // 2. StackLocalFirstSlot:
4017 // Index of a first stack slot for stack local. Stack locals belonging to
4018 // this scope are located on a stack at slots starting from this index.
4019 // 3. StackLocalEntries:
4020 // Contains the names of local variables that are allocated on the stack,
4021 // in increasing order of the stack slot index. First local variable has
4022 // a stack slot index defined in StackLocalFirstSlot (point 2 above).
4023 // One slot is used per stack local, so in total this part occupies
4024 // StackLocalCount() slots in the array.
4025 // 4. ContextLocalNameEntries:
4026 // Contains the names of local variables and parameters that are allocated
4027 // in the context. They are stored in increasing order of the context slot
4028 // index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
4029 // context local, so in total this part occupies ContextLocalCount() slots
4031 // 5. ContextLocalInfoEntries:
4032 // Contains the variable modes and initialization flags corresponding to
4033 // the context locals in ContextLocalNameEntries. One slot is used per
4034 // context local, so in total this part occupies ContextLocalCount()
4035 // slots in the array.
4036 // 6. StrongModeFreeVariableNameEntries:
4037 // Stores the names of strong mode free variables.
4038 // 7. StrongModeFreeVariablePositionEntries:
4039 // Stores the locations (start and end position) of strong mode free
4041 // 8. RecieverEntryIndex:
4042 // If the scope binds a "this" value, one slot is reserved to hold the
4043 // context or stack slot index for the variable.
4044 // 9. FunctionNameEntryIndex:
4045 // If the scope belongs to a named function expression this part contains
4046 // information about the function variable. It always occupies two array
4047 // slots: a. The name of the function variable.
4048 // b. The context or stack slot index for the variable.
4049 int ParameterEntriesIndex();
4050 int StackLocalFirstSlotIndex();
4051 int StackLocalEntriesIndex();
4052 int ContextLocalNameEntriesIndex();
4053 int ContextGlobalNameEntriesIndex();
4054 int ContextLocalInfoEntriesIndex();
4055 int ContextGlobalInfoEntriesIndex();
4056 int StrongModeFreeVariableNameEntriesIndex();
4057 int StrongModeFreeVariablePositionEntriesIndex();
4058 int ReceiverEntryIndex();
4059 int FunctionNameEntryIndex();
4061 int Lookup(Handle<String> name, int start, int end, VariableMode* mode,
4062 VariableLocation* location, InitializationFlag* init_flag,
4063 MaybeAssignedFlag* maybe_assigned_flag);
4065 // Used for the function name variable for named function expressions, and for
4067 enum VariableAllocationInfo { NONE, STACK, CONTEXT, UNUSED };
4069 // Properties of scopes.
4070 class ScopeTypeField : public BitField<ScopeType, 0, 4> {};
4071 class CallsEvalField : public BitField<bool, ScopeTypeField::kNext, 1> {};
4072 STATIC_ASSERT(LANGUAGE_END == 3);
4073 class LanguageModeField
4074 : public BitField<LanguageMode, CallsEvalField::kNext, 2> {};
4075 class ReceiverVariableField
4076 : public BitField<VariableAllocationInfo, LanguageModeField::kNext, 2> {};
4077 class FunctionVariableField
4078 : public BitField<VariableAllocationInfo, ReceiverVariableField::kNext,
4080 class FunctionVariableMode
4081 : public BitField<VariableMode, FunctionVariableField::kNext, 3> {};
4082 class AsmModuleField : public BitField<bool, FunctionVariableMode::kNext, 1> {
4084 class AsmFunctionField : public BitField<bool, AsmModuleField::kNext, 1> {};
4085 class IsSimpleParameterListField
4086 : public BitField<bool, AsmFunctionField::kNext, 1> {};
4087 class FunctionKindField
4088 : public BitField<FunctionKind, IsSimpleParameterListField::kNext, 8> {};
4090 // BitFields representing the encoded information for context locals in the
4091 // ContextLocalInfoEntries part.
4092 class ContextLocalMode: public BitField<VariableMode, 0, 3> {};
4093 class ContextLocalInitFlag: public BitField<InitializationFlag, 3, 1> {};
4094 class ContextLocalMaybeAssignedFlag
4095 : public BitField<MaybeAssignedFlag, 4, 1> {};
4099 // The cache for maps used by normalized (dictionary mode) objects.
4100 // Such maps do not have property descriptors, so a typical program
4101 // needs very limited number of distinct normalized maps.
4102 class NormalizedMapCache: public FixedArray {
4104 static Handle<NormalizedMapCache> New(Isolate* isolate);
4106 MUST_USE_RESULT MaybeHandle<Map> Get(Handle<Map> fast_map,
4107 PropertyNormalizationMode mode);
4108 void Set(Handle<Map> fast_map, Handle<Map> normalized_map);
4112 DECLARE_CAST(NormalizedMapCache)
4114 static inline bool IsNormalizedMapCache(const Object* obj);
4116 DECLARE_VERIFIER(NormalizedMapCache)
4118 static const int kEntries = 64;
4120 static inline int GetIndex(Handle<Map> map);
4122 // The following declarations hide base class methods.
4123 Object* get(int index);
4124 void set(int index, Object* value);
4128 // ByteArray represents fixed sized byte arrays. Used for the relocation info
4129 // that is attached to code objects.
4130 class ByteArray: public FixedArrayBase {
4132 inline int Size() { return RoundUp(length() + kHeaderSize, kPointerSize); }
4134 // Setter and getter.
4135 inline byte get(int index);
4136 inline void set(int index, byte value);
4138 // Treat contents as an int array.
4139 inline int get_int(int index);
4141 static int SizeFor(int length) {
4142 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4144 // We use byte arrays for free blocks in the heap. Given a desired size in
4145 // bytes that is a multiple of the word size and big enough to hold a byte
4146 // array, this function returns the number of elements a byte array should
4148 static int LengthFor(int size_in_bytes) {
4149 DCHECK(IsAligned(size_in_bytes, kPointerSize));
4150 DCHECK(size_in_bytes >= kHeaderSize);
4151 return size_in_bytes - kHeaderSize;
4154 // Returns data start address.
4155 inline Address GetDataStartAddress();
4157 // Returns a pointer to the ByteArray object for a given data start address.
4158 static inline ByteArray* FromDataStartAddress(Address address);
4160 DECLARE_CAST(ByteArray)
4162 // Dispatched behavior.
4163 inline int ByteArraySize() {
4164 return SizeFor(this->length());
4166 DECLARE_PRINTER(ByteArray)
4167 DECLARE_VERIFIER(ByteArray)
4169 // Layout description.
4170 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4172 // Maximal memory consumption for a single ByteArray.
4173 static const int kMaxSize = 512 * MB;
4174 // Maximal length of a single ByteArray.
4175 static const int kMaxLength = kMaxSize - kHeaderSize;
4178 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4182 // BytecodeArray represents a sequence of interpreter bytecodes.
4183 class BytecodeArray : public FixedArrayBase {
4185 static int SizeFor(int length) {
4186 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4189 // Setter and getter
4190 inline byte get(int index);
4191 inline void set(int index, byte value);
4193 // Returns data start address.
4194 inline Address GetFirstBytecodeAddress();
4196 // Accessors for frame size and the number of locals
4197 inline int frame_size() const;
4198 inline void set_frame_size(int value);
4200 DECLARE_CAST(BytecodeArray)
4202 // Dispatched behavior.
4203 inline int BytecodeArraySize() { return SizeFor(this->length()); }
4205 DECLARE_PRINTER(BytecodeArray)
4206 DECLARE_VERIFIER(BytecodeArray)
4208 void Disassemble(std::ostream& os);
4210 // Layout description.
4211 static const int kFrameSizeOffset = FixedArrayBase::kHeaderSize;
4212 static const int kHeaderSize = kFrameSizeOffset + kIntSize;
4214 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4216 // Maximal memory consumption for a single BytecodeArray.
4217 static const int kMaxSize = 512 * MB;
4218 // Maximal length of a single BytecodeArray.
4219 static const int kMaxLength = kMaxSize - kHeaderSize;
4222 DISALLOW_IMPLICIT_CONSTRUCTORS(BytecodeArray);
4226 // FreeSpace are fixed-size free memory blocks used by the heap and GC.
4227 // They look like heap objects (are heap object tagged and have a map) so that
4228 // the heap remains iterable. They have a size and a next pointer.
4229 // The next pointer is the raw address of the next FreeSpace object (or NULL)
4230 // in the free list.
4231 class FreeSpace: public HeapObject {
4233 // [size]: size of the free space including the header.
4234 inline int size() const;
4235 inline void set_size(int value);
4237 inline int nobarrier_size() const;
4238 inline void nobarrier_set_size(int value);
4240 inline int Size() { return size(); }
4242 // Accessors for the next field.
4243 inline FreeSpace* next();
4244 inline FreeSpace** next_address();
4245 inline void set_next(FreeSpace* next);
4247 inline static FreeSpace* cast(HeapObject* obj);
4249 // Dispatched behavior.
4250 DECLARE_PRINTER(FreeSpace)
4251 DECLARE_VERIFIER(FreeSpace)
4253 // Layout description.
4254 // Size is smi tagged when it is stored.
4255 static const int kSizeOffset = HeapObject::kHeaderSize;
4256 static const int kNextOffset = POINTER_SIZE_ALIGN(kSizeOffset + kPointerSize);
4259 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
4263 // V has parameters (Type, type, TYPE, C type, element_size)
4264 #define TYPED_ARRAYS(V) \
4265 V(Uint8, uint8, UINT8, uint8_t, 1) \
4266 V(Int8, int8, INT8, int8_t, 1) \
4267 V(Uint16, uint16, UINT16, uint16_t, 2) \
4268 V(Int16, int16, INT16, int16_t, 2) \
4269 V(Uint32, uint32, UINT32, uint32_t, 4) \
4270 V(Int32, int32, INT32, int32_t, 4) \
4271 V(Float32, float32, FLOAT32, float, 4) \
4272 V(Float64, float64, FLOAT64, double, 8) \
4273 V(Uint8Clamped, uint8_clamped, UINT8_CLAMPED, uint8_t, 1)
4276 class FixedTypedArrayBase: public FixedArrayBase {
4278 // [base_pointer]: Either points to the FixedTypedArrayBase itself or nullptr.
4279 DECL_ACCESSORS(base_pointer, Object)
4281 // [external_pointer]: Contains the offset between base_pointer and the start
4282 // of the data. If the base_pointer is a nullptr, the external_pointer
4283 // therefore points to the actual backing store.
4284 DECL_ACCESSORS(external_pointer, void)
4286 // Dispatched behavior.
4287 inline void FixedTypedArrayBaseIterateBody(ObjectVisitor* v);
4289 template <typename StaticVisitor>
4290 inline void FixedTypedArrayBaseIterateBody();
4292 DECLARE_CAST(FixedTypedArrayBase)
4294 static const int kBasePointerOffset = FixedArrayBase::kHeaderSize;
4295 static const int kExternalPointerOffset = kBasePointerOffset + kPointerSize;
4296 static const int kHeaderSize =
4297 DOUBLE_POINTER_ALIGN(kExternalPointerOffset + kPointerSize);
4299 static const int kDataOffset = kHeaderSize;
4303 static inline int TypedArraySize(InstanceType type, int length);
4304 inline int TypedArraySize(InstanceType type);
4306 // Use with care: returns raw pointer into heap.
4307 inline void* DataPtr();
4309 inline int DataSize();
4312 static inline int ElementSize(InstanceType type);
4314 inline int DataSize(InstanceType type);
4316 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
4320 template <class Traits>
4321 class FixedTypedArray: public FixedTypedArrayBase {
4323 typedef typename Traits::ElementType ElementType;
4324 static const InstanceType kInstanceType = Traits::kInstanceType;
4326 DECLARE_CAST(FixedTypedArray<Traits>)
4328 inline ElementType get_scalar(int index);
4329 static inline Handle<Object> get(Handle<FixedTypedArray> array, int index);
4330 inline void set(int index, ElementType value);
4332 static inline ElementType from_int(int value);
4333 static inline ElementType from_double(double value);
4335 // This accessor applies the correct conversion from Smi, HeapNumber
4337 void SetValue(uint32_t index, Object* value);
4339 DECLARE_PRINTER(FixedTypedArray)
4340 DECLARE_VERIFIER(FixedTypedArray)
4343 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
4346 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size) \
4347 class Type##ArrayTraits { \
4348 public: /* NOLINT */ \
4349 typedef elementType ElementType; \
4350 static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE; \
4351 static const char* Designator() { return #type " array"; } \
4352 static inline Handle<Object> ToHandle(Isolate* isolate, \
4353 elementType scalar); \
4354 static inline elementType defaultValue(); \
4357 typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
4359 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
4361 #undef FIXED_TYPED_ARRAY_TRAITS
4364 // DeoptimizationInputData is a fixed array used to hold the deoptimization
4365 // data for code generated by the Hydrogen/Lithium compiler. It also
4366 // contains information about functions that were inlined. If N different
4367 // functions were inlined then first N elements of the literal array will
4368 // contain these functions.
4371 class DeoptimizationInputData: public FixedArray {
4373 // Layout description. Indices in the array.
4374 static const int kTranslationByteArrayIndex = 0;
4375 static const int kInlinedFunctionCountIndex = 1;
4376 static const int kLiteralArrayIndex = 2;
4377 static const int kOsrAstIdIndex = 3;
4378 static const int kOsrPcOffsetIndex = 4;
4379 static const int kOptimizationIdIndex = 5;
4380 static const int kSharedFunctionInfoIndex = 6;
4381 static const int kWeakCellCacheIndex = 7;
4382 static const int kFirstDeoptEntryIndex = 8;
4384 // Offsets of deopt entry elements relative to the start of the entry.
4385 static const int kAstIdRawOffset = 0;
4386 static const int kTranslationIndexOffset = 1;
4387 static const int kArgumentsStackHeightOffset = 2;
4388 static const int kPcOffset = 3;
4389 static const int kDeoptEntrySize = 4;
4391 // Simple element accessors.
4392 #define DEFINE_ELEMENT_ACCESSORS(name, type) \
4394 return type::cast(get(k##name##Index)); \
4396 void Set##name(type* value) { \
4397 set(k##name##Index, value); \
4400 DEFINE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
4401 DEFINE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
4402 DEFINE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
4403 DEFINE_ELEMENT_ACCESSORS(OsrAstId, Smi)
4404 DEFINE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
4405 DEFINE_ELEMENT_ACCESSORS(OptimizationId, Smi)
4406 DEFINE_ELEMENT_ACCESSORS(SharedFunctionInfo, Object)
4407 DEFINE_ELEMENT_ACCESSORS(WeakCellCache, Object)
4409 #undef DEFINE_ELEMENT_ACCESSORS
4411 // Accessors for elements of the ith deoptimization entry.
4412 #define DEFINE_ENTRY_ACCESSORS(name, type) \
4413 type* name(int i) { \
4414 return type::cast(get(IndexForEntry(i) + k##name##Offset)); \
4416 void Set##name(int i, type* value) { \
4417 set(IndexForEntry(i) + k##name##Offset, value); \
4420 DEFINE_ENTRY_ACCESSORS(AstIdRaw, Smi)
4421 DEFINE_ENTRY_ACCESSORS(TranslationIndex, Smi)
4422 DEFINE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
4423 DEFINE_ENTRY_ACCESSORS(Pc, Smi)
4425 #undef DEFINE_DEOPT_ENTRY_ACCESSORS
4427 BailoutId AstId(int i) {
4428 return BailoutId(AstIdRaw(i)->value());
4431 void SetAstId(int i, BailoutId value) {
4432 SetAstIdRaw(i, Smi::FromInt(value.ToInt()));
4436 return (length() - kFirstDeoptEntryIndex) / kDeoptEntrySize;
4439 // Allocates a DeoptimizationInputData.
4440 static Handle<DeoptimizationInputData> New(Isolate* isolate,
4441 int deopt_entry_count,
4442 PretenureFlag pretenure);
4444 DECLARE_CAST(DeoptimizationInputData)
4446 #ifdef ENABLE_DISASSEMBLER
4447 void DeoptimizationInputDataPrint(std::ostream& os); // NOLINT
4451 static int IndexForEntry(int i) {
4452 return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
4456 static int LengthFor(int entry_count) { return IndexForEntry(entry_count); }
4460 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
4461 // data for code generated by the full compiler.
4462 // The format of the these objects is
4463 // [i * 2]: Ast ID for ith deoptimization.
4464 // [i * 2 + 1]: PC and state of ith deoptimization
4465 class DeoptimizationOutputData: public FixedArray {
4467 int DeoptPoints() { return length() / 2; }
4469 BailoutId AstId(int index) {
4470 return BailoutId(Smi::cast(get(index * 2))->value());
4473 void SetAstId(int index, BailoutId id) {
4474 set(index * 2, Smi::FromInt(id.ToInt()));
4477 Smi* PcAndState(int index) { return Smi::cast(get(1 + index * 2)); }
4478 void SetPcAndState(int index, Smi* offset) { set(1 + index * 2, offset); }
4480 static int LengthOfFixedArray(int deopt_points) {
4481 return deopt_points * 2;
4484 // Allocates a DeoptimizationOutputData.
4485 static Handle<DeoptimizationOutputData> New(Isolate* isolate,
4486 int number_of_deopt_points,
4487 PretenureFlag pretenure);
4489 DECLARE_CAST(DeoptimizationOutputData)
4491 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4492 void DeoptimizationOutputDataPrint(std::ostream& os); // NOLINT
4497 // HandlerTable is a fixed array containing entries for exception handlers in
4498 // the code object it is associated with. The tables comes in two flavors:
4499 // 1) Based on ranges: Used for unoptimized code. Contains one entry per
4500 // exception handler and a range representing the try-block covered by that
4501 // handler. Layout looks as follows:
4502 // [ range-start , range-end , handler-offset , stack-depth ]
4503 // 2) Based on return addresses: Used for turbofanned code. Contains one entry
4504 // per call-site that could throw an exception. Layout looks as follows:
4505 // [ return-address-offset , handler-offset ]
4506 class HandlerTable : public FixedArray {
4508 // Conservative prediction whether a given handler will locally catch an
4509 // exception or cause a re-throw to outside the code boundary. Since this is
4510 // undecidable it is merely an approximation (e.g. useful for debugger).
4511 enum CatchPrediction { UNCAUGHT, CAUGHT };
4513 // Accessors for handler table based on ranges.
4514 void SetRangeStart(int index, int value) {
4515 set(index * kRangeEntrySize + kRangeStartIndex, Smi::FromInt(value));
4517 void SetRangeEnd(int index, int value) {
4518 set(index * kRangeEntrySize + kRangeEndIndex, Smi::FromInt(value));
4520 void SetRangeHandler(int index, int offset, CatchPrediction prediction) {
4521 int value = HandlerOffsetField::encode(offset) |
4522 HandlerPredictionField::encode(prediction);
4523 set(index * kRangeEntrySize + kRangeHandlerIndex, Smi::FromInt(value));
4525 void SetRangeDepth(int index, int value) {
4526 set(index * kRangeEntrySize + kRangeDepthIndex, Smi::FromInt(value));
4529 // Accessors for handler table based on return addresses.
4530 void SetReturnOffset(int index, int value) {
4531 set(index * kReturnEntrySize + kReturnOffsetIndex, Smi::FromInt(value));
4533 void SetReturnHandler(int index, int offset, CatchPrediction prediction) {
4534 int value = HandlerOffsetField::encode(offset) |
4535 HandlerPredictionField::encode(prediction);
4536 set(index * kReturnEntrySize + kReturnHandlerIndex, Smi::FromInt(value));
4539 // Lookup handler in a table based on ranges.
4540 int LookupRange(int pc_offset, int* stack_depth, CatchPrediction* prediction);
4542 // Lookup handler in a table based on return addresses.
4543 int LookupReturn(int pc_offset, CatchPrediction* prediction);
4545 // Returns the required length of the underlying fixed array.
4546 static int LengthForRange(int entries) { return entries * kRangeEntrySize; }
4547 static int LengthForReturn(int entries) { return entries * kReturnEntrySize; }
4549 DECLARE_CAST(HandlerTable)
4551 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4552 void HandlerTableRangePrint(std::ostream& os); // NOLINT
4553 void HandlerTableReturnPrint(std::ostream& os); // NOLINT
4557 // Layout description for handler table based on ranges.
4558 static const int kRangeStartIndex = 0;
4559 static const int kRangeEndIndex = 1;
4560 static const int kRangeHandlerIndex = 2;
4561 static const int kRangeDepthIndex = 3;
4562 static const int kRangeEntrySize = 4;
4564 // Layout description for handler table based on return addresses.
4565 static const int kReturnOffsetIndex = 0;
4566 static const int kReturnHandlerIndex = 1;
4567 static const int kReturnEntrySize = 2;
4569 // Encoding of the {handler} field.
4570 class HandlerPredictionField : public BitField<CatchPrediction, 0, 1> {};
4571 class HandlerOffsetField : public BitField<int, 1, 30> {};
4575 // Code describes objects with on-the-fly generated machine code.
4576 class Code: public HeapObject {
4578 // Opaque data type for encapsulating code flags like kind, inline
4579 // cache state, and arguments count.
4580 typedef uint32_t Flags;
4582 #define NON_IC_KIND_LIST(V) \
4584 V(OPTIMIZED_FUNCTION) \
4590 #define IC_KIND_LIST(V) \
4601 #define CODE_KIND_LIST(V) \
4602 NON_IC_KIND_LIST(V) \
4606 #define DEFINE_CODE_KIND_ENUM(name) name,
4607 CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
4608 #undef DEFINE_CODE_KIND_ENUM
4612 // No more than 16 kinds. The value is currently encoded in four bits in
4614 STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
4616 static const char* Kind2String(Kind kind);
4624 static const int kPrologueOffsetNotSet = -1;
4626 #ifdef ENABLE_DISASSEMBLER
4628 static const char* ICState2String(InlineCacheState state);
4629 static const char* StubType2String(StubType type);
4630 static void PrintExtraICState(std::ostream& os, // NOLINT
4631 Kind kind, ExtraICState extra);
4632 void Disassemble(const char* name, std::ostream& os); // NOLINT
4633 #endif // ENABLE_DISASSEMBLER
4635 // [instruction_size]: Size of the native instructions
4636 inline int instruction_size() const;
4637 inline void set_instruction_size(int value);
4639 // [relocation_info]: Code relocation information
4640 DECL_ACCESSORS(relocation_info, ByteArray)
4641 void InvalidateRelocation();
4642 void InvalidateEmbeddedObjects();
4644 // [handler_table]: Fixed array containing offsets of exception handlers.
4645 DECL_ACCESSORS(handler_table, FixedArray)
4647 // [deoptimization_data]: Array containing data for deopt.
4648 DECL_ACCESSORS(deoptimization_data, FixedArray)
4650 // [raw_type_feedback_info]: This field stores various things, depending on
4651 // the kind of the code object.
4652 // FUNCTION => type feedback information.
4653 // STUB and ICs => major/minor key as Smi.
4654 DECL_ACCESSORS(raw_type_feedback_info, Object)
4655 inline Object* type_feedback_info();
4656 inline void set_type_feedback_info(
4657 Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
4658 inline uint32_t stub_key();
4659 inline void set_stub_key(uint32_t key);
4661 // [next_code_link]: Link for lists of optimized or deoptimized code.
4662 // Note that storage for this field is overlapped with typefeedback_info.
4663 DECL_ACCESSORS(next_code_link, Object)
4665 // [gc_metadata]: Field used to hold GC related metadata. The contents of this
4666 // field does not have to be traced during garbage collection since
4667 // it is only used by the garbage collector itself.
4668 DECL_ACCESSORS(gc_metadata, Object)
4670 // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
4671 // at the moment when this object was created.
4672 inline void set_ic_age(int count);
4673 inline int ic_age() const;
4675 // [prologue_offset]: Offset of the function prologue, used for aging
4676 // FUNCTIONs and OPTIMIZED_FUNCTIONs.
4677 inline int prologue_offset() const;
4678 inline void set_prologue_offset(int offset);
4680 // [constant_pool offset]: Offset of the constant pool.
4681 // Valid for FLAG_enable_embedded_constant_pool only
4682 inline int constant_pool_offset() const;
4683 inline void set_constant_pool_offset(int offset);
4685 // Unchecked accessors to be used during GC.
4686 inline ByteArray* unchecked_relocation_info();
4688 inline int relocation_size();
4690 // [flags]: Various code flags.
4691 inline Flags flags();
4692 inline void set_flags(Flags flags);
4694 // [flags]: Access to specific code flags.
4696 inline InlineCacheState ic_state(); // Only valid for IC stubs.
4697 inline ExtraICState extra_ic_state(); // Only valid for IC stubs.
4699 inline StubType type(); // Only valid for monomorphic IC stubs.
4701 // Testers for IC stub kinds.
4702 inline bool is_inline_cache_stub();
4703 inline bool is_debug_stub();
4704 inline bool is_handler() { return kind() == HANDLER; }
4705 inline bool is_load_stub() { return kind() == LOAD_IC; }
4706 inline bool is_keyed_load_stub() { return kind() == KEYED_LOAD_IC; }
4707 inline bool is_store_stub() { return kind() == STORE_IC; }
4708 inline bool is_keyed_store_stub() { return kind() == KEYED_STORE_IC; }
4709 inline bool is_call_stub() { return kind() == CALL_IC; }
4710 inline bool is_binary_op_stub() { return kind() == BINARY_OP_IC; }
4711 inline bool is_compare_ic_stub() { return kind() == COMPARE_IC; }
4712 inline bool is_compare_nil_ic_stub() { return kind() == COMPARE_NIL_IC; }
4713 inline bool is_to_boolean_ic_stub() { return kind() == TO_BOOLEAN_IC; }
4714 inline bool is_keyed_stub();
4715 inline bool is_optimized_code() { return kind() == OPTIMIZED_FUNCTION; }
4716 inline bool embeds_maps_weakly() {
4718 return (k == LOAD_IC || k == STORE_IC || k == KEYED_LOAD_IC ||
4719 k == KEYED_STORE_IC || k == COMPARE_NIL_IC) &&
4720 ic_state() == MONOMORPHIC;
4723 inline bool IsCodeStubOrIC();
4725 inline void set_raw_kind_specific_flags1(int value);
4726 inline void set_raw_kind_specific_flags2(int value);
4728 // [is_crankshafted]: For kind STUB or ICs, tells whether or not a code
4729 // object was generated by either the hydrogen or the TurboFan optimizing
4730 // compiler (but it may not be an optimized function).
4731 inline bool is_crankshafted();
4732 inline bool is_hydrogen_stub(); // Crankshafted, but not a function.
4733 inline void set_is_crankshafted(bool value);
4735 // [is_turbofanned]: For kind STUB or OPTIMIZED_FUNCTION, tells whether the
4736 // code object was generated by the TurboFan optimizing compiler.
4737 inline bool is_turbofanned();
4738 inline void set_is_turbofanned(bool value);
4740 // [can_have_weak_objects]: For kind OPTIMIZED_FUNCTION, tells whether the
4741 // embedded objects in code should be treated weakly.
4742 inline bool can_have_weak_objects();
4743 inline void set_can_have_weak_objects(bool value);
4745 // [has_deoptimization_support]: For FUNCTION kind, tells if it has
4746 // deoptimization support.
4747 inline bool has_deoptimization_support();
4748 inline void set_has_deoptimization_support(bool value);
4750 // [has_debug_break_slots]: For FUNCTION kind, tells if it has
4751 // been compiled with debug break slots.
4752 inline bool has_debug_break_slots();
4753 inline void set_has_debug_break_slots(bool value);
4755 // [has_reloc_info_for_serialization]: For FUNCTION kind, tells if its
4756 // reloc info includes runtime and external references to support
4757 // serialization/deserialization.
4758 inline bool has_reloc_info_for_serialization();
4759 inline void set_has_reloc_info_for_serialization(bool value);
4761 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
4762 // how long the function has been marked for OSR and therefore which
4763 // level of loop nesting we are willing to do on-stack replacement
4765 inline void set_allow_osr_at_loop_nesting_level(int level);
4766 inline int allow_osr_at_loop_nesting_level();
4768 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
4769 // the code object was seen on the stack with no IC patching going on.
4770 inline int profiler_ticks();
4771 inline void set_profiler_ticks(int ticks);
4773 // [builtin_index]: For BUILTIN kind, tells which builtin index it has.
4774 // For builtins, tells which builtin index it has.
4775 // Note that builtins can have a code kind other than BUILTIN, which means
4776 // that for arbitrary code objects, this index value may be random garbage.
4777 // To verify in that case, compare the code object to the indexed builtin.
4778 inline int builtin_index();
4779 inline void set_builtin_index(int id);
4781 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
4782 // reserved in the code prologue.
4783 inline unsigned stack_slots();
4784 inline void set_stack_slots(unsigned slots);
4786 // [safepoint_table_start]: For kind OPTIMIZED_FUNCTION, the offset in
4787 // the instruction stream where the safepoint table starts.
4788 inline unsigned safepoint_table_offset();
4789 inline void set_safepoint_table_offset(unsigned offset);
4791 // [back_edge_table_start]: For kind FUNCTION, the offset in the
4792 // instruction stream where the back edge table starts.
4793 inline unsigned back_edge_table_offset();
4794 inline void set_back_edge_table_offset(unsigned offset);
4796 inline bool back_edges_patched_for_osr();
4798 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
4799 inline uint16_t to_boolean_state();
4801 // [has_function_cache]: For kind STUB tells whether there is a function
4802 // cache is passed to the stub.
4803 inline bool has_function_cache();
4804 inline void set_has_function_cache(bool flag);
4807 // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
4808 // the code is going to be deoptimized because of dead embedded maps.
4809 inline bool marked_for_deoptimization();
4810 inline void set_marked_for_deoptimization(bool flag);
4812 // [constant_pool]: The constant pool for this function.
4813 inline Address constant_pool();
4815 // Get the safepoint entry for the given pc.
4816 SafepointEntry GetSafepointEntry(Address pc);
4818 // Find an object in a stub with a specified map
4819 Object* FindNthObject(int n, Map* match_map);
4821 // Find the first allocation site in an IC stub.
4822 AllocationSite* FindFirstAllocationSite();
4824 // Find the first map in an IC stub.
4825 Map* FindFirstMap();
4826 void FindAllMaps(MapHandleList* maps);
4828 // Find the first handler in an IC stub.
4829 Code* FindFirstHandler();
4831 // Find |length| handlers and put them into |code_list|. Returns false if not
4832 // enough handlers can be found.
4833 bool FindHandlers(CodeHandleList* code_list, int length = -1);
4835 // Find the handler for |map|.
4836 MaybeHandle<Code> FindHandlerForMap(Map* map);
4838 // Find the first name in an IC stub.
4839 Name* FindFirstName();
4841 class FindAndReplacePattern;
4842 // For each (map-to-find, object-to-replace) pair in the pattern, this
4843 // function replaces the corresponding placeholder in the code with the
4844 // object-to-replace. The function assumes that pairs in the pattern come in
4845 // the same order as the placeholders in the code.
4846 // If the placeholder is a weak cell, then the value of weak cell is matched
4847 // against the map-to-find.
4848 void FindAndReplace(const FindAndReplacePattern& pattern);
4850 // The entire code object including its header is copied verbatim to the
4851 // snapshot so that it can be written in one, fast, memcpy during
4852 // deserialization. The deserializer will overwrite some pointers, rather
4853 // like a runtime linker, but the random allocation addresses used in the
4854 // mksnapshot process would still be present in the unlinked snapshot data,
4855 // which would make snapshot production non-reproducible. This method wipes
4856 // out the to-be-overwritten header data for reproducible snapshots.
4857 inline void WipeOutHeader();
4859 // Flags operations.
4860 static inline Flags ComputeFlags(
4861 Kind kind, InlineCacheState ic_state = UNINITIALIZED,
4862 ExtraICState extra_ic_state = kNoExtraICState, StubType type = NORMAL,
4863 CacheHolderFlag holder = kCacheOnReceiver);
4865 static inline Flags ComputeMonomorphicFlags(
4866 Kind kind, ExtraICState extra_ic_state = kNoExtraICState,
4867 CacheHolderFlag holder = kCacheOnReceiver, StubType type = NORMAL);
4869 static inline Flags ComputeHandlerFlags(
4870 Kind handler_kind, StubType type = NORMAL,
4871 CacheHolderFlag holder = kCacheOnReceiver);
4873 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
4874 static inline StubType ExtractTypeFromFlags(Flags flags);
4875 static inline CacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
4876 static inline Kind ExtractKindFromFlags(Flags flags);
4877 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
4879 static inline Flags RemoveTypeFromFlags(Flags flags);
4880 static inline Flags RemoveTypeAndHolderFromFlags(Flags flags);
4882 // Convert a target address into a code object.
4883 static inline Code* GetCodeFromTargetAddress(Address address);
4885 // Convert an entry address into an object.
4886 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
4888 // Returns the address of the first instruction.
4889 inline byte* instruction_start();
4891 // Returns the address right after the last instruction.
4892 inline byte* instruction_end();
4894 // Returns the size of the instructions, padding, and relocation information.
4895 inline int body_size();
4897 // Returns the address of the first relocation info (read backwards!).
4898 inline byte* relocation_start();
4900 // Code entry point.
4901 inline byte* entry();
4903 // Returns true if pc is inside this object's instructions.
4904 inline bool contains(byte* pc);
4906 // Relocate the code by delta bytes. Called to signal that this code
4907 // object has been moved by delta bytes.
4908 void Relocate(intptr_t delta);
4910 // Migrate code described by desc.
4911 void CopyFrom(const CodeDesc& desc);
4913 // Returns the object size for a given body (used for allocation).
4914 static int SizeFor(int body_size) {
4915 DCHECK_SIZE_TAG_ALIGNED(body_size);
4916 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
4919 // Calculate the size of the code object to report for log events. This takes
4920 // the layout of the code object into account.
4921 int ExecutableSize() {
4922 // Check that the assumptions about the layout of the code object holds.
4923 DCHECK_EQ(static_cast<int>(instruction_start() - address()),
4925 return instruction_size() + Code::kHeaderSize;
4928 // Locating source position.
4929 int SourcePosition(Address pc);
4930 int SourceStatementPosition(Address pc);
4934 // Dispatched behavior.
4935 int CodeSize() { return SizeFor(body_size()); }
4936 inline void CodeIterateBody(ObjectVisitor* v);
4938 template<typename StaticVisitor>
4939 inline void CodeIterateBody(Heap* heap);
4941 DECLARE_PRINTER(Code)
4942 DECLARE_VERIFIER(Code)
4944 void ClearInlineCaches();
4945 void ClearInlineCaches(Kind kind);
4947 BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
4948 uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
4950 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
4952 kToBeExecutedOnceCodeAge = -3,
4953 kNotExecutedCodeAge = -2,
4954 kExecutedOnceCodeAge = -1,
4956 CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
4958 kFirstCodeAge = kToBeExecutedOnceCodeAge,
4959 kLastCodeAge = kAfterLastCodeAge - 1,
4960 kCodeAgeCount = kAfterLastCodeAge - kFirstCodeAge - 1,
4961 kIsOldCodeAge = kSexagenarianCodeAge,
4962 kPreAgedCodeAge = kIsOldCodeAge - 1
4964 #undef DECLARE_CODE_AGE_ENUM
4966 // Code aging. Indicates how many full GCs this code has survived without
4967 // being entered through the prologue. Used to determine when it is
4968 // relatively safe to flush this code object and replace it with the lazy
4969 // compilation stub.
4970 static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
4971 static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
4972 void MakeYoung(Isolate* isolate);
4973 void MarkToBeExecutedOnce(Isolate* isolate);
4974 void MakeOlder(MarkingParity);
4975 static bool IsYoungSequence(Isolate* isolate, byte* sequence);
4978 static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
4979 return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
4982 void PrintDeoptLocation(FILE* out, Address pc);
4983 bool CanDeoptAt(Address pc);
4986 void VerifyEmbeddedObjectsDependency();
4990 enum VerifyMode { kNoContextSpecificPointers, kNoContextRetainingPointers };
4991 void VerifyEmbeddedObjects(VerifyMode mode = kNoContextRetainingPointers);
4994 inline bool CanContainWeakObjects() {
4995 // is_turbofanned() implies !can_have_weak_objects().
4996 DCHECK(!is_optimized_code() || !is_turbofanned() ||
4997 !can_have_weak_objects());
4998 return is_optimized_code() && can_have_weak_objects();
5001 inline bool IsWeakObject(Object* object) {
5002 return (CanContainWeakObjects() && IsWeakObjectInOptimizedCode(object));
5005 static inline bool IsWeakObjectInOptimizedCode(Object* object);
5007 static Handle<WeakCell> WeakCellFor(Handle<Code> code);
5008 WeakCell* CachedWeakCell();
5010 // Max loop nesting marker used to postpose OSR. We don't take loop
5011 // nesting that is deeper than 5 levels into account.
5012 static const int kMaxLoopNestingMarker = 6;
5014 static const int kConstantPoolSize =
5015 FLAG_enable_embedded_constant_pool ? kIntSize : 0;
5017 // Layout description.
5018 static const int kRelocationInfoOffset = HeapObject::kHeaderSize;
5019 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
5020 static const int kDeoptimizationDataOffset =
5021 kHandlerTableOffset + kPointerSize;
5022 // For FUNCTION kind, we store the type feedback info here.
5023 static const int kTypeFeedbackInfoOffset =
5024 kDeoptimizationDataOffset + kPointerSize;
5025 static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
5026 static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
5027 static const int kInstructionSizeOffset = kGCMetadataOffset + kPointerSize;
5028 static const int kICAgeOffset = kInstructionSizeOffset + kIntSize;
5029 static const int kFlagsOffset = kICAgeOffset + kIntSize;
5030 static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
5031 static const int kKindSpecificFlags2Offset =
5032 kKindSpecificFlags1Offset + kIntSize;
5033 // Note: We might be able to squeeze this into the flags above.
5034 static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
5035 static const int kConstantPoolOffset = kPrologueOffset + kIntSize;
5036 static const int kHeaderPaddingStart =
5037 kConstantPoolOffset + kConstantPoolSize;
5039 // Add padding to align the instruction start following right after
5040 // the Code object header.
5041 static const int kHeaderSize =
5042 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
5044 // Byte offsets within kKindSpecificFlags1Offset.
5045 static const int kFullCodeFlags = kKindSpecificFlags1Offset;
5046 class FullCodeFlagsHasDeoptimizationSupportField:
5047 public BitField<bool, 0, 1> {}; // NOLINT
5048 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
5049 class FullCodeFlagsHasRelocInfoForSerialization
5050 : public BitField<bool, 2, 1> {};
5051 // Bit 3 in this bitfield is unused.
5052 class ProfilerTicksField : public BitField<int, 4, 28> {};
5054 // Flags layout. BitField<type, shift, size>.
5055 class ICStateField : public BitField<InlineCacheState, 0, 4> {};
5056 class TypeField : public BitField<StubType, 4, 1> {};
5057 class CacheHolderField : public BitField<CacheHolderFlag, 5, 2> {};
5058 class KindField : public BitField<Kind, 7, 4> {};
5059 class ExtraICStateField: public BitField<ExtraICState, 11,
5060 PlatformSmiTagging::kSmiValueSize - 11 + 1> {}; // NOLINT
5062 // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
5063 static const int kStackSlotsFirstBit = 0;
5064 static const int kStackSlotsBitCount = 24;
5065 static const int kHasFunctionCacheBit =
5066 kStackSlotsFirstBit + kStackSlotsBitCount;
5067 static const int kMarkedForDeoptimizationBit = kHasFunctionCacheBit + 1;
5068 static const int kIsTurbofannedBit = kMarkedForDeoptimizationBit + 1;
5069 static const int kCanHaveWeakObjects = kIsTurbofannedBit + 1;
5071 STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
5072 STATIC_ASSERT(kCanHaveWeakObjects + 1 <= 32);
5074 class StackSlotsField: public BitField<int,
5075 kStackSlotsFirstBit, kStackSlotsBitCount> {}; // NOLINT
5076 class HasFunctionCacheField : public BitField<bool, kHasFunctionCacheBit, 1> {
5078 class MarkedForDeoptimizationField
5079 : public BitField<bool, kMarkedForDeoptimizationBit, 1> {}; // NOLINT
5080 class IsTurbofannedField : public BitField<bool, kIsTurbofannedBit, 1> {
5082 class CanHaveWeakObjectsField
5083 : public BitField<bool, kCanHaveWeakObjects, 1> {}; // NOLINT
5085 // KindSpecificFlags2 layout (ALL)
5086 static const int kIsCrankshaftedBit = 0;
5087 class IsCrankshaftedField: public BitField<bool,
5088 kIsCrankshaftedBit, 1> {}; // NOLINT
5090 // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
5091 static const int kSafepointTableOffsetFirstBit = kIsCrankshaftedBit + 1;
5092 static const int kSafepointTableOffsetBitCount = 24;
5094 STATIC_ASSERT(kSafepointTableOffsetFirstBit +
5095 kSafepointTableOffsetBitCount <= 32);
5096 STATIC_ASSERT(1 + kSafepointTableOffsetBitCount <= 32);
5098 class SafepointTableOffsetField: public BitField<int,
5099 kSafepointTableOffsetFirstBit,
5100 kSafepointTableOffsetBitCount> {}; // NOLINT
5102 // KindSpecificFlags2 layout (FUNCTION)
5103 class BackEdgeTableOffsetField: public BitField<int,
5104 kIsCrankshaftedBit + 1, 27> {}; // NOLINT
5105 class AllowOSRAtLoopNestingLevelField: public BitField<int,
5106 kIsCrankshaftedBit + 1 + 27, 4> {}; // NOLINT
5107 STATIC_ASSERT(AllowOSRAtLoopNestingLevelField::kMax >= kMaxLoopNestingMarker);
5109 static const int kArgumentsBits = 16;
5110 static const int kMaxArguments = (1 << kArgumentsBits) - 1;
5112 // This constant should be encodable in an ARM instruction.
5113 static const int kFlagsNotUsedInLookup =
5114 TypeField::kMask | CacheHolderField::kMask;
5117 friend class RelocIterator;
5118 friend class Deoptimizer; // For FindCodeAgeSequence.
5120 void ClearInlineCaches(Kind* kind);
5123 byte* FindCodeAgeSequence();
5124 static void GetCodeAgeAndParity(Code* code, Age* age,
5125 MarkingParity* parity);
5126 static void GetCodeAgeAndParity(Isolate* isolate, byte* sequence, Age* age,
5127 MarkingParity* parity);
5128 static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
5130 // Code aging -- platform-specific
5131 static void PatchPlatformCodeAge(Isolate* isolate,
5132 byte* sequence, Age age,
5133 MarkingParity parity);
5135 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5139 // This class describes the layout of dependent codes array of a map. The
5140 // array is partitioned into several groups of dependent codes. Each group
5141 // contains codes with the same dependency on the map. The array has the
5142 // following layout for n dependency groups:
5144 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5145 // | C1 | C2 | ... | Cn | group 1 | group 2 | ... | group n | undefined |
5146 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5148 // The first n elements are Smis, each of them specifies the number of codes
5149 // in the corresponding group. The subsequent elements contain grouped code
5150 // objects in weak cells. The suffix of the array can be filled with the
5151 // undefined value if the number of codes is less than the length of the
5152 // array. The order of the code objects within a group is not preserved.
5154 // All code indexes used in the class are counted starting from the first
5155 // code object of the first group. In other words, code index 0 corresponds
5156 // to array index n = kCodesStartIndex.
5158 class DependentCode: public FixedArray {
5160 enum DependencyGroup {
5161 // Group of code that weakly embed this map and depend on being
5162 // deoptimized when the map is garbage collected.
5164 // Group of code that embed a transition to this map, and depend on being
5165 // deoptimized when the transition is replaced by a new version.
5167 // Group of code that omit run-time prototype checks for prototypes
5168 // described by this map. The group is deoptimized whenever an object
5169 // described by this map changes shape (and transitions to a new map),
5170 // possibly invalidating the assumptions embedded in the code.
5171 kPrototypeCheckGroup,
5172 // Group of code that depends on global property values in property cells
5173 // not being changed.
5174 kPropertyCellChangedGroup,
5175 // Group of code that omit run-time type checks for the field(s) introduced
5178 // Group of code that omit run-time type checks for initial maps of
5180 kInitialMapChangedGroup,
5181 // Group of code that depends on tenuring information in AllocationSites
5182 // not being changed.
5183 kAllocationSiteTenuringChangedGroup,
5184 // Group of code that depends on element transition information in
5185 // AllocationSites not being changed.
5186 kAllocationSiteTransitionChangedGroup
5189 static const int kGroupCount = kAllocationSiteTransitionChangedGroup + 1;
5191 // Array for holding the index of the first code object of each group.
5192 // The last element stores the total number of code objects.
5193 class GroupStartIndexes {
5195 explicit GroupStartIndexes(DependentCode* entries);
5196 void Recompute(DependentCode* entries);
5197 int at(int i) { return start_indexes_[i]; }
5198 int number_of_entries() { return start_indexes_[kGroupCount]; }
5200 int start_indexes_[kGroupCount + 1];
5203 bool Contains(DependencyGroup group, WeakCell* code_cell);
5205 static Handle<DependentCode> InsertCompilationDependencies(
5206 Handle<DependentCode> entries, DependencyGroup group,
5207 Handle<Foreign> info);
5209 static Handle<DependentCode> InsertWeakCode(Handle<DependentCode> entries,
5210 DependencyGroup group,
5211 Handle<WeakCell> code_cell);
5213 void UpdateToFinishedCode(DependencyGroup group, Foreign* info,
5214 WeakCell* code_cell);
5216 void RemoveCompilationDependencies(DependentCode::DependencyGroup group,
5219 void DeoptimizeDependentCodeGroup(Isolate* isolate,
5220 DependentCode::DependencyGroup group);
5222 bool MarkCodeForDeoptimization(Isolate* isolate,
5223 DependentCode::DependencyGroup group);
5225 // The following low-level accessors should only be used by this class
5226 // and the mark compact collector.
5227 inline int number_of_entries(DependencyGroup group);
5228 inline void set_number_of_entries(DependencyGroup group, int value);
5229 inline Object* object_at(int i);
5230 inline void set_object_at(int i, Object* object);
5231 inline void clear_at(int i);
5232 inline void copy(int from, int to);
5233 DECLARE_CAST(DependentCode)
5235 static const char* DependencyGroupName(DependencyGroup group);
5236 static void SetMarkedForDeoptimization(Code* code, DependencyGroup group);
5239 static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5240 DependencyGroup group,
5241 Handle<Object> object);
5242 static Handle<DependentCode> EnsureSpace(Handle<DependentCode> entries);
5243 // Make a room at the end of the given group by moving out the first
5244 // code objects of the subsequent groups.
5245 inline void ExtendGroup(DependencyGroup group);
5246 // Compact by removing cleared weak cells and return true if there was
5247 // any cleared weak cell.
5249 static int Grow(int number_of_entries) {
5250 if (number_of_entries < 5) return number_of_entries + 1;
5251 return number_of_entries * 5 / 4;
5253 static const int kCodesStartIndex = kGroupCount;
5257 class PrototypeInfo;
5260 // All heap objects have a Map that describes their structure.
5261 // A Map contains information about:
5262 // - Size information about the object
5263 // - How to iterate over an object (for garbage collection)
5264 class Map: public HeapObject {
5267 // Size in bytes or kVariableSizeSentinel if instances do not have
5269 inline int instance_size();
5270 inline void set_instance_size(int value);
5272 // Only to clear an unused byte, remove once byte is used.
5273 inline void clear_unused();
5275 // Count of properties allocated in the object.
5276 inline int inobject_properties();
5277 inline void set_inobject_properties(int value);
5280 inline InstanceType instance_type();
5281 inline void set_instance_type(InstanceType value);
5283 // Tells how many unused property fields are available in the
5284 // instance (only used for JSObject in fast mode).
5285 inline int unused_property_fields();
5286 inline void set_unused_property_fields(int value);
5289 inline byte bit_field() const;
5290 inline void set_bit_field(byte value);
5293 inline byte bit_field2() const;
5294 inline void set_bit_field2(byte value);
5297 inline uint32_t bit_field3() const;
5298 inline void set_bit_field3(uint32_t bits);
5300 class EnumLengthBits: public BitField<int,
5301 0, kDescriptorIndexBitCount> {}; // NOLINT
5302 class NumberOfOwnDescriptorsBits: public BitField<int,
5303 kDescriptorIndexBitCount, kDescriptorIndexBitCount> {}; // NOLINT
5304 STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
5305 class DictionaryMap : public BitField<bool, 20, 1> {};
5306 class OwnsDescriptors : public BitField<bool, 21, 1> {};
5307 class HasInstanceCallHandler : public BitField<bool, 22, 1> {};
5308 class Deprecated : public BitField<bool, 23, 1> {};
5309 class IsUnstable : public BitField<bool, 24, 1> {};
5310 class IsMigrationTarget : public BitField<bool, 25, 1> {};
5311 class IsStrong : public BitField<bool, 26, 1> {};
5314 // Keep this bit field at the very end for better code in
5315 // Builtins::kJSConstructStubGeneric stub.
5316 // This counter is used for in-object slack tracking and for map aging.
5317 // The in-object slack tracking is considered enabled when the counter is
5318 // in the range [kSlackTrackingCounterStart, kSlackTrackingCounterEnd].
5319 class Counter : public BitField<int, 28, 4> {};
5320 static const int kSlackTrackingCounterStart = 14;
5321 static const int kSlackTrackingCounterEnd = 8;
5322 static const int kRetainingCounterStart = kSlackTrackingCounterEnd - 1;
5323 static const int kRetainingCounterEnd = 0;
5325 // Tells whether the object in the prototype property will be used
5326 // for instances created from this function. If the prototype
5327 // property is set to a value that is not a JSObject, the prototype
5328 // property will not be used to create instances of the function.
5329 // See ECMA-262, 13.2.2.
5330 inline void set_non_instance_prototype(bool value);
5331 inline bool has_non_instance_prototype();
5333 // Tells whether function has special prototype property. If not, prototype
5334 // property will not be created when accessed (will return undefined),
5335 // and construction from this function will not be allowed.
5336 inline void set_function_with_prototype(bool value);
5337 inline bool function_with_prototype();
5339 // Tells whether the instance with this map should be ignored by the
5340 // Object.getPrototypeOf() function and the __proto__ accessor.
5341 inline void set_is_hidden_prototype() {
5342 set_bit_field(bit_field() | (1 << kIsHiddenPrototype));
5345 inline bool is_hidden_prototype() {
5346 return ((1 << kIsHiddenPrototype) & bit_field()) != 0;
5349 // Records and queries whether the instance has a named interceptor.
5350 inline void set_has_named_interceptor() {
5351 set_bit_field(bit_field() | (1 << kHasNamedInterceptor));
5354 inline bool has_named_interceptor() {
5355 return ((1 << kHasNamedInterceptor) & bit_field()) != 0;
5358 // Records and queries whether the instance has an indexed interceptor.
5359 inline void set_has_indexed_interceptor() {
5360 set_bit_field(bit_field() | (1 << kHasIndexedInterceptor));
5363 inline bool has_indexed_interceptor() {
5364 return ((1 << kHasIndexedInterceptor) & bit_field()) != 0;
5367 // Tells whether the instance is undetectable.
5368 // An undetectable object is a special class of JSObject: 'typeof' operator
5369 // returns undefined, ToBoolean returns false. Otherwise it behaves like
5370 // a normal JS object. It is useful for implementing undetectable
5371 // document.all in Firefox & Safari.
5372 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
5373 inline void set_is_undetectable() {
5374 set_bit_field(bit_field() | (1 << kIsUndetectable));
5377 inline bool is_undetectable() {
5378 return ((1 << kIsUndetectable) & bit_field()) != 0;
5381 // Tells whether the instance has a call-as-function handler.
5382 inline void set_is_observed() {
5383 set_bit_field(bit_field() | (1 << kIsObserved));
5386 inline bool is_observed() {
5387 return ((1 << kIsObserved) & bit_field()) != 0;
5390 inline void set_is_strong();
5391 inline bool is_strong();
5392 inline void set_is_extensible(bool value);
5393 inline bool is_extensible();
5394 inline void set_is_prototype_map(bool value);
5395 inline bool is_prototype_map() const;
5397 inline void set_elements_kind(ElementsKind elements_kind) {
5398 DCHECK(static_cast<int>(elements_kind) < kElementsKindCount);
5399 DCHECK(kElementsKindCount <= (1 << Map::ElementsKindBits::kSize));
5400 set_bit_field2(Map::ElementsKindBits::update(bit_field2(), elements_kind));
5401 DCHECK(this->elements_kind() == elements_kind);
5404 inline ElementsKind elements_kind() {
5405 return Map::ElementsKindBits::decode(bit_field2());
5408 // Tells whether the instance has fast elements that are only Smis.
5409 inline bool has_fast_smi_elements() {
5410 return IsFastSmiElementsKind(elements_kind());
5413 // Tells whether the instance has fast elements.
5414 inline bool has_fast_object_elements() {
5415 return IsFastObjectElementsKind(elements_kind());
5418 inline bool has_fast_smi_or_object_elements() {
5419 return IsFastSmiOrObjectElementsKind(elements_kind());
5422 inline bool has_fast_double_elements() {
5423 return IsFastDoubleElementsKind(elements_kind());
5426 inline bool has_fast_elements() {
5427 return IsFastElementsKind(elements_kind());
5430 inline bool has_sloppy_arguments_elements() {
5431 return IsSloppyArgumentsElements(elements_kind());
5434 inline bool has_fixed_typed_array_elements() {
5435 return IsFixedTypedArrayElementsKind(elements_kind());
5438 inline bool has_dictionary_elements() {
5439 return IsDictionaryElementsKind(elements_kind());
5442 static bool IsValidElementsTransition(ElementsKind from_kind,
5443 ElementsKind to_kind);
5445 // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
5446 // map with DICTIONARY_ELEMENTS was found in the prototype chain.
5447 bool DictionaryElementsInPrototypeChainOnly();
5449 inline Map* ElementsTransitionMap();
5451 inline FixedArrayBase* GetInitialElements();
5453 // [raw_transitions]: Provides access to the transitions storage field.
5454 // Don't call set_raw_transitions() directly to overwrite transitions, use
5455 // the TransitionArray::ReplaceTransitions() wrapper instead!
5456 DECL_ACCESSORS(raw_transitions, Object)
5457 // [prototype_info]: Per-prototype metadata. Aliased with transitions
5458 // (which prototype maps don't have).
5459 DECL_ACCESSORS(prototype_info, Object)
5460 // PrototypeInfo is created lazily using this helper (which installs it on
5461 // the given prototype's map).
5462 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5463 Handle<JSObject> prototype, Isolate* isolate);
5465 // [prototype chain validity cell]: Associated with a prototype object,
5466 // stored in that object's map's PrototypeInfo, indicates that prototype
5467 // chains through this object are currently valid. The cell will be
5468 // invalidated and replaced when the prototype chain changes.
5469 static Handle<Cell> GetOrCreatePrototypeChainValidityCell(Handle<Map> map,
5471 static const int kPrototypeChainValid = 0;
5472 static const int kPrototypeChainInvalid = 1;
5475 Map* FindFieldOwner(int descriptor);
5477 inline int GetInObjectPropertyOffset(int index);
5479 int NumberOfFields();
5481 // TODO(ishell): candidate with JSObject::MigrateToMap().
5482 bool InstancesNeedRewriting(Map* target, int target_number_of_fields,
5483 int target_inobject, int target_unused,
5484 int* old_number_of_fields);
5485 // TODO(ishell): moveit!
5486 static Handle<Map> GeneralizeAllFieldRepresentations(Handle<Map> map);
5487 MUST_USE_RESULT static Handle<HeapType> GeneralizeFieldType(
5488 Handle<HeapType> type1,
5489 Handle<HeapType> type2,
5491 static void GeneralizeFieldType(Handle<Map> map, int modify_index,
5492 Representation new_representation,
5493 Handle<HeapType> new_field_type);
5494 static Handle<Map> ReconfigureProperty(Handle<Map> map, int modify_index,
5495 PropertyKind new_kind,
5496 PropertyAttributes new_attributes,
5497 Representation new_representation,
5498 Handle<HeapType> new_field_type,
5499 StoreMode store_mode);
5500 static Handle<Map> CopyGeneralizeAllRepresentations(
5501 Handle<Map> map, int modify_index, StoreMode store_mode,
5502 PropertyKind kind, PropertyAttributes attributes, const char* reason);
5504 static Handle<Map> PrepareForDataProperty(Handle<Map> old_map,
5505 int descriptor_number,
5506 Handle<Object> value);
5508 static Handle<Map> Normalize(Handle<Map> map, PropertyNormalizationMode mode,
5509 const char* reason);
5511 // Returns the constructor name (the name (possibly, inferred name) of the
5512 // function that was used to instantiate the object).
5513 String* constructor_name();
5515 // Tells whether the map is used for JSObjects in dictionary mode (ie
5516 // normalized objects, ie objects for which HasFastProperties returns false).
5517 // A map can never be used for both dictionary mode and fast mode JSObjects.
5518 // False by default and for HeapObjects that are not JSObjects.
5519 inline void set_dictionary_map(bool value);
5520 inline bool is_dictionary_map();
5522 // Tells whether the instance needs security checks when accessing its
5524 inline void set_is_access_check_needed(bool access_check_needed);
5525 inline bool is_access_check_needed();
5527 // Returns true if map has a non-empty stub code cache.
5528 inline bool has_code_cache();
5530 // [prototype]: implicit prototype object.
5531 DECL_ACCESSORS(prototype, Object)
5532 // TODO(jkummerow): make set_prototype private.
5533 static void SetPrototype(
5534 Handle<Map> map, Handle<Object> prototype,
5535 PrototypeOptimizationMode proto_mode = FAST_PROTOTYPE);
5537 // [constructor]: points back to the function responsible for this map.
5538 // The field overlaps with the back pointer. All maps in a transition tree
5539 // have the same constructor, so maps with back pointers can walk the
5540 // back pointer chain until they find the map holding their constructor.
5541 DECL_ACCESSORS(constructor_or_backpointer, Object)
5542 inline Object* GetConstructor() const;
5543 inline void SetConstructor(Object* constructor,
5544 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5545 // [back pointer]: points back to the parent map from which a transition
5546 // leads to this map. The field overlaps with the constructor (see above).
5547 inline Object* GetBackPointer();
5548 inline void SetBackPointer(Object* value,
5549 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5551 // [instance descriptors]: describes the object.
5552 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
5554 // [layout descriptor]: describes the object layout.
5555 DECL_ACCESSORS(layout_descriptor, LayoutDescriptor)
5556 // |layout descriptor| accessor which can be used from GC.
5557 inline LayoutDescriptor* layout_descriptor_gc_safe();
5558 inline bool HasFastPointerLayout() const;
5560 // |layout descriptor| accessor that is safe to call even when
5561 // FLAG_unbox_double_fields is disabled (in this case Map does not contain
5562 // |layout_descriptor| field at all).
5563 inline LayoutDescriptor* GetLayoutDescriptor();
5565 inline void UpdateDescriptors(DescriptorArray* descriptors,
5566 LayoutDescriptor* layout_descriptor);
5567 inline void InitializeDescriptors(DescriptorArray* descriptors,
5568 LayoutDescriptor* layout_descriptor);
5570 // [stub cache]: contains stubs compiled for this map.
5571 DECL_ACCESSORS(code_cache, Object)
5573 // [dependent code]: list of optimized codes that weakly embed this map.
5574 DECL_ACCESSORS(dependent_code, DependentCode)
5576 // [weak cell cache]: cache that stores a weak cell pointing to this map.
5577 DECL_ACCESSORS(weak_cell_cache, Object)
5579 inline PropertyDetails GetLastDescriptorDetails();
5582 int number_of_own_descriptors = NumberOfOwnDescriptors();
5583 DCHECK(number_of_own_descriptors > 0);
5584 return number_of_own_descriptors - 1;
5587 int NumberOfOwnDescriptors() {
5588 return NumberOfOwnDescriptorsBits::decode(bit_field3());
5591 void SetNumberOfOwnDescriptors(int number) {
5592 DCHECK(number <= instance_descriptors()->number_of_descriptors());
5593 set_bit_field3(NumberOfOwnDescriptorsBits::update(bit_field3(), number));
5596 inline Cell* RetrieveDescriptorsPointer();
5599 return EnumLengthBits::decode(bit_field3());
5602 void SetEnumLength(int length) {
5603 if (length != kInvalidEnumCacheSentinel) {
5604 DCHECK(length >= 0);
5605 DCHECK(length == 0 || instance_descriptors()->HasEnumCache());
5606 DCHECK(length <= NumberOfOwnDescriptors());
5608 set_bit_field3(EnumLengthBits::update(bit_field3(), length));
5611 inline bool owns_descriptors();
5612 inline void set_owns_descriptors(bool owns_descriptors);
5613 inline bool has_instance_call_handler();
5614 inline void set_has_instance_call_handler();
5615 inline void mark_unstable();
5616 inline bool is_stable();
5617 inline void set_migration_target(bool value);
5618 inline bool is_migration_target();
5619 inline void set_counter(int value);
5620 inline int counter();
5621 inline void deprecate();
5622 inline bool is_deprecated();
5623 inline bool CanBeDeprecated();
5624 // Returns a non-deprecated version of the input. If the input was not
5625 // deprecated, it is directly returned. Otherwise, the non-deprecated version
5626 // is found by re-transitioning from the root of the transition tree using the
5627 // descriptor array of the map. Returns MaybeHandle<Map>() if no updated map
5629 static MaybeHandle<Map> TryUpdate(Handle<Map> map) WARN_UNUSED_RESULT;
5631 // Returns a non-deprecated version of the input. This method may deprecate
5632 // existing maps along the way if encodings conflict. Not for use while
5633 // gathering type feedback. Use TryUpdate in those cases instead.
5634 static Handle<Map> Update(Handle<Map> map);
5636 static Handle<Map> CopyDropDescriptors(Handle<Map> map);
5637 static Handle<Map> CopyInsertDescriptor(Handle<Map> map,
5638 Descriptor* descriptor,
5639 TransitionFlag flag);
5641 MUST_USE_RESULT static MaybeHandle<Map> CopyWithField(
5644 Handle<HeapType> type,
5645 PropertyAttributes attributes,
5646 Representation representation,
5647 TransitionFlag flag);
5649 MUST_USE_RESULT static MaybeHandle<Map> CopyWithConstant(
5652 Handle<Object> constant,
5653 PropertyAttributes attributes,
5654 TransitionFlag flag);
5656 // Returns a new map with all transitions dropped from the given map and
5657 // the ElementsKind set.
5658 static Handle<Map> TransitionElementsTo(Handle<Map> map,
5659 ElementsKind to_kind);
5661 static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
5663 static Handle<Map> CopyAsElementsKind(Handle<Map> map,
5665 TransitionFlag flag);
5667 static Handle<Map> CopyForObserved(Handle<Map> map);
5669 static Handle<Map> CopyForPreventExtensions(Handle<Map> map,
5670 PropertyAttributes attrs_to_add,
5671 Handle<Symbol> transition_marker,
5672 const char* reason);
5674 static Handle<Map> FixProxy(Handle<Map> map, InstanceType type, int size);
5677 // Maximal number of fast properties. Used to restrict the number of map
5678 // transitions to avoid an explosion in the number of maps for objects used as
5680 inline bool TooManyFastProperties(StoreFromKeyed store_mode);
5681 static Handle<Map> TransitionToDataProperty(Handle<Map> map,
5683 Handle<Object> value,
5684 PropertyAttributes attributes,
5685 StoreFromKeyed store_mode);
5686 static Handle<Map> TransitionToAccessorProperty(
5687 Handle<Map> map, Handle<Name> name, AccessorComponent component,
5688 Handle<Object> accessor, PropertyAttributes attributes);
5689 static Handle<Map> ReconfigureExistingProperty(Handle<Map> map,
5692 PropertyAttributes attributes);
5694 inline void AppendDescriptor(Descriptor* desc);
5696 // Returns a copy of the map, prepared for inserting into the transition
5697 // tree (if the |map| owns descriptors then the new one will share
5698 // descriptors with |map|).
5699 static Handle<Map> CopyForTransition(Handle<Map> map, const char* reason);
5701 // Returns a copy of the map, with all transitions dropped from the
5702 // instance descriptors.
5703 static Handle<Map> Copy(Handle<Map> map, const char* reason);
5704 static Handle<Map> Create(Isolate* isolate, int inobject_properties);
5706 // Returns the next free property index (only valid for FAST MODE).
5707 int NextFreePropertyIndex();
5709 // Returns the number of properties described in instance_descriptors
5710 // filtering out properties with the specified attributes.
5711 int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
5712 PropertyAttributes filter = NONE);
5716 // Code cache operations.
5718 // Clears the code cache.
5719 inline void ClearCodeCache(Heap* heap);
5721 // Update code cache.
5722 static void UpdateCodeCache(Handle<Map> map,
5726 // Extend the descriptor array of the map with the list of descriptors.
5727 // In case of duplicates, the latest descriptor is used.
5728 static void AppendCallbackDescriptors(Handle<Map> map,
5729 Handle<Object> descriptors);
5731 static inline int SlackForArraySize(int old_size, int size_limit);
5733 static void EnsureDescriptorSlack(Handle<Map> map, int slack);
5735 // Returns the found code or undefined if absent.
5736 Object* FindInCodeCache(Name* name, Code::Flags flags);
5738 // Returns the non-negative index of the code object if it is in the
5739 // cache and -1 otherwise.
5740 int IndexInCodeCache(Object* name, Code* code);
5742 // Removes a code object from the code cache at the given index.
5743 void RemoveFromCodeCache(Name* name, Code* code, int index);
5745 // Computes a hash value for this map, to be used in HashTables and such.
5748 // Returns the map that this map transitions to if its elements_kind
5749 // is changed to |elements_kind|, or NULL if no such map is cached yet.
5750 // |safe_to_add_transitions| is set to false if adding transitions is not
5752 Map* LookupElementsTransitionMap(ElementsKind elements_kind);
5754 // Returns the transitioned map for this map with the most generic
5755 // elements_kind that's found in |candidates|, or null handle if no match is
5757 static Handle<Map> FindTransitionedMap(Handle<Map> map,
5758 MapHandleList* candidates);
5760 bool CanTransition() {
5761 // Only JSObject and subtypes have map transitions and back pointers.
5762 STATIC_ASSERT(LAST_TYPE == LAST_JS_OBJECT_TYPE);
5763 return instance_type() >= FIRST_JS_OBJECT_TYPE;
5766 bool IsJSObjectMap() {
5767 return instance_type() >= FIRST_JS_OBJECT_TYPE;
5769 bool IsJSArrayMap() { return instance_type() == JS_ARRAY_TYPE; }
5770 bool IsStringMap() { return instance_type() < FIRST_NONSTRING_TYPE; }
5771 bool IsJSProxyMap() {
5772 InstanceType type = instance_type();
5773 return FIRST_JS_PROXY_TYPE <= type && type <= LAST_JS_PROXY_TYPE;
5775 bool IsJSGlobalProxyMap() {
5776 return instance_type() == JS_GLOBAL_PROXY_TYPE;
5778 bool IsJSGlobalObjectMap() {
5779 return instance_type() == JS_GLOBAL_OBJECT_TYPE;
5781 bool IsGlobalObjectMap() {
5782 const InstanceType type = instance_type();
5783 return type == JS_GLOBAL_OBJECT_TYPE || type == JS_BUILTINS_OBJECT_TYPE;
5786 inline bool CanOmitMapChecks();
5788 static void AddDependentCode(Handle<Map> map,
5789 DependentCode::DependencyGroup group,
5792 bool IsMapInArrayPrototypeChain();
5794 static Handle<WeakCell> WeakCellForMap(Handle<Map> map);
5796 // Dispatched behavior.
5797 DECLARE_PRINTER(Map)
5798 DECLARE_VERIFIER(Map)
5801 void DictionaryMapVerify();
5802 void VerifyOmittedMapChecks();
5805 inline int visitor_id();
5806 inline void set_visitor_id(int visitor_id);
5808 static Handle<Map> TransitionToPrototype(Handle<Map> map,
5809 Handle<Object> prototype,
5810 PrototypeOptimizationMode mode);
5812 static const int kMaxPreAllocatedPropertyFields = 255;
5814 // Layout description.
5815 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
5816 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
5817 static const int kBitField3Offset = kInstanceAttributesOffset + kIntSize;
5818 static const int kPrototypeOffset = kBitField3Offset + kPointerSize;
5819 static const int kConstructorOrBackPointerOffset =
5820 kPrototypeOffset + kPointerSize;
5821 // When there is only one transition, it is stored directly in this field;
5822 // otherwise a transition array is used.
5823 // For prototype maps, this slot is used to store this map's PrototypeInfo
5825 static const int kTransitionsOrPrototypeInfoOffset =
5826 kConstructorOrBackPointerOffset + kPointerSize;
5827 static const int kDescriptorsOffset =
5828 kTransitionsOrPrototypeInfoOffset + kPointerSize;
5829 #if V8_DOUBLE_FIELDS_UNBOXING
5830 static const int kLayoutDecriptorOffset = kDescriptorsOffset + kPointerSize;
5831 static const int kCodeCacheOffset = kLayoutDecriptorOffset + kPointerSize;
5833 static const int kLayoutDecriptorOffset = 1; // Must not be ever accessed.
5834 static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
5836 static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
5837 static const int kWeakCellCacheOffset = kDependentCodeOffset + kPointerSize;
5838 static const int kSize = kWeakCellCacheOffset + kPointerSize;
5840 // Layout of pointer fields. Heap iteration code relies on them
5841 // being continuously allocated.
5842 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
5843 static const int kPointerFieldsEndOffset = kSize;
5845 // Byte offsets within kInstanceSizesOffset.
5846 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
5847 static const int kInObjectPropertiesByte = 1;
5848 static const int kInObjectPropertiesOffset =
5849 kInstanceSizesOffset + kInObjectPropertiesByte;
5850 // Note there is one byte available for use here.
5851 static const int kUnusedByte = 2;
5852 static const int kUnusedOffset = kInstanceSizesOffset + kUnusedByte;
5853 static const int kVisitorIdByte = 3;
5854 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
5856 // Byte offsets within kInstanceAttributesOffset attributes.
5857 #if V8_TARGET_LITTLE_ENDIAN
5858 // Order instance type and bit field together such that they can be loaded
5859 // together as a 16-bit word with instance type in the lower 8 bits regardless
5860 // of endianess. Also provide endian-independent offset to that 16-bit word.
5861 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
5862 static const int kBitFieldOffset = kInstanceAttributesOffset + 1;
5864 static const int kBitFieldOffset = kInstanceAttributesOffset + 0;
5865 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 1;
5867 static const int kInstanceTypeAndBitFieldOffset =
5868 kInstanceAttributesOffset + 0;
5869 static const int kBitField2Offset = kInstanceAttributesOffset + 2;
5870 static const int kUnusedPropertyFieldsByte = 3;
5871 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 3;
5873 STATIC_ASSERT(kInstanceTypeAndBitFieldOffset ==
5874 Internals::kMapInstanceTypeAndBitFieldOffset);
5876 // Bit positions for bit field.
5877 static const int kHasNonInstancePrototype = 0;
5878 static const int kIsHiddenPrototype = 1;
5879 static const int kHasNamedInterceptor = 2;
5880 static const int kHasIndexedInterceptor = 3;
5881 static const int kIsUndetectable = 4;
5882 static const int kIsObserved = 5;
5883 static const int kIsAccessCheckNeeded = 6;
5884 class FunctionWithPrototype: public BitField<bool, 7, 1> {};
5886 // Bit positions for bit field 2
5887 static const int kIsExtensible = 0;
5888 static const int kStringWrapperSafeForDefaultValueOf = 1;
5889 class IsPrototypeMapBits : public BitField<bool, 2, 1> {};
5890 class ElementsKindBits: public BitField<ElementsKind, 3, 5> {};
5892 // Derived values from bit field 2
5893 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
5894 (FAST_ELEMENTS + 1) << Map::ElementsKindBits::kShift) - 1;
5895 static const int8_t kMaximumBitField2FastSmiElementValue =
5896 static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
5897 Map::ElementsKindBits::kShift) - 1;
5898 static const int8_t kMaximumBitField2FastHoleyElementValue =
5899 static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
5900 Map::ElementsKindBits::kShift) - 1;
5901 static const int8_t kMaximumBitField2FastHoleySmiElementValue =
5902 static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
5903 Map::ElementsKindBits::kShift) - 1;
5905 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
5906 kPointerFieldsEndOffset,
5907 kSize> BodyDescriptor;
5909 // Compares this map to another to see if they describe equivalent objects.
5910 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
5911 // it had exactly zero inobject properties.
5912 // The "shared" flags of both this map and |other| are ignored.
5913 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
5915 // Returns true if given field is unboxed double.
5916 inline bool IsUnboxedDoubleField(FieldIndex index);
5919 static void TraceTransition(const char* what, Map* from, Map* to, Name* name);
5920 static void TraceAllTransitions(Map* map);
5923 static inline Handle<Map> CopyInstallDescriptorsForTesting(
5924 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5925 Handle<LayoutDescriptor> layout_descriptor);
5928 static void ConnectTransition(Handle<Map> parent, Handle<Map> child,
5929 Handle<Name> name, SimpleTransitionFlag flag);
5931 bool EquivalentToForTransition(Map* other);
5932 static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
5933 static Handle<Map> ShareDescriptor(Handle<Map> map,
5934 Handle<DescriptorArray> descriptors,
5935 Descriptor* descriptor);
5936 static Handle<Map> CopyInstallDescriptors(
5937 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5938 Handle<LayoutDescriptor> layout_descriptor);
5939 static Handle<Map> CopyAddDescriptor(Handle<Map> map,
5940 Descriptor* descriptor,
5941 TransitionFlag flag);
5942 static Handle<Map> CopyReplaceDescriptors(
5943 Handle<Map> map, Handle<DescriptorArray> descriptors,
5944 Handle<LayoutDescriptor> layout_descriptor, TransitionFlag flag,
5945 MaybeHandle<Name> maybe_name, const char* reason,
5946 SimpleTransitionFlag simple_flag);
5948 static Handle<Map> CopyReplaceDescriptor(Handle<Map> map,
5949 Handle<DescriptorArray> descriptors,
5950 Descriptor* descriptor,
5952 TransitionFlag flag);
5953 static MUST_USE_RESULT MaybeHandle<Map> TryReconfigureExistingProperty(
5954 Handle<Map> map, int descriptor, PropertyKind kind,
5955 PropertyAttributes attributes, const char** reason);
5957 static Handle<Map> CopyNormalized(Handle<Map> map,
5958 PropertyNormalizationMode mode);
5960 // Fires when the layout of an object with a leaf map changes.
5961 // This includes adding transitions to the leaf map or changing
5962 // the descriptor array.
5963 inline void NotifyLeafMapLayoutChange();
5965 void DeprecateTransitionTree();
5966 bool DeprecateTarget(PropertyKind kind, Name* key,
5967 PropertyAttributes attributes,
5968 DescriptorArray* new_descriptors,
5969 LayoutDescriptor* new_layout_descriptor);
5971 Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
5973 // Update field type of the given descriptor to new representation and new
5974 // type. The type must be prepared for storing in descriptor array:
5975 // it must be either a simple type or a map wrapped in a weak cell.
5976 void UpdateFieldType(int descriptor_number, Handle<Name> name,
5977 Representation new_representation,
5978 Handle<Object> new_wrapped_type);
5980 void PrintReconfiguration(FILE* file, int modify_index, PropertyKind kind,
5981 PropertyAttributes attributes);
5982 void PrintGeneralization(FILE* file,
5987 bool constant_to_field,
5988 Representation old_representation,
5989 Representation new_representation,
5990 HeapType* old_field_type,
5991 HeapType* new_field_type);
5993 static const int kFastPropertiesSoftLimit = 12;
5994 static const int kMaxFastProperties = 128;
5996 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
6000 // An abstract superclass, a marker class really, for simple structure classes.
6001 // It doesn't carry much functionality but allows struct classes to be
6002 // identified in the type system.
6003 class Struct: public HeapObject {
6005 inline void InitializeBody(int object_size);
6006 DECLARE_CAST(Struct)
6010 // A simple one-element struct, useful where smis need to be boxed.
6011 class Box : public Struct {
6013 // [value]: the boxed contents.
6014 DECL_ACCESSORS(value, Object)
6018 // Dispatched behavior.
6019 DECLARE_PRINTER(Box)
6020 DECLARE_VERIFIER(Box)
6022 static const int kValueOffset = HeapObject::kHeaderSize;
6023 static const int kSize = kValueOffset + kPointerSize;
6026 DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
6030 // Container for metadata stored on each prototype map.
6031 class PrototypeInfo : public Struct {
6033 // [prototype_users]: WeakFixedArray containing maps using this prototype,
6034 // or Smi(0) if uninitialized.
6035 DECL_ACCESSORS(prototype_users, Object)
6036 // [validity_cell]: Cell containing the validity bit for prototype chains
6037 // going through this object, or Smi(0) if uninitialized.
6038 DECL_ACCESSORS(validity_cell, Object)
6039 // [constructor_name]: User-friendly name of the original constructor.
6040 DECL_ACCESSORS(constructor_name, Object)
6042 DECLARE_CAST(PrototypeInfo)
6044 // Dispatched behavior.
6045 DECLARE_PRINTER(PrototypeInfo)
6046 DECLARE_VERIFIER(PrototypeInfo)
6048 static const int kPrototypeUsersOffset = HeapObject::kHeaderSize;
6049 static const int kValidityCellOffset = kPrototypeUsersOffset + kPointerSize;
6050 static const int kConstructorNameOffset = kValidityCellOffset + kPointerSize;
6051 static const int kSize = kConstructorNameOffset + kPointerSize;
6054 DISALLOW_IMPLICIT_CONSTRUCTORS(PrototypeInfo);
6058 // Script describes a script which has been added to the VM.
6059 class Script: public Struct {
6068 // Script compilation types.
6069 enum CompilationType {
6070 COMPILATION_TYPE_HOST = 0,
6071 COMPILATION_TYPE_EVAL = 1
6074 // Script compilation state.
6075 enum CompilationState {
6076 COMPILATION_STATE_INITIAL = 0,
6077 COMPILATION_STATE_COMPILED = 1
6080 // [source]: the script source.
6081 DECL_ACCESSORS(source, Object)
6083 // [name]: the script name.
6084 DECL_ACCESSORS(name, Object)
6086 // [id]: the script id.
6087 DECL_ACCESSORS(id, Smi)
6089 // [line_offset]: script line offset in resource from where it was extracted.
6090 DECL_ACCESSORS(line_offset, Smi)
6092 // [column_offset]: script column offset in resource from where it was
6094 DECL_ACCESSORS(column_offset, Smi)
6096 // [context_data]: context data for the context this script was compiled in.
6097 DECL_ACCESSORS(context_data, Object)
6099 // [wrapper]: the wrapper cache. This is either undefined or a WeakCell.
6100 DECL_ACCESSORS(wrapper, HeapObject)
6102 // [type]: the script type.
6103 DECL_ACCESSORS(type, Smi)
6105 // [line_ends]: FixedArray of line ends positions.
6106 DECL_ACCESSORS(line_ends, Object)
6108 // [eval_from_shared]: for eval scripts the shared funcion info for the
6109 // function from which eval was called.
6110 DECL_ACCESSORS(eval_from_shared, Object)
6112 // [eval_from_instructions_offset]: the instruction offset in the code for the
6113 // function from which eval was called where eval was called.
6114 DECL_ACCESSORS(eval_from_instructions_offset, Smi)
6116 // [shared_function_infos]: weak fixed array containing all shared
6117 // function infos created from this script.
6118 DECL_ACCESSORS(shared_function_infos, Object)
6120 // [flags]: Holds an exciting bitfield.
6121 DECL_ACCESSORS(flags, Smi)
6123 // [source_url]: sourceURL from magic comment
6124 DECL_ACCESSORS(source_url, Object)
6126 // [source_url]: sourceMappingURL magic comment
6127 DECL_ACCESSORS(source_mapping_url, Object)
6129 // [compilation_type]: how the the script was compiled. Encoded in the
6131 inline CompilationType compilation_type();
6132 inline void set_compilation_type(CompilationType type);
6134 // [compilation_state]: determines whether the script has already been
6135 // compiled. Encoded in the 'flags' field.
6136 inline CompilationState compilation_state();
6137 inline void set_compilation_state(CompilationState state);
6139 // [origin_options]: optional attributes set by the embedder via ScriptOrigin,
6140 // and used by the embedder to make decisions about the script. V8 just passes
6141 // this through. Encoded in the 'flags' field.
6142 inline v8::ScriptOriginOptions origin_options();
6143 inline void set_origin_options(ScriptOriginOptions origin_options);
6145 DECLARE_CAST(Script)
6147 // If script source is an external string, check that the underlying
6148 // resource is accessible. Otherwise, always return true.
6149 inline bool HasValidSource();
6151 // Convert code position into column number.
6152 static int GetColumnNumber(Handle<Script> script, int code_pos);
6154 // Convert code position into (zero-based) line number.
6155 // The non-handlified version does not allocate, but may be much slower.
6156 static int GetLineNumber(Handle<Script> script, int code_pos);
6157 int GetLineNumber(int code_pos);
6159 static Handle<Object> GetNameOrSourceURL(Handle<Script> script);
6161 // Init line_ends array with code positions of line ends inside script source.
6162 static void InitLineEnds(Handle<Script> script);
6164 // Get the JS object wrapping the given script; create it if none exists.
6165 static Handle<JSObject> GetWrapper(Handle<Script> script);
6167 // Look through the list of existing shared function infos to find one
6168 // that matches the function literal. Return empty handle if not found.
6169 MaybeHandle<SharedFunctionInfo> FindSharedFunctionInfo(FunctionLiteral* fun);
6171 // Dispatched behavior.
6172 DECLARE_PRINTER(Script)
6173 DECLARE_VERIFIER(Script)
6175 static const int kSourceOffset = HeapObject::kHeaderSize;
6176 static const int kNameOffset = kSourceOffset + kPointerSize;
6177 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
6178 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
6179 static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
6180 static const int kWrapperOffset = kContextOffset + kPointerSize;
6181 static const int kTypeOffset = kWrapperOffset + kPointerSize;
6182 static const int kLineEndsOffset = kTypeOffset + kPointerSize;
6183 static const int kIdOffset = kLineEndsOffset + kPointerSize;
6184 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
6185 static const int kEvalFrominstructionsOffsetOffset =
6186 kEvalFromSharedOffset + kPointerSize;
6187 static const int kSharedFunctionInfosOffset =
6188 kEvalFrominstructionsOffsetOffset + kPointerSize;
6189 static const int kFlagsOffset = kSharedFunctionInfosOffset + kPointerSize;
6190 static const int kSourceUrlOffset = kFlagsOffset + kPointerSize;
6191 static const int kSourceMappingUrlOffset = kSourceUrlOffset + kPointerSize;
6192 static const int kSize = kSourceMappingUrlOffset + kPointerSize;
6195 int GetLineNumberWithArray(int code_pos);
6197 // Bit positions in the flags field.
6198 static const int kCompilationTypeBit = 0;
6199 static const int kCompilationStateBit = 1;
6200 static const int kOriginOptionsShift = 2;
6201 static const int kOriginOptionsSize = 3;
6202 static const int kOriginOptionsMask = ((1 << kOriginOptionsSize) - 1)
6203 << kOriginOptionsShift;
6205 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6209 // List of builtin functions we want to identify to improve code
6212 // Each entry has a name of a global object property holding an object
6213 // optionally followed by ".prototype", a name of a builtin function
6214 // on the object (the one the id is set for), and a label.
6216 // Installation of ids for the selected builtin functions is handled
6217 // by the bootstrapper.
6218 #define FUNCTIONS_WITH_ID_LIST(V) \
6219 V(Array.prototype, indexOf, ArrayIndexOf) \
6220 V(Array.prototype, lastIndexOf, ArrayLastIndexOf) \
6221 V(Array.prototype, push, ArrayPush) \
6222 V(Array.prototype, pop, ArrayPop) \
6223 V(Array.prototype, shift, ArrayShift) \
6224 V(Function.prototype, apply, FunctionApply) \
6225 V(Function.prototype, call, FunctionCall) \
6226 V(String.prototype, charCodeAt, StringCharCodeAt) \
6227 V(String.prototype, charAt, StringCharAt) \
6228 V(String, fromCharCode, StringFromCharCode) \
6229 V(Math, random, MathRandom) \
6230 V(Math, floor, MathFloor) \
6231 V(Math, round, MathRound) \
6232 V(Math, ceil, MathCeil) \
6233 V(Math, abs, MathAbs) \
6234 V(Math, log, MathLog) \
6235 V(Math, exp, MathExp) \
6236 V(Math, sqrt, MathSqrt) \
6237 V(Math, pow, MathPow) \
6238 V(Math, max, MathMax) \
6239 V(Math, min, MathMin) \
6240 V(Math, cos, MathCos) \
6241 V(Math, sin, MathSin) \
6242 V(Math, tan, MathTan) \
6243 V(Math, acos, MathAcos) \
6244 V(Math, asin, MathAsin) \
6245 V(Math, atan, MathAtan) \
6246 V(Math, atan2, MathAtan2) \
6247 V(Math, imul, MathImul) \
6248 V(Math, clz32, MathClz32) \
6249 V(Math, fround, MathFround)
6251 #define ATOMIC_FUNCTIONS_WITH_ID_LIST(V) \
6252 V(Atomics, load, AtomicsLoad) \
6253 V(Atomics, store, AtomicsStore)
6255 enum BuiltinFunctionId {
6257 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
6259 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6260 ATOMIC_FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6261 #undef DECLARE_FUNCTION_ID
6262 // Fake id for a special case of Math.pow. Note, it continues the
6263 // list of math functions.
6268 // Result of searching in an optimized code map of a SharedFunctionInfo. Note
6269 // that both {code} and {literals} can be NULL to pass search result status.
6270 struct CodeAndLiterals {
6271 Code* code; // Cached optimized code.
6272 FixedArray* literals; // Cached literals array.
6276 // SharedFunctionInfo describes the JSFunction information that can be
6277 // shared by multiple instances of the function.
6278 class SharedFunctionInfo: public HeapObject {
6280 // [name]: Function name.
6281 DECL_ACCESSORS(name, Object)
6283 // [code]: Function code.
6284 DECL_ACCESSORS(code, Code)
6285 inline void ReplaceCode(Code* code);
6287 // [optimized_code_map]: Map from native context to optimized code
6288 // and a shared literals array or Smi(0) if none.
6289 DECL_ACCESSORS(optimized_code_map, Object)
6291 // Returns entry from optimized code map for specified context and OSR entry.
6292 // Note that {code == nullptr} indicates no matching entry has been found,
6293 // whereas {literals == nullptr} indicates the code is context-independent.
6294 CodeAndLiterals SearchOptimizedCodeMap(Context* native_context,
6295 BailoutId osr_ast_id);
6297 // Clear optimized code map.
6298 void ClearOptimizedCodeMap();
6300 // Removed a specific optimized code object from the optimized code map.
6301 void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
6303 // Trims the optimized code map after entries have been removed.
6304 void TrimOptimizedCodeMap(int shrink_by);
6306 // Add a new entry to the optimized code map for context-independent code.
6307 static void AddSharedCodeToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6310 // Add a new entry to the optimized code map for context-dependent code.
6311 static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6312 Handle<Context> native_context,
6314 Handle<FixedArray> literals,
6315 BailoutId osr_ast_id);
6317 // Set up the link between shared function info and the script. The shared
6318 // function info is added to the list on the script.
6319 static void SetScript(Handle<SharedFunctionInfo> shared,
6320 Handle<Object> script_object);
6322 // Layout description of the optimized code map.
6323 static const int kNextMapIndex = 0;
6324 static const int kSharedCodeIndex = 1;
6325 static const int kEntriesStart = 2;
6326 static const int kContextOffset = 0;
6327 static const int kCachedCodeOffset = 1;
6328 static const int kLiteralsOffset = 2;
6329 static const int kOsrAstIdOffset = 3;
6330 static const int kEntryLength = 4;
6331 static const int kInitialLength = kEntriesStart + kEntryLength;
6333 // [scope_info]: Scope info.
6334 DECL_ACCESSORS(scope_info, ScopeInfo)
6336 // [construct stub]: Code stub for constructing instances of this function.
6337 DECL_ACCESSORS(construct_stub, Code)
6339 // Returns if this function has been compiled to native code yet.
6340 inline bool is_compiled();
6342 // [length]: The function length - usually the number of declared parameters.
6343 // Use up to 2^30 parameters.
6344 inline int length() const;
6345 inline void set_length(int value);
6347 // [internal formal parameter count]: The declared number of parameters.
6348 // For subclass constructors, also includes new.target.
6349 // The size of function's frame is internal_formal_parameter_count + 1.
6350 inline int internal_formal_parameter_count() const;
6351 inline void set_internal_formal_parameter_count(int value);
6353 // Set the formal parameter count so the function code will be
6354 // called without using argument adaptor frames.
6355 inline void DontAdaptArguments();
6357 // [expected_nof_properties]: Expected number of properties for the function.
6358 inline int expected_nof_properties() const;
6359 inline void set_expected_nof_properties(int value);
6361 // [feedback_vector] - accumulates ast node feedback from full-codegen and
6362 // (increasingly) from crankshafted code where sufficient feedback isn't
6364 DECL_ACCESSORS(feedback_vector, TypeFeedbackVector)
6366 // Unconditionally clear the type feedback vector (including vector ICs).
6367 void ClearTypeFeedbackInfo();
6369 // Clear the type feedback vector with a more subtle policy at GC time.
6370 void ClearTypeFeedbackInfoAtGCTime();
6373 // [unique_id] - For --trace-maps purposes, an identifier that's persistent
6374 // even if the GC moves this SharedFunctionInfo.
6375 inline int unique_id() const;
6376 inline void set_unique_id(int value);
6379 // [instance class name]: class name for instances.
6380 DECL_ACCESSORS(instance_class_name, Object)
6382 // [function data]: This field holds some additional data for function.
6383 // Currently it has one of:
6384 // - a FunctionTemplateInfo to make benefit the API [IsApiFunction()].
6385 // - a Smi identifying a builtin function [HasBuiltinFunctionId()].
6386 // - a BytecodeArray for the interpreter [HasBytecodeArray()].
6387 // In the long run we don't want all functions to have this field but
6388 // we can fix that when we have a better model for storing hidden data
6390 DECL_ACCESSORS(function_data, Object)
6392 inline bool IsApiFunction();
6393 inline FunctionTemplateInfo* get_api_func_data();
6394 inline bool HasBuiltinFunctionId();
6395 inline BuiltinFunctionId builtin_function_id();
6396 inline bool HasBytecodeArray();
6397 inline BytecodeArray* bytecode_array();
6399 // [script info]: Script from which the function originates.
6400 DECL_ACCESSORS(script, Object)
6402 // [num_literals]: Number of literals used by this function.
6403 inline int num_literals() const;
6404 inline void set_num_literals(int value);
6406 // [start_position_and_type]: Field used to store both the source code
6407 // position, whether or not the function is a function expression,
6408 // and whether or not the function is a toplevel function. The two
6409 // least significants bit indicates whether the function is an
6410 // expression and the rest contains the source code position.
6411 inline int start_position_and_type() const;
6412 inline void set_start_position_and_type(int value);
6414 // The function is subject to debugging if a debug info is attached.
6415 inline bool HasDebugInfo();
6416 inline DebugInfo* GetDebugInfo();
6418 // A function has debug code if the compiled code has debug break slots.
6419 inline bool HasDebugCode();
6421 // [debug info]: Debug information.
6422 DECL_ACCESSORS(debug_info, Object)
6424 // [inferred name]: Name inferred from variable or property
6425 // assignment of this function. Used to facilitate debugging and
6426 // profiling of JavaScript code written in OO style, where almost
6427 // all functions are anonymous but are assigned to object
6429 DECL_ACCESSORS(inferred_name, String)
6431 // The function's name if it is non-empty, otherwise the inferred name.
6432 String* DebugName();
6434 // Position of the 'function' token in the script source.
6435 inline int function_token_position() const;
6436 inline void set_function_token_position(int function_token_position);
6438 // Position of this function in the script source.
6439 inline int start_position() const;
6440 inline void set_start_position(int start_position);
6442 // End position of this function in the script source.
6443 inline int end_position() const;
6444 inline void set_end_position(int end_position);
6446 // Is this function a function expression in the source code.
6447 DECL_BOOLEAN_ACCESSORS(is_expression)
6449 // Is this function a top-level function (scripts, evals).
6450 DECL_BOOLEAN_ACCESSORS(is_toplevel)
6452 // Bit field containing various information collected by the compiler to
6453 // drive optimization.
6454 inline int compiler_hints() const;
6455 inline void set_compiler_hints(int value);
6457 inline int ast_node_count() const;
6458 inline void set_ast_node_count(int count);
6460 inline int profiler_ticks() const;
6461 inline void set_profiler_ticks(int ticks);
6463 // Inline cache age is used to infer whether the function survived a context
6464 // disposal or not. In the former case we reset the opt_count.
6465 inline int ic_age();
6466 inline void set_ic_age(int age);
6468 // Indicates if this function can be lazy compiled.
6469 // This is used to determine if we can safely flush code from a function
6470 // when doing GC if we expect that the function will no longer be used.
6471 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
6473 // Indicates if this function can be lazy compiled without a context.
6474 // This is used to determine if we can force compilation without reaching
6475 // the function through program execution but through other means (e.g. heap
6476 // iteration by the debugger).
6477 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
6479 // Indicates whether optimizations have been disabled for this
6480 // shared function info. If a function is repeatedly optimized or if
6481 // we cannot optimize the function we disable optimization to avoid
6482 // spending time attempting to optimize it again.
6483 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
6485 // Indicates the language mode.
6486 inline LanguageMode language_mode();
6487 inline void set_language_mode(LanguageMode language_mode);
6489 // False if the function definitely does not allocate an arguments object.
6490 DECL_BOOLEAN_ACCESSORS(uses_arguments)
6492 // Indicates that this function uses a super property (or an eval that may
6493 // use a super property).
6494 // This is needed to set up the [[HomeObject]] on the function instance.
6495 DECL_BOOLEAN_ACCESSORS(needs_home_object)
6497 // True if the function has any duplicated parameter names.
6498 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
6500 // Indicates whether the function is a native function.
6501 // These needs special treatment in .call and .apply since
6502 // null passed as the receiver should not be translated to the
6504 DECL_BOOLEAN_ACCESSORS(native)
6506 // Indicate that this function should always be inlined in optimized code.
6507 DECL_BOOLEAN_ACCESSORS(force_inline)
6509 // Indicates that the function was created by the Function function.
6510 // Though it's anonymous, toString should treat it as if it had the name
6511 // "anonymous". We don't set the name itself so that the system does not
6512 // see a binding for it.
6513 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
6515 // Indicates whether the function is a bound function created using
6516 // the bind function.
6517 DECL_BOOLEAN_ACCESSORS(bound)
6519 // Indicates that the function is anonymous (the name field can be set
6520 // through the API, which does not change this flag).
6521 DECL_BOOLEAN_ACCESSORS(is_anonymous)
6523 // Is this a function or top-level/eval code.
6524 DECL_BOOLEAN_ACCESSORS(is_function)
6526 // Indicates that code for this function cannot be compiled with Crankshaft.
6527 DECL_BOOLEAN_ACCESSORS(dont_crankshaft)
6529 // Indicates that code for this function cannot be flushed.
6530 DECL_BOOLEAN_ACCESSORS(dont_flush)
6532 // Indicates that this function is a generator.
6533 DECL_BOOLEAN_ACCESSORS(is_generator)
6535 // Indicates that this function is an arrow function.
6536 DECL_BOOLEAN_ACCESSORS(is_arrow)
6538 // Indicates that this function is a concise method.
6539 DECL_BOOLEAN_ACCESSORS(is_concise_method)
6541 // Indicates that this function is an accessor (getter or setter).
6542 DECL_BOOLEAN_ACCESSORS(is_accessor_function)
6544 // Indicates that this function is a default constructor.
6545 DECL_BOOLEAN_ACCESSORS(is_default_constructor)
6547 // Indicates that this function is an asm function.
6548 DECL_BOOLEAN_ACCESSORS(asm_function)
6550 // Indicates that the the shared function info is deserialized from cache.
6551 DECL_BOOLEAN_ACCESSORS(deserialized)
6553 // Indicates that the the shared function info has never been compiled before.
6554 DECL_BOOLEAN_ACCESSORS(never_compiled)
6556 inline FunctionKind kind();
6557 inline void set_kind(FunctionKind kind);
6559 // Indicates whether or not the code in the shared function support
6561 inline bool has_deoptimization_support();
6563 // Enable deoptimization support through recompiled code.
6564 void EnableDeoptimizationSupport(Code* recompiled);
6566 // Disable (further) attempted optimization of all functions sharing this
6567 // shared function info.
6568 void DisableOptimization(BailoutReason reason);
6570 inline BailoutReason disable_optimization_reason();
6572 // Lookup the bailout ID and DCHECK that it exists in the non-optimized
6573 // code, returns whether it asserted (i.e., always true if assertions are
6575 bool VerifyBailoutId(BailoutId id);
6577 // [source code]: Source code for the function.
6578 bool HasSourceCode() const;
6579 Handle<Object> GetSourceCode();
6581 // Number of times the function was optimized.
6582 inline int opt_count();
6583 inline void set_opt_count(int opt_count);
6585 // Number of times the function was deoptimized.
6586 inline void set_deopt_count(int value);
6587 inline int deopt_count();
6588 inline void increment_deopt_count();
6590 // Number of time we tried to re-enable optimization after it
6591 // was disabled due to high number of deoptimizations.
6592 inline void set_opt_reenable_tries(int value);
6593 inline int opt_reenable_tries();
6595 inline void TryReenableOptimization();
6597 // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
6598 inline void set_counters(int value);
6599 inline int counters() const;
6601 // Stores opt_count and bailout_reason as bit-fields.
6602 inline void set_opt_count_and_bailout_reason(int value);
6603 inline int opt_count_and_bailout_reason() const;
6605 void set_disable_optimization_reason(BailoutReason reason) {
6606 set_opt_count_and_bailout_reason(
6607 DisabledOptimizationReasonBits::update(opt_count_and_bailout_reason(),
6611 // Tells whether this function should be subject to debugging.
6612 inline bool IsSubjectToDebugging();
6614 // Check whether or not this function is inlineable.
6615 bool IsInlineable();
6617 // Source size of this function.
6620 // Calculate the instance size.
6621 int CalculateInstanceSize();
6623 // Calculate the number of in-object properties.
6624 int CalculateInObjectProperties();
6626 inline bool is_simple_parameter_list();
6628 // Initialize a SharedFunctionInfo from a parsed function literal.
6629 static void InitFromFunctionLiteral(Handle<SharedFunctionInfo> shared_info,
6630 FunctionLiteral* lit);
6632 // Dispatched behavior.
6633 DECLARE_PRINTER(SharedFunctionInfo)
6634 DECLARE_VERIFIER(SharedFunctionInfo)
6636 void ResetForNewContext(int new_ic_age);
6638 DECLARE_CAST(SharedFunctionInfo)
6641 static const int kDontAdaptArgumentsSentinel = -1;
6643 // Layout description.
6645 static const int kNameOffset = HeapObject::kHeaderSize;
6646 static const int kCodeOffset = kNameOffset + kPointerSize;
6647 static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
6648 static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
6649 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
6650 static const int kInstanceClassNameOffset =
6651 kConstructStubOffset + kPointerSize;
6652 static const int kFunctionDataOffset =
6653 kInstanceClassNameOffset + kPointerSize;
6654 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
6655 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
6656 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
6657 static const int kFeedbackVectorOffset =
6658 kInferredNameOffset + kPointerSize;
6660 static const int kUniqueIdOffset = kFeedbackVectorOffset + kPointerSize;
6661 static const int kLastPointerFieldOffset = kUniqueIdOffset;
6663 // Just to not break the postmortrem support with conditional offsets
6664 static const int kUniqueIdOffset = kFeedbackVectorOffset;
6665 static const int kLastPointerFieldOffset = kFeedbackVectorOffset;
6668 #if V8_HOST_ARCH_32_BIT
6670 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6671 static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
6672 static const int kExpectedNofPropertiesOffset =
6673 kFormalParameterCountOffset + kPointerSize;
6674 static const int kNumLiteralsOffset =
6675 kExpectedNofPropertiesOffset + kPointerSize;
6676 static const int kStartPositionAndTypeOffset =
6677 kNumLiteralsOffset + kPointerSize;
6678 static const int kEndPositionOffset =
6679 kStartPositionAndTypeOffset + kPointerSize;
6680 static const int kFunctionTokenPositionOffset =
6681 kEndPositionOffset + kPointerSize;
6682 static const int kCompilerHintsOffset =
6683 kFunctionTokenPositionOffset + kPointerSize;
6684 static const int kOptCountAndBailoutReasonOffset =
6685 kCompilerHintsOffset + kPointerSize;
6686 static const int kCountersOffset =
6687 kOptCountAndBailoutReasonOffset + kPointerSize;
6688 static const int kAstNodeCountOffset =
6689 kCountersOffset + kPointerSize;
6690 static const int kProfilerTicksOffset =
6691 kAstNodeCountOffset + kPointerSize;
6694 static const int kSize = kProfilerTicksOffset + kPointerSize;
6696 // The only reason to use smi fields instead of int fields
6697 // is to allow iteration without maps decoding during
6698 // garbage collections.
6699 // To avoid wasting space on 64-bit architectures we use
6700 // the following trick: we group integer fields into pairs
6701 // The least significant integer in each pair is shifted left by 1.
6702 // By doing this we guarantee that LSB of each kPointerSize aligned
6703 // word is not set and thus this word cannot be treated as pointer
6704 // to HeapObject during old space traversal.
6705 #if V8_TARGET_LITTLE_ENDIAN
6706 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6707 static const int kFormalParameterCountOffset =
6708 kLengthOffset + kIntSize;
6710 static const int kExpectedNofPropertiesOffset =
6711 kFormalParameterCountOffset + kIntSize;
6712 static const int kNumLiteralsOffset =
6713 kExpectedNofPropertiesOffset + kIntSize;
6715 static const int kEndPositionOffset =
6716 kNumLiteralsOffset + kIntSize;
6717 static const int kStartPositionAndTypeOffset =
6718 kEndPositionOffset + kIntSize;
6720 static const int kFunctionTokenPositionOffset =
6721 kStartPositionAndTypeOffset + kIntSize;
6722 static const int kCompilerHintsOffset =
6723 kFunctionTokenPositionOffset + kIntSize;
6725 static const int kOptCountAndBailoutReasonOffset =
6726 kCompilerHintsOffset + kIntSize;
6727 static const int kCountersOffset =
6728 kOptCountAndBailoutReasonOffset + kIntSize;
6730 static const int kAstNodeCountOffset =
6731 kCountersOffset + kIntSize;
6732 static const int kProfilerTicksOffset =
6733 kAstNodeCountOffset + kIntSize;
6736 static const int kSize = kProfilerTicksOffset + kIntSize;
6738 #elif V8_TARGET_BIG_ENDIAN
6739 static const int kFormalParameterCountOffset =
6740 kLastPointerFieldOffset + kPointerSize;
6741 static const int kLengthOffset = kFormalParameterCountOffset + kIntSize;
6743 static const int kNumLiteralsOffset = kLengthOffset + kIntSize;
6744 static const int kExpectedNofPropertiesOffset = kNumLiteralsOffset + kIntSize;
6746 static const int kStartPositionAndTypeOffset =
6747 kExpectedNofPropertiesOffset + kIntSize;
6748 static const int kEndPositionOffset = kStartPositionAndTypeOffset + kIntSize;
6750 static const int kCompilerHintsOffset = kEndPositionOffset + kIntSize;
6751 static const int kFunctionTokenPositionOffset =
6752 kCompilerHintsOffset + kIntSize;
6754 static const int kCountersOffset = kFunctionTokenPositionOffset + kIntSize;
6755 static const int kOptCountAndBailoutReasonOffset = kCountersOffset + kIntSize;
6757 static const int kProfilerTicksOffset =
6758 kOptCountAndBailoutReasonOffset + kIntSize;
6759 static const int kAstNodeCountOffset = kProfilerTicksOffset + kIntSize;
6762 static const int kSize = kAstNodeCountOffset + kIntSize;
6765 #error Unknown byte ordering
6766 #endif // Big endian
6770 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
6772 typedef FixedBodyDescriptor<kNameOffset,
6773 kLastPointerFieldOffset + kPointerSize,
6774 kSize> BodyDescriptor;
6776 // Bit positions in start_position_and_type.
6777 // The source code start position is in the 30 most significant bits of
6778 // the start_position_and_type field.
6779 static const int kIsExpressionBit = 0;
6780 static const int kIsTopLevelBit = 1;
6781 static const int kStartPositionShift = 2;
6782 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
6784 // Bit positions in compiler_hints.
6785 enum CompilerHints {
6786 kAllowLazyCompilation,
6787 kAllowLazyCompilationWithoutContext,
6788 kOptimizationDisabled,
6789 kStrictModeFunction,
6790 kStrongModeFunction,
6793 kHasDuplicateParameters,
6798 kNameShouldPrintAsAnonymous,
6805 kIsAccessorFunction,
6806 kIsDefaultConstructor,
6807 kIsSubclassConstructor,
6813 kCompilerHintsCount // Pseudo entry
6815 // Add hints for other modes when they're added.
6816 STATIC_ASSERT(LANGUAGE_END == 3);
6818 class FunctionKindBits : public BitField<FunctionKind, kIsArrow, 8> {};
6820 class DeoptCountBits : public BitField<int, 0, 4> {};
6821 class OptReenableTriesBits : public BitField<int, 4, 18> {};
6822 class ICAgeBits : public BitField<int, 22, 8> {};
6824 class OptCountBits : public BitField<int, 0, 22> {};
6825 class DisabledOptimizationReasonBits : public BitField<int, 22, 8> {};
6828 #if V8_HOST_ARCH_32_BIT
6829 // On 32 bit platforms, compiler hints is a smi.
6830 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
6831 static const int kCompilerHintsSize = kPointerSize;
6833 // On 64 bit platforms, compiler hints is not a smi, see comment above.
6834 static const int kCompilerHintsSmiTagSize = 0;
6835 static const int kCompilerHintsSize = kIntSize;
6838 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
6839 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
6842 // Constants for optimizing codegen for strict mode function and
6844 // Allows to use byte-width instructions.
6845 static const int kStrictModeBitWithinByte =
6846 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6847 static const int kStrongModeBitWithinByte =
6848 (kStrongModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6850 static const int kNativeBitWithinByte =
6851 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
6853 #if defined(V8_TARGET_LITTLE_ENDIAN)
6854 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6855 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6856 static const int kStrongModeByteOffset =
6857 kCompilerHintsOffset +
6858 (kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6859 static const int kNativeByteOffset = kCompilerHintsOffset +
6860 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
6861 #elif defined(V8_TARGET_BIG_ENDIAN)
6862 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6863 (kCompilerHintsSize - 1) -
6864 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6865 static const int kStrongModeByteOffset =
6866 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6867 ((kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6868 static const int kNativeByteOffset = kCompilerHintsOffset +
6869 (kCompilerHintsSize - 1) -
6870 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
6872 #error Unknown byte ordering
6876 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
6880 // Printing support.
6881 struct SourceCodeOf {
6882 explicit SourceCodeOf(SharedFunctionInfo* v, int max = -1)
6883 : value(v), max_length(max) {}
6884 const SharedFunctionInfo* value;
6889 std::ostream& operator<<(std::ostream& os, const SourceCodeOf& v);
6892 class JSGeneratorObject: public JSObject {
6894 // [function]: The function corresponding to this generator object.
6895 DECL_ACCESSORS(function, JSFunction)
6897 // [context]: The context of the suspended computation.
6898 DECL_ACCESSORS(context, Context)
6900 // [receiver]: The receiver of the suspended computation.
6901 DECL_ACCESSORS(receiver, Object)
6903 // [continuation]: Offset into code of continuation.
6905 // A positive offset indicates a suspended generator. The special
6906 // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
6907 // cannot be resumed.
6908 inline int continuation() const;
6909 inline void set_continuation(int continuation);
6910 inline bool is_closed();
6911 inline bool is_executing();
6912 inline bool is_suspended();
6914 // [operand_stack]: Saved operand stack.
6915 DECL_ACCESSORS(operand_stack, FixedArray)
6917 DECLARE_CAST(JSGeneratorObject)
6919 // Dispatched behavior.
6920 DECLARE_PRINTER(JSGeneratorObject)
6921 DECLARE_VERIFIER(JSGeneratorObject)
6923 // Magic sentinel values for the continuation.
6924 static const int kGeneratorExecuting = -1;
6925 static const int kGeneratorClosed = 0;
6927 // Layout description.
6928 static const int kFunctionOffset = JSObject::kHeaderSize;
6929 static const int kContextOffset = kFunctionOffset + kPointerSize;
6930 static const int kReceiverOffset = kContextOffset + kPointerSize;
6931 static const int kContinuationOffset = kReceiverOffset + kPointerSize;
6932 static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
6933 static const int kSize = kOperandStackOffset + kPointerSize;
6935 // Resume mode, for use by runtime functions.
6936 enum ResumeMode { NEXT, THROW };
6938 // Yielding from a generator returns an object with the following inobject
6939 // properties. See Context::iterator_result_map() for the map.
6940 static const int kResultValuePropertyIndex = 0;
6941 static const int kResultDonePropertyIndex = 1;
6942 static const int kResultPropertyCount = 2;
6944 static const int kResultValuePropertyOffset = JSObject::kHeaderSize;
6945 static const int kResultDonePropertyOffset =
6946 kResultValuePropertyOffset + kPointerSize;
6947 static const int kResultSize = kResultDonePropertyOffset + kPointerSize;
6950 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
6954 // Representation for module instance objects.
6955 class JSModule: public JSObject {
6957 // [context]: the context holding the module's locals, or undefined if none.
6958 DECL_ACCESSORS(context, Object)
6960 // [scope_info]: Scope info.
6961 DECL_ACCESSORS(scope_info, ScopeInfo)
6963 DECLARE_CAST(JSModule)
6965 // Dispatched behavior.
6966 DECLARE_PRINTER(JSModule)
6967 DECLARE_VERIFIER(JSModule)
6969 // Layout description.
6970 static const int kContextOffset = JSObject::kHeaderSize;
6971 static const int kScopeInfoOffset = kContextOffset + kPointerSize;
6972 static const int kSize = kScopeInfoOffset + kPointerSize;
6975 DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
6979 // JSFunction describes JavaScript functions.
6980 class JSFunction: public JSObject {
6982 // [prototype_or_initial_map]:
6983 DECL_ACCESSORS(prototype_or_initial_map, Object)
6985 // [shared]: The information about the function that
6986 // can be shared by instances.
6987 DECL_ACCESSORS(shared, SharedFunctionInfo)
6989 // [context]: The context for this function.
6990 inline Context* context();
6991 inline void set_context(Object* context);
6992 inline JSObject* global_proxy();
6994 // [code]: The generated code object for this function. Executed
6995 // when the function is invoked, e.g. foo() or new foo(). See
6996 // [[Call]] and [[Construct]] description in ECMA-262, section
6998 inline Code* code();
6999 inline void set_code(Code* code);
7000 inline void set_code_no_write_barrier(Code* code);
7001 inline void ReplaceCode(Code* code);
7003 // Tells whether this function is builtin.
7004 inline bool IsBuiltin();
7006 // Tells whether this function inlines the given shared function info.
7007 bool Inlines(SharedFunctionInfo* candidate);
7009 // Tells whether this function should be subject to debugging.
7010 inline bool IsSubjectToDebugging();
7012 // Tells whether or not the function needs arguments adaption.
7013 inline bool NeedsArgumentsAdaption();
7015 // Tells whether or not this function has been optimized.
7016 inline bool IsOptimized();
7018 // Mark this function for lazy recompilation. The function will be
7019 // recompiled the next time it is executed.
7020 void MarkForOptimization();
7021 void AttemptConcurrentOptimization();
7023 // Tells whether or not the function is already marked for lazy
7025 inline bool IsMarkedForOptimization();
7026 inline bool IsMarkedForConcurrentOptimization();
7028 // Tells whether or not the function is on the concurrent recompilation queue.
7029 inline bool IsInOptimizationQueue();
7031 // Inobject slack tracking is the way to reclaim unused inobject space.
7033 // The instance size is initially determined by adding some slack to
7034 // expected_nof_properties (to allow for a few extra properties added
7035 // after the constructor). There is no guarantee that the extra space
7036 // will not be wasted.
7038 // Here is the algorithm to reclaim the unused inobject space:
7039 // - Detect the first constructor call for this JSFunction.
7040 // When it happens enter the "in progress" state: initialize construction
7041 // counter in the initial_map.
7042 // - While the tracking is in progress create objects filled with
7043 // one_pointer_filler_map instead of undefined_value. This way they can be
7044 // resized quickly and safely.
7045 // - Once enough objects have been created compute the 'slack'
7046 // (traverse the map transition tree starting from the
7047 // initial_map and find the lowest value of unused_property_fields).
7048 // - Traverse the transition tree again and decrease the instance size
7049 // of every map. Existing objects will resize automatically (they are
7050 // filled with one_pointer_filler_map). All further allocations will
7051 // use the adjusted instance size.
7052 // - SharedFunctionInfo's expected_nof_properties left unmodified since
7053 // allocations made using different closures could actually create different
7054 // kind of objects (see prototype inheritance pattern).
7056 // Important: inobject slack tracking is not attempted during the snapshot
7059 // True if the initial_map is set and the object constructions countdown
7060 // counter is not zero.
7061 static const int kGenerousAllocationCount =
7062 Map::kSlackTrackingCounterStart - Map::kSlackTrackingCounterEnd + 1;
7063 inline bool IsInobjectSlackTrackingInProgress();
7065 // Starts the tracking.
7066 // Initializes object constructions countdown counter in the initial map.
7067 void StartInobjectSlackTracking();
7069 // Completes the tracking.
7070 void CompleteInobjectSlackTracking();
7072 // [literals_or_bindings]: Fixed array holding either
7073 // the materialized literals or the bindings of a bound function.
7075 // If the function contains object, regexp or array literals, the
7076 // literals array prefix contains the object, regexp, and array
7077 // function to be used when creating these literals. This is
7078 // necessary so that we do not dynamically lookup the object, regexp
7079 // or array functions. Performing a dynamic lookup, we might end up
7080 // using the functions from a new context that we should not have
7083 // On bound functions, the array is a (copy-on-write) fixed-array containing
7084 // the function that was bound, bound this-value and any bound
7085 // arguments. Bound functions never contain literals.
7086 DECL_ACCESSORS(literals_or_bindings, FixedArray)
7088 inline FixedArray* literals();
7089 inline void set_literals(FixedArray* literals);
7091 inline FixedArray* function_bindings();
7092 inline void set_function_bindings(FixedArray* bindings);
7094 // The initial map for an object created by this constructor.
7095 inline Map* initial_map();
7096 static void SetInitialMap(Handle<JSFunction> function, Handle<Map> map,
7097 Handle<Object> prototype);
7098 inline bool has_initial_map();
7099 static void EnsureHasInitialMap(Handle<JSFunction> function);
7101 // Get and set the prototype property on a JSFunction. If the
7102 // function has an initial map the prototype is set on the initial
7103 // map. Otherwise, the prototype is put in the initial map field
7104 // until an initial map is needed.
7105 inline bool has_prototype();
7106 inline bool has_instance_prototype();
7107 inline Object* prototype();
7108 inline Object* instance_prototype();
7109 static void SetPrototype(Handle<JSFunction> function,
7110 Handle<Object> value);
7111 static void SetInstancePrototype(Handle<JSFunction> function,
7112 Handle<Object> value);
7114 // Creates a new closure for the fucntion with the same bindings,
7115 // bound values, and prototype. An equivalent of spec operations
7116 // ``CloneMethod`` and ``CloneBoundFunction``.
7117 static Handle<JSFunction> CloneClosure(Handle<JSFunction> function);
7119 // After prototype is removed, it will not be created when accessed, and
7120 // [[Construct]] from this function will not be allowed.
7121 bool RemovePrototype();
7122 inline bool should_have_prototype();
7124 // Accessor for this function's initial map's [[class]]
7125 // property. This is primarily used by ECMA native functions. This
7126 // method sets the class_name field of this function's initial map
7127 // to a given value. It creates an initial map if this function does
7128 // not have one. Note that this method does not copy the initial map
7129 // if it has one already, but simply replaces it with the new value.
7130 // Instances created afterwards will have a map whose [[class]] is
7131 // set to 'value', but there is no guarantees on instances created
7133 void SetInstanceClassName(String* name);
7135 // Returns if this function has been compiled to native code yet.
7136 inline bool is_compiled();
7138 // Returns `false` if formal parameters include rest parameters, optional
7139 // parameters, or destructuring parameters.
7140 // TODO(caitp): make this a flag set during parsing
7141 inline bool is_simple_parameter_list();
7143 // [next_function_link]: Links functions into various lists, e.g. the list
7144 // of optimized functions hanging off the native_context. The CodeFlusher
7145 // uses this link to chain together flushing candidates. Treated weakly
7146 // by the garbage collector.
7147 DECL_ACCESSORS(next_function_link, Object)
7149 // Prints the name of the function using PrintF.
7150 void PrintName(FILE* out = stdout);
7152 DECLARE_CAST(JSFunction)
7154 // Iterates the objects, including code objects indirectly referenced
7155 // through pointers to the first instruction in the code object.
7156 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
7158 // Dispatched behavior.
7159 DECLARE_PRINTER(JSFunction)
7160 DECLARE_VERIFIER(JSFunction)
7162 // Returns the number of allocated literals.
7163 inline int NumberOfLiterals();
7165 // Used for flags such as --hydrogen-filter.
7166 bool PassesFilter(const char* raw_filter);
7168 // The function's name if it is configured, otherwise shared function info
7170 static Handle<String> GetDebugName(Handle<JSFunction> function);
7172 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
7173 // kSize) is weak and has special handling during garbage collection.
7174 static const int kCodeEntryOffset = JSObject::kHeaderSize;
7175 static const int kPrototypeOrInitialMapOffset =
7176 kCodeEntryOffset + kPointerSize;
7177 static const int kSharedFunctionInfoOffset =
7178 kPrototypeOrInitialMapOffset + kPointerSize;
7179 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
7180 static const int kLiteralsOffset = kContextOffset + kPointerSize;
7181 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
7182 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
7183 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
7185 // Layout of the bound-function binding array.
7186 static const int kBoundFunctionIndex = 0;
7187 static const int kBoundThisIndex = 1;
7188 static const int kBoundArgumentsStartIndex = 2;
7191 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7195 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7196 // and the prototype is hidden. JSGlobalProxy always delegates
7197 // property accesses to its prototype if the prototype is not null.
7199 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7201 // Accessing a JSGlobalProxy requires security check.
7203 class JSGlobalProxy : public JSObject {
7205 // [native_context]: the owner native context of this global proxy object.
7206 // It is null value if this object is not used by any context.
7207 DECL_ACCESSORS(native_context, Object)
7209 // [hash]: The hash code property (undefined if not initialized yet).
7210 DECL_ACCESSORS(hash, Object)
7212 DECLARE_CAST(JSGlobalProxy)
7214 inline bool IsDetachedFrom(GlobalObject* global) const;
7216 // Dispatched behavior.
7217 DECLARE_PRINTER(JSGlobalProxy)
7218 DECLARE_VERIFIER(JSGlobalProxy)
7220 // Layout description.
7221 static const int kNativeContextOffset = JSObject::kHeaderSize;
7222 static const int kHashOffset = kNativeContextOffset + kPointerSize;
7223 static const int kSize = kHashOffset + kPointerSize;
7226 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7230 // Common super class for JavaScript global objects and the special
7231 // builtins global objects.
7232 class GlobalObject: public JSObject {
7234 // [builtins]: the object holding the runtime routines written in JS.
7235 DECL_ACCESSORS(builtins, JSBuiltinsObject)
7237 // [native context]: the natives corresponding to this global object.
7238 DECL_ACCESSORS(native_context, Context)
7240 // [global proxy]: the global proxy object of the context
7241 DECL_ACCESSORS(global_proxy, JSObject)
7243 DECLARE_CAST(GlobalObject)
7245 static void InvalidatePropertyCell(Handle<GlobalObject> object,
7247 // Ensure that the global object has a cell for the given property name.
7248 static Handle<PropertyCell> EnsurePropertyCell(Handle<GlobalObject> global,
7251 // Layout description.
7252 static const int kBuiltinsOffset = JSObject::kHeaderSize;
7253 static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7254 static const int kGlobalProxyOffset = kNativeContextOffset + kPointerSize;
7255 static const int kHeaderSize = kGlobalProxyOffset + kPointerSize;
7258 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7262 // JavaScript global object.
7263 class JSGlobalObject: public GlobalObject {
7265 DECLARE_CAST(JSGlobalObject)
7267 inline bool IsDetached();
7269 // Dispatched behavior.
7270 DECLARE_PRINTER(JSGlobalObject)
7271 DECLARE_VERIFIER(JSGlobalObject)
7273 // Layout description.
7274 static const int kSize = GlobalObject::kHeaderSize;
7277 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7281 // Builtins global object which holds the runtime routines written in
7283 class JSBuiltinsObject: public GlobalObject {
7285 // Accessors for the runtime routines written in JavaScript.
7286 inline Object* javascript_builtin(Builtins::JavaScript id);
7287 inline void set_javascript_builtin(Builtins::JavaScript id, Object* value);
7289 DECLARE_CAST(JSBuiltinsObject)
7291 // Dispatched behavior.
7292 DECLARE_PRINTER(JSBuiltinsObject)
7293 DECLARE_VERIFIER(JSBuiltinsObject)
7295 // Layout description. The size of the builtins object includes
7296 // room for two pointers per runtime routine written in javascript
7297 // (function and code object).
7298 static const int kJSBuiltinsCount = Builtins::id_count;
7299 static const int kJSBuiltinsOffset = GlobalObject::kHeaderSize;
7300 static const int kSize =
7301 GlobalObject::kHeaderSize + (kJSBuiltinsCount * kPointerSize);
7303 static int OffsetOfFunctionWithId(Builtins::JavaScript id) {
7304 return kJSBuiltinsOffset + id * kPointerSize;
7308 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7312 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
7313 class JSValue: public JSObject {
7315 // [value]: the object being wrapped.
7316 DECL_ACCESSORS(value, Object)
7318 DECLARE_CAST(JSValue)
7320 // Dispatched behavior.
7321 DECLARE_PRINTER(JSValue)
7322 DECLARE_VERIFIER(JSValue)
7324 // Layout description.
7325 static const int kValueOffset = JSObject::kHeaderSize;
7326 static const int kSize = kValueOffset + kPointerSize;
7329 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
7335 // Representation for JS date objects.
7336 class JSDate: public JSObject {
7338 // If one component is NaN, all of them are, indicating a NaN time value.
7339 // [value]: the time value.
7340 DECL_ACCESSORS(value, Object)
7341 // [year]: caches year. Either undefined, smi, or NaN.
7342 DECL_ACCESSORS(year, Object)
7343 // [month]: caches month. Either undefined, smi, or NaN.
7344 DECL_ACCESSORS(month, Object)
7345 // [day]: caches day. Either undefined, smi, or NaN.
7346 DECL_ACCESSORS(day, Object)
7347 // [weekday]: caches day of week. Either undefined, smi, or NaN.
7348 DECL_ACCESSORS(weekday, Object)
7349 // [hour]: caches hours. Either undefined, smi, or NaN.
7350 DECL_ACCESSORS(hour, Object)
7351 // [min]: caches minutes. Either undefined, smi, or NaN.
7352 DECL_ACCESSORS(min, Object)
7353 // [sec]: caches seconds. Either undefined, smi, or NaN.
7354 DECL_ACCESSORS(sec, Object)
7355 // [cache stamp]: sample of the date cache stamp at the
7356 // moment when chached fields were cached.
7357 DECL_ACCESSORS(cache_stamp, Object)
7359 DECLARE_CAST(JSDate)
7361 // Returns the date field with the specified index.
7362 // See FieldIndex for the list of date fields.
7363 static Object* GetField(Object* date, Smi* index);
7365 void SetValue(Object* value, bool is_value_nan);
7368 // Dispatched behavior.
7369 DECLARE_PRINTER(JSDate)
7370 DECLARE_VERIFIER(JSDate)
7372 // The order is important. It must be kept in sync with date macros
7383 kFirstUncachedField,
7384 kMillisecond = kFirstUncachedField,
7388 kYearUTC = kFirstUTCField,
7401 // Layout description.
7402 static const int kValueOffset = JSObject::kHeaderSize;
7403 static const int kYearOffset = kValueOffset + kPointerSize;
7404 static const int kMonthOffset = kYearOffset + kPointerSize;
7405 static const int kDayOffset = kMonthOffset + kPointerSize;
7406 static const int kWeekdayOffset = kDayOffset + kPointerSize;
7407 static const int kHourOffset = kWeekdayOffset + kPointerSize;
7408 static const int kMinOffset = kHourOffset + kPointerSize;
7409 static const int kSecOffset = kMinOffset + kPointerSize;
7410 static const int kCacheStampOffset = kSecOffset + kPointerSize;
7411 static const int kSize = kCacheStampOffset + kPointerSize;
7414 inline Object* DoGetField(FieldIndex index);
7416 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
7418 // Computes and caches the cacheable fields of the date.
7419 inline void SetCachedFields(int64_t local_time_ms, DateCache* date_cache);
7422 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
7426 // Representation of message objects used for error reporting through
7427 // the API. The messages are formatted in JavaScript so this object is
7428 // a real JavaScript object. The information used for formatting the
7429 // error messages are not directly accessible from JavaScript to
7430 // prevent leaking information to user code called during error
7432 class JSMessageObject: public JSObject {
7434 // [type]: the type of error message.
7435 inline int type() const;
7436 inline void set_type(int value);
7438 // [arguments]: the arguments for formatting the error message.
7439 DECL_ACCESSORS(argument, Object)
7441 // [script]: the script from which the error message originated.
7442 DECL_ACCESSORS(script, Object)
7444 // [stack_frames]: an array of stack frames for this error object.
7445 DECL_ACCESSORS(stack_frames, Object)
7447 // [start_position]: the start position in the script for the error message.
7448 inline int start_position() const;
7449 inline void set_start_position(int value);
7451 // [end_position]: the end position in the script for the error message.
7452 inline int end_position() const;
7453 inline void set_end_position(int value);
7455 DECLARE_CAST(JSMessageObject)
7457 // Dispatched behavior.
7458 DECLARE_PRINTER(JSMessageObject)
7459 DECLARE_VERIFIER(JSMessageObject)
7461 // Layout description.
7462 static const int kTypeOffset = JSObject::kHeaderSize;
7463 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
7464 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
7465 static const int kStackFramesOffset = kScriptOffset + kPointerSize;
7466 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
7467 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
7468 static const int kSize = kEndPositionOffset + kPointerSize;
7470 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
7471 kStackFramesOffset + kPointerSize,
7472 kSize> BodyDescriptor;
7476 // Regular expressions
7477 // The regular expression holds a single reference to a FixedArray in
7478 // the kDataOffset field.
7479 // The FixedArray contains the following data:
7480 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
7481 // - reference to the original source string
7482 // - reference to the original flag string
7483 // If it is an atom regexp
7484 // - a reference to a literal string to search for
7485 // If it is an irregexp regexp:
7486 // - a reference to code for Latin1 inputs (bytecode or compiled), or a smi
7487 // used for tracking the last usage (used for code flushing).
7488 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
7489 // used for tracking the last usage (used for code flushing)..
7490 // - max number of registers used by irregexp implementations.
7491 // - number of capture registers (output values) of the regexp.
7492 class JSRegExp: public JSObject {
7495 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
7496 // ATOM: A simple string to match against using an indexOf operation.
7497 // IRREGEXP: Compiled with Irregexp.
7498 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
7499 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
7506 UNICODE_ESCAPES = 16
7511 explicit Flags(uint32_t value) : value_(value) { }
7512 bool is_global() { return (value_ & GLOBAL) != 0; }
7513 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
7514 bool is_multiline() { return (value_ & MULTILINE) != 0; }
7515 bool is_sticky() { return (value_ & STICKY) != 0; }
7516 bool is_unicode() { return (value_ & UNICODE_ESCAPES) != 0; }
7517 uint32_t value() { return value_; }
7522 DECL_ACCESSORS(data, Object)
7524 inline Type TypeTag();
7525 inline int CaptureCount();
7526 inline Flags GetFlags();
7527 inline String* Pattern();
7528 inline Object* DataAt(int index);
7529 // Set implementation data after the object has been prepared.
7530 inline void SetDataAt(int index, Object* value);
7532 static int code_index(bool is_latin1) {
7534 return kIrregexpLatin1CodeIndex;
7536 return kIrregexpUC16CodeIndex;
7540 static int saved_code_index(bool is_latin1) {
7542 return kIrregexpLatin1CodeSavedIndex;
7544 return kIrregexpUC16CodeSavedIndex;
7548 DECLARE_CAST(JSRegExp)
7550 // Dispatched behavior.
7551 DECLARE_VERIFIER(JSRegExp)
7553 static const int kDataOffset = JSObject::kHeaderSize;
7554 static const int kSize = kDataOffset + kPointerSize;
7556 // Indices in the data array.
7557 static const int kTagIndex = 0;
7558 static const int kSourceIndex = kTagIndex + 1;
7559 static const int kFlagsIndex = kSourceIndex + 1;
7560 static const int kDataIndex = kFlagsIndex + 1;
7561 // The data fields are used in different ways depending on the
7562 // value of the tag.
7563 // Atom regexps (literal strings).
7564 static const int kAtomPatternIndex = kDataIndex;
7566 static const int kAtomDataSize = kAtomPatternIndex + 1;
7568 // Irregexp compiled code or bytecode for Latin1. If compilation
7569 // fails, this fields hold an exception object that should be
7570 // thrown if the regexp is used again.
7571 static const int kIrregexpLatin1CodeIndex = kDataIndex;
7572 // Irregexp compiled code or bytecode for UC16. If compilation
7573 // fails, this fields hold an exception object that should be
7574 // thrown if the regexp is used again.
7575 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
7577 // Saved instance of Irregexp compiled code or bytecode for Latin1 that
7578 // is a potential candidate for flushing.
7579 static const int kIrregexpLatin1CodeSavedIndex = kDataIndex + 2;
7580 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
7581 // a potential candidate for flushing.
7582 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
7584 // Maximal number of registers used by either Latin1 or UC16.
7585 // Only used to check that there is enough stack space
7586 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
7587 // Number of captures in the compiled regexp.
7588 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
7590 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
7592 // Offsets directly into the data fixed array.
7593 static const int kDataTagOffset =
7594 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
7595 static const int kDataOneByteCodeOffset =
7596 FixedArray::kHeaderSize + kIrregexpLatin1CodeIndex * kPointerSize;
7597 static const int kDataUC16CodeOffset =
7598 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
7599 static const int kIrregexpCaptureCountOffset =
7600 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
7602 // In-object fields.
7603 static const int kSourceFieldIndex = 0;
7604 static const int kGlobalFieldIndex = 1;
7605 static const int kIgnoreCaseFieldIndex = 2;
7606 static const int kMultilineFieldIndex = 3;
7607 static const int kLastIndexFieldIndex = 4;
7608 static const int kInObjectFieldCount = 5;
7610 // The uninitialized value for a regexp code object.
7611 static const int kUninitializedValue = -1;
7613 // The compilation error value for the regexp code object. The real error
7614 // object is in the saved code field.
7615 static const int kCompilationErrorValue = -2;
7617 // When we store the sweep generation at which we moved the code from the
7618 // code index to the saved code index we mask it of to be in the [0:255]
7620 static const int kCodeAgeMask = 0xff;
7624 class CompilationCacheShape : public BaseShape<HashTableKey*> {
7626 static inline bool IsMatch(HashTableKey* key, Object* value) {
7627 return key->IsMatch(value);
7630 static inline uint32_t Hash(HashTableKey* key) {
7634 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7635 return key->HashForObject(object);
7638 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7640 static const int kPrefixSize = 0;
7641 static const int kEntrySize = 2;
7645 // This cache is used in two different variants. For regexp caching, it simply
7646 // maps identifying info of the regexp to the cached regexp object. Scripts and
7647 // eval code only gets cached after a second probe for the code object. To do
7648 // so, on first "put" only a hash identifying the source is entered into the
7649 // cache, mapping it to a lifetime count of the hash. On each call to Age all
7650 // such lifetimes get reduced, and removed once they reach zero. If a second put
7651 // is called while such a hash is live in the cache, the hash gets replaced by
7652 // an actual cache entry. Age also removes stale live entries from the cache.
7653 // Such entries are identified by SharedFunctionInfos pointing to either the
7654 // recompilation stub, or to "old" code. This avoids memory leaks due to
7655 // premature caching of scripts and eval strings that are never needed later.
7656 class CompilationCacheTable: public HashTable<CompilationCacheTable,
7657 CompilationCacheShape,
7660 // Find cached value for a string key, otherwise return null.
7661 Handle<Object> Lookup(
7662 Handle<String> src, Handle<Context> context, LanguageMode language_mode);
7663 Handle<Object> LookupEval(
7664 Handle<String> src, Handle<SharedFunctionInfo> shared,
7665 LanguageMode language_mode, int scope_position);
7666 Handle<Object> LookupRegExp(Handle<String> source, JSRegExp::Flags flags);
7667 static Handle<CompilationCacheTable> Put(
7668 Handle<CompilationCacheTable> cache, Handle<String> src,
7669 Handle<Context> context, LanguageMode language_mode,
7670 Handle<Object> value);
7671 static Handle<CompilationCacheTable> PutEval(
7672 Handle<CompilationCacheTable> cache, Handle<String> src,
7673 Handle<SharedFunctionInfo> context, Handle<SharedFunctionInfo> value,
7674 int scope_position);
7675 static Handle<CompilationCacheTable> PutRegExp(
7676 Handle<CompilationCacheTable> cache, Handle<String> src,
7677 JSRegExp::Flags flags, Handle<FixedArray> value);
7678 void Remove(Object* value);
7680 static const int kHashGenerations = 10;
7682 DECLARE_CAST(CompilationCacheTable)
7685 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
7689 class CodeCache: public Struct {
7691 DECL_ACCESSORS(default_cache, FixedArray)
7692 DECL_ACCESSORS(normal_type_cache, Object)
7694 // Add the code object to the cache.
7696 Handle<CodeCache> cache, Handle<Name> name, Handle<Code> code);
7698 // Lookup code object in the cache. Returns code object if found and undefined
7700 Object* Lookup(Name* name, Code::Flags flags);
7702 // Get the internal index of a code object in the cache. Returns -1 if the
7703 // code object is not in that cache. This index can be used to later call
7704 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
7706 int GetIndex(Object* name, Code* code);
7708 // Remove an object from the cache with the provided internal index.
7709 void RemoveByIndex(Object* name, Code* code, int index);
7711 DECLARE_CAST(CodeCache)
7713 // Dispatched behavior.
7714 DECLARE_PRINTER(CodeCache)
7715 DECLARE_VERIFIER(CodeCache)
7717 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
7718 static const int kNormalTypeCacheOffset =
7719 kDefaultCacheOffset + kPointerSize;
7720 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
7723 static void UpdateDefaultCache(
7724 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7725 static void UpdateNormalTypeCache(
7726 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7727 Object* LookupDefaultCache(Name* name, Code::Flags flags);
7728 Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
7730 // Code cache layout of the default cache. Elements are alternating name and
7731 // code objects for non normal load/store/call IC's.
7732 static const int kCodeCacheEntrySize = 2;
7733 static const int kCodeCacheEntryNameOffset = 0;
7734 static const int kCodeCacheEntryCodeOffset = 1;
7736 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
7740 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
7742 static inline bool IsMatch(HashTableKey* key, Object* value) {
7743 return key->IsMatch(value);
7746 static inline uint32_t Hash(HashTableKey* key) {
7750 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7751 return key->HashForObject(object);
7754 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7756 static const int kPrefixSize = 0;
7757 static const int kEntrySize = 2;
7761 class CodeCacheHashTable: public HashTable<CodeCacheHashTable,
7762 CodeCacheHashTableShape,
7765 Object* Lookup(Name* name, Code::Flags flags);
7766 static Handle<CodeCacheHashTable> Put(
7767 Handle<CodeCacheHashTable> table,
7771 int GetIndex(Name* name, Code::Flags flags);
7772 void RemoveByIndex(int index);
7774 DECLARE_CAST(CodeCacheHashTable)
7776 // Initial size of the fixed array backing the hash table.
7777 static const int kInitialSize = 64;
7780 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
7784 class PolymorphicCodeCache: public Struct {
7786 DECL_ACCESSORS(cache, Object)
7788 static void Update(Handle<PolymorphicCodeCache> cache,
7789 MapHandleList* maps,
7794 // Returns an undefined value if the entry is not found.
7795 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
7797 DECLARE_CAST(PolymorphicCodeCache)
7799 // Dispatched behavior.
7800 DECLARE_PRINTER(PolymorphicCodeCache)
7801 DECLARE_VERIFIER(PolymorphicCodeCache)
7803 static const int kCacheOffset = HeapObject::kHeaderSize;
7804 static const int kSize = kCacheOffset + kPointerSize;
7807 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
7811 class PolymorphicCodeCacheHashTable
7812 : public HashTable<PolymorphicCodeCacheHashTable,
7813 CodeCacheHashTableShape,
7816 Object* Lookup(MapHandleList* maps, int code_kind);
7818 static Handle<PolymorphicCodeCacheHashTable> Put(
7819 Handle<PolymorphicCodeCacheHashTable> hash_table,
7820 MapHandleList* maps,
7824 DECLARE_CAST(PolymorphicCodeCacheHashTable)
7826 static const int kInitialSize = 64;
7828 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
7832 class TypeFeedbackInfo: public Struct {
7834 inline int ic_total_count();
7835 inline void set_ic_total_count(int count);
7837 inline int ic_with_type_info_count();
7838 inline void change_ic_with_type_info_count(int delta);
7840 inline int ic_generic_count();
7841 inline void change_ic_generic_count(int delta);
7843 inline void initialize_storage();
7845 inline void change_own_type_change_checksum();
7846 inline int own_type_change_checksum();
7848 inline void set_inlined_type_change_checksum(int checksum);
7849 inline bool matches_inlined_type_change_checksum(int checksum);
7851 DECLARE_CAST(TypeFeedbackInfo)
7853 // Dispatched behavior.
7854 DECLARE_PRINTER(TypeFeedbackInfo)
7855 DECLARE_VERIFIER(TypeFeedbackInfo)
7857 static const int kStorage1Offset = HeapObject::kHeaderSize;
7858 static const int kStorage2Offset = kStorage1Offset + kPointerSize;
7859 static const int kStorage3Offset = kStorage2Offset + kPointerSize;
7860 static const int kSize = kStorage3Offset + kPointerSize;
7863 static const int kTypeChangeChecksumBits = 7;
7865 class ICTotalCountField: public BitField<int, 0,
7866 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7867 class OwnTypeChangeChecksum: public BitField<int,
7868 kSmiValueSize - kTypeChangeChecksumBits,
7869 kTypeChangeChecksumBits> {}; // NOLINT
7870 class ICsWithTypeInfoCountField: public BitField<int, 0,
7871 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7872 class InlinedTypeChangeChecksum: public BitField<int,
7873 kSmiValueSize - kTypeChangeChecksumBits,
7874 kTypeChangeChecksumBits> {}; // NOLINT
7876 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
7880 enum AllocationSiteMode {
7881 DONT_TRACK_ALLOCATION_SITE,
7882 TRACK_ALLOCATION_SITE,
7883 LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
7887 class AllocationSite: public Struct {
7889 static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
7890 static const double kPretenureRatio;
7891 static const int kPretenureMinimumCreated = 100;
7893 // Values for pretenure decision field.
7894 enum PretenureDecision {
7900 kLastPretenureDecisionValue = kZombie
7903 const char* PretenureDecisionName(PretenureDecision decision);
7905 DECL_ACCESSORS(transition_info, Object)
7906 // nested_site threads a list of sites that represent nested literals
7907 // walked in a particular order. So [[1, 2], 1, 2] will have one
7908 // nested_site, but [[1, 2], 3, [4]] will have a list of two.
7909 DECL_ACCESSORS(nested_site, Object)
7910 DECL_ACCESSORS(pretenure_data, Smi)
7911 DECL_ACCESSORS(pretenure_create_count, Smi)
7912 DECL_ACCESSORS(dependent_code, DependentCode)
7913 DECL_ACCESSORS(weak_next, Object)
7915 inline void Initialize();
7917 // This method is expensive, it should only be called for reporting.
7918 bool IsNestedSite();
7920 // transition_info bitfields, for constructed array transition info.
7921 class ElementsKindBits: public BitField<ElementsKind, 0, 15> {};
7922 class UnusedBits: public BitField<int, 15, 14> {};
7923 class DoNotInlineBit: public BitField<bool, 29, 1> {};
7925 // Bitfields for pretenure_data
7926 class MementoFoundCountBits: public BitField<int, 0, 26> {};
7927 class PretenureDecisionBits: public BitField<PretenureDecision, 26, 3> {};
7928 class DeoptDependentCodeBit: public BitField<bool, 29, 1> {};
7929 STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
7931 // Increments the mementos found counter and returns true when the first
7932 // memento was found for a given allocation site.
7933 inline bool IncrementMementoFoundCount();
7935 inline void IncrementMementoCreateCount();
7937 PretenureFlag GetPretenureMode();
7939 void ResetPretenureDecision();
7941 PretenureDecision pretenure_decision() {
7942 int value = pretenure_data()->value();
7943 return PretenureDecisionBits::decode(value);
7946 void set_pretenure_decision(PretenureDecision decision) {
7947 int value = pretenure_data()->value();
7949 Smi::FromInt(PretenureDecisionBits::update(value, decision)),
7950 SKIP_WRITE_BARRIER);
7953 bool deopt_dependent_code() {
7954 int value = pretenure_data()->value();
7955 return DeoptDependentCodeBit::decode(value);
7958 void set_deopt_dependent_code(bool deopt) {
7959 int value = pretenure_data()->value();
7961 Smi::FromInt(DeoptDependentCodeBit::update(value, deopt)),
7962 SKIP_WRITE_BARRIER);
7965 int memento_found_count() {
7966 int value = pretenure_data()->value();
7967 return MementoFoundCountBits::decode(value);
7970 inline void set_memento_found_count(int count);
7972 int memento_create_count() {
7973 return pretenure_create_count()->value();
7976 void set_memento_create_count(int count) {
7977 set_pretenure_create_count(Smi::FromInt(count), SKIP_WRITE_BARRIER);
7980 // The pretenuring decision is made during gc, and the zombie state allows
7981 // us to recognize when an allocation site is just being kept alive because
7982 // a later traversal of new space may discover AllocationMementos that point
7983 // to this AllocationSite.
7985 return pretenure_decision() == kZombie;
7988 bool IsMaybeTenure() {
7989 return pretenure_decision() == kMaybeTenure;
7992 inline void MarkZombie();
7994 inline bool MakePretenureDecision(PretenureDecision current_decision,
7996 bool maximum_size_scavenge);
7998 inline bool DigestPretenuringFeedback(bool maximum_size_scavenge);
8000 ElementsKind GetElementsKind() {
8001 DCHECK(!SitePointsToLiteral());
8002 int value = Smi::cast(transition_info())->value();
8003 return ElementsKindBits::decode(value);
8006 void SetElementsKind(ElementsKind kind) {
8007 int value = Smi::cast(transition_info())->value();
8008 set_transition_info(Smi::FromInt(ElementsKindBits::update(value, kind)),
8009 SKIP_WRITE_BARRIER);
8012 bool CanInlineCall() {
8013 int value = Smi::cast(transition_info())->value();
8014 return DoNotInlineBit::decode(value) == 0;
8017 void SetDoNotInlineCall() {
8018 int value = Smi::cast(transition_info())->value();
8019 set_transition_info(Smi::FromInt(DoNotInlineBit::update(value, true)),
8020 SKIP_WRITE_BARRIER);
8023 bool SitePointsToLiteral() {
8024 // If transition_info is a smi, then it represents an ElementsKind
8025 // for a constructed array. Otherwise, it must be a boilerplate
8026 // for an object or array literal.
8027 return transition_info()->IsJSArray() || transition_info()->IsJSObject();
8030 static void DigestTransitionFeedback(Handle<AllocationSite> site,
8031 ElementsKind to_kind);
8033 DECLARE_PRINTER(AllocationSite)
8034 DECLARE_VERIFIER(AllocationSite)
8036 DECLARE_CAST(AllocationSite)
8037 static inline AllocationSiteMode GetMode(
8038 ElementsKind boilerplate_elements_kind);
8039 static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
8040 static inline bool CanTrack(InstanceType type);
8042 static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
8043 static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
8044 static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
8045 static const int kPretenureCreateCountOffset =
8046 kPretenureDataOffset + kPointerSize;
8047 static const int kDependentCodeOffset =
8048 kPretenureCreateCountOffset + kPointerSize;
8049 static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
8050 static const int kSize = kWeakNextOffset + kPointerSize;
8052 // During mark compact we need to take special care for the dependent code
8054 static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
8055 static const int kPointerFieldsEndOffset = kWeakNextOffset;
8057 // For other visitors, use the fixed body descriptor below.
8058 typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
8059 kDependentCodeOffset + kPointerSize,
8060 kSize> BodyDescriptor;
8063 bool PretenuringDecisionMade() {
8064 return pretenure_decision() != kUndecided;
8067 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
8071 class AllocationMemento: public Struct {
8073 static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
8074 static const int kSize = kAllocationSiteOffset + kPointerSize;
8076 DECL_ACCESSORS(allocation_site, Object)
8079 return allocation_site()->IsAllocationSite() &&
8080 !AllocationSite::cast(allocation_site())->IsZombie();
8082 AllocationSite* GetAllocationSite() {
8084 return AllocationSite::cast(allocation_site());
8087 DECLARE_PRINTER(AllocationMemento)
8088 DECLARE_VERIFIER(AllocationMemento)
8090 DECLARE_CAST(AllocationMemento)
8093 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
8097 // Representation of a slow alias as part of a sloppy arguments objects.
8098 // For fast aliases (if HasSloppyArgumentsElements()):
8099 // - the parameter map contains an index into the context
8100 // - all attributes of the element have default values
8101 // For slow aliases (if HasDictionaryArgumentsElements()):
8102 // - the parameter map contains no fast alias mapping (i.e. the hole)
8103 // - this struct (in the slow backing store) contains an index into the context
8104 // - all attributes are available as part if the property details
8105 class AliasedArgumentsEntry: public Struct {
8107 inline int aliased_context_slot() const;
8108 inline void set_aliased_context_slot(int count);
8110 DECLARE_CAST(AliasedArgumentsEntry)
8112 // Dispatched behavior.
8113 DECLARE_PRINTER(AliasedArgumentsEntry)
8114 DECLARE_VERIFIER(AliasedArgumentsEntry)
8116 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
8117 static const int kSize = kAliasedContextSlot + kPointerSize;
8120 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
8124 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
8125 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
8128 class StringHasher {
8130 explicit inline StringHasher(int length, uint32_t seed);
8132 template <typename schar>
8133 static inline uint32_t HashSequentialString(const schar* chars,
8137 // Reads all the data, even for long strings and computes the utf16 length.
8138 static uint32_t ComputeUtf8Hash(Vector<const char> chars,
8140 int* utf16_length_out);
8142 // Calculated hash value for a string consisting of 1 to
8143 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
8144 // value is represented decimal value.
8145 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
8147 // No string is allowed to have a hash of zero. That value is reserved
8148 // for internal properties. If the hash calculation yields zero then we
8150 static const int kZeroHash = 27;
8152 // Reusable parts of the hashing algorithm.
8153 INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
8154 INLINE(static uint32_t GetHashCore(uint32_t running_hash));
8155 INLINE(static uint32_t ComputeRunningHash(uint32_t running_hash,
8156 const uc16* chars, int length));
8157 INLINE(static uint32_t ComputeRunningHashOneByte(uint32_t running_hash,
8162 // Returns the value to store in the hash field of a string with
8163 // the given length and contents.
8164 uint32_t GetHashField();
8165 // Returns true if the hash of this string can be computed without
8166 // looking at the contents.
8167 inline bool has_trivial_hash();
8168 // Adds a block of characters to the hash.
8169 template<typename Char>
8170 inline void AddCharacters(const Char* chars, int len);
8173 // Add a character to the hash.
8174 inline void AddCharacter(uint16_t c);
8175 // Update index. Returns true if string is still an index.
8176 inline bool UpdateIndex(uint16_t c);
8179 uint32_t raw_running_hash_;
8180 uint32_t array_index_;
8181 bool is_array_index_;
8182 bool is_first_char_;
8183 DISALLOW_COPY_AND_ASSIGN(StringHasher);
8187 class IteratingStringHasher : public StringHasher {
8189 static inline uint32_t Hash(String* string, uint32_t seed);
8190 inline void VisitOneByteString(const uint8_t* chars, int length);
8191 inline void VisitTwoByteString(const uint16_t* chars, int length);
8194 inline IteratingStringHasher(int len, uint32_t seed)
8195 : StringHasher(len, seed) {}
8196 void VisitConsString(ConsString* cons_string);
8197 DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher);
8201 // The characteristics of a string are stored in its map. Retrieving these
8202 // few bits of information is moderately expensive, involving two memory
8203 // loads where the second is dependent on the first. To improve efficiency
8204 // the shape of the string is given its own class so that it can be retrieved
8205 // once and used for several string operations. A StringShape is small enough
8206 // to be passed by value and is immutable, but be aware that flattening a
8207 // string can potentially alter its shape. Also be aware that a GC caused by
8208 // something else can alter the shape of a string due to ConsString
8209 // shortcutting. Keeping these restrictions in mind has proven to be error-
8210 // prone and so we no longer put StringShapes in variables unless there is a
8211 // concrete performance benefit at that particular point in the code.
8212 class StringShape BASE_EMBEDDED {
8214 inline explicit StringShape(const String* s);
8215 inline explicit StringShape(Map* s);
8216 inline explicit StringShape(InstanceType t);
8217 inline bool IsSequential();
8218 inline bool IsExternal();
8219 inline bool IsCons();
8220 inline bool IsSliced();
8221 inline bool IsIndirect();
8222 inline bool IsExternalOneByte();
8223 inline bool IsExternalTwoByte();
8224 inline bool IsSequentialOneByte();
8225 inline bool IsSequentialTwoByte();
8226 inline bool IsInternalized();
8227 inline StringRepresentationTag representation_tag();
8228 inline uint32_t encoding_tag();
8229 inline uint32_t full_representation_tag();
8230 inline uint32_t size_tag();
8232 inline uint32_t type() { return type_; }
8233 inline void invalidate() { valid_ = false; }
8234 inline bool valid() { return valid_; }
8236 inline void invalidate() { }
8242 inline void set_valid() { valid_ = true; }
8245 inline void set_valid() { }
8250 // The Name abstract class captures anything that can be used as a property
8251 // name, i.e., strings and symbols. All names store a hash value.
8252 class Name: public HeapObject {
8254 // Get and set the hash field of the name.
8255 inline uint32_t hash_field();
8256 inline void set_hash_field(uint32_t value);
8258 // Tells whether the hash code has been computed.
8259 inline bool HasHashCode();
8261 // Returns a hash value used for the property table
8262 inline uint32_t Hash();
8264 // Equality operations.
8265 inline bool Equals(Name* other);
8266 inline static bool Equals(Handle<Name> one, Handle<Name> two);
8269 inline bool AsArrayIndex(uint32_t* index);
8271 // If the name is private, it can only name own properties.
8272 inline bool IsPrivate();
8274 // If the name is a non-flat string, this method returns a flat version of the
8275 // string. Otherwise it'll just return the input.
8276 static inline Handle<Name> Flatten(Handle<Name> name,
8277 PretenureFlag pretenure = NOT_TENURED);
8281 DECLARE_PRINTER(Name)
8283 void NameShortPrint();
8284 int NameShortPrint(Vector<char> str);
8287 // Layout description.
8288 static const int kHashFieldSlot = HeapObject::kHeaderSize;
8289 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
8290 static const int kHashFieldOffset = kHashFieldSlot;
8292 static const int kHashFieldOffset = kHashFieldSlot + kIntSize;
8294 static const int kSize = kHashFieldSlot + kPointerSize;
8296 // Mask constant for checking if a name has a computed hash code
8297 // and if it is a string that is an array index. The least significant bit
8298 // indicates whether a hash code has been computed. If the hash code has
8299 // been computed the 2nd bit tells whether the string can be used as an
8301 static const int kHashNotComputedMask = 1;
8302 static const int kIsNotArrayIndexMask = 1 << 1;
8303 static const int kNofHashBitFields = 2;
8305 // Shift constant retrieving hash code from hash field.
8306 static const int kHashShift = kNofHashBitFields;
8308 // Only these bits are relevant in the hash, since the top two are shifted
8310 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8312 // Array index strings this short can keep their index in the hash field.
8313 static const int kMaxCachedArrayIndexLength = 7;
8315 // For strings which are array indexes the hash value has the string length
8316 // mixed into the hash, mainly to avoid a hash value of zero which would be
8317 // the case for the string '0'. 24 bits are used for the array index value.
8318 static const int kArrayIndexValueBits = 24;
8319 static const int kArrayIndexLengthBits =
8320 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8322 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8324 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8325 kArrayIndexValueBits> {}; // NOLINT
8326 class ArrayIndexLengthBits : public BitField<unsigned int,
8327 kNofHashBitFields + kArrayIndexValueBits,
8328 kArrayIndexLengthBits> {}; // NOLINT
8330 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8331 // could use a mask to test if the length of string is less than or equal to
8332 // kMaxCachedArrayIndexLength.
8333 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8335 static const unsigned int kContainsCachedArrayIndexMask =
8336 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8337 << ArrayIndexLengthBits::kShift) |
8338 kIsNotArrayIndexMask;
8340 // Value of empty hash field indicating that the hash is not computed.
8341 static const int kEmptyHashField =
8342 kIsNotArrayIndexMask | kHashNotComputedMask;
8345 static inline bool IsHashFieldComputed(uint32_t field);
8348 DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8353 class Symbol: public Name {
8355 // [name]: The print name of a symbol, or undefined if none.
8356 DECL_ACCESSORS(name, Object)
8358 DECL_ACCESSORS(flags, Smi)
8360 // [is_private]: Whether this is a private symbol. Private symbols can only
8361 // be used to designate own properties of objects.
8362 DECL_BOOLEAN_ACCESSORS(is_private)
8364 DECLARE_CAST(Symbol)
8366 // Dispatched behavior.
8367 DECLARE_PRINTER(Symbol)
8368 DECLARE_VERIFIER(Symbol)
8370 // Layout description.
8371 static const int kNameOffset = Name::kSize;
8372 static const int kFlagsOffset = kNameOffset + kPointerSize;
8373 static const int kSize = kFlagsOffset + kPointerSize;
8375 typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
8377 void SymbolShortPrint(std::ostream& os);
8380 static const int kPrivateBit = 0;
8382 const char* PrivateSymbolToName() const;
8385 friend class Name; // For PrivateSymbolToName.
8388 DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
8394 // The String abstract class captures JavaScript string values:
8397 // 4.3.16 String Value
8398 // A string value is a member of the type String and is a finite
8399 // ordered sequence of zero or more 16-bit unsigned integer values.
8401 // All string values have a length field.
8402 class String: public Name {
8404 enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
8406 // Array index strings this short can keep their index in the hash field.
8407 static const int kMaxCachedArrayIndexLength = 7;
8409 // For strings which are array indexes the hash value has the string length
8410 // mixed into the hash, mainly to avoid a hash value of zero which would be
8411 // the case for the string '0'. 24 bits are used for the array index value.
8412 static const int kArrayIndexValueBits = 24;
8413 static const int kArrayIndexLengthBits =
8414 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8416 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8418 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8419 kArrayIndexValueBits> {}; // NOLINT
8420 class ArrayIndexLengthBits : public BitField<unsigned int,
8421 kNofHashBitFields + kArrayIndexValueBits,
8422 kArrayIndexLengthBits> {}; // NOLINT
8424 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8425 // could use a mask to test if the length of string is less than or equal to
8426 // kMaxCachedArrayIndexLength.
8427 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8429 static const unsigned int kContainsCachedArrayIndexMask =
8430 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8431 << ArrayIndexLengthBits::kShift) |
8432 kIsNotArrayIndexMask;
8434 class SubStringRange {
8436 explicit SubStringRange(String* string, int first = 0, int length = -1)
8439 length_(length == -1 ? string->length() : length) {}
8441 inline iterator begin();
8442 inline iterator end();
8450 // Representation of the flat content of a String.
8451 // A non-flat string doesn't have flat content.
8452 // A flat string has content that's encoded as a sequence of either
8453 // one-byte chars or two-byte UC16.
8454 // Returned by String::GetFlatContent().
8457 // Returns true if the string is flat and this structure contains content.
8458 bool IsFlat() { return state_ != NON_FLAT; }
8459 // Returns true if the structure contains one-byte content.
8460 bool IsOneByte() { return state_ == ONE_BYTE; }
8461 // Returns true if the structure contains two-byte content.
8462 bool IsTwoByte() { return state_ == TWO_BYTE; }
8464 // Return the one byte content of the string. Only use if IsOneByte()
8466 Vector<const uint8_t> ToOneByteVector() {
8467 DCHECK_EQ(ONE_BYTE, state_);
8468 return Vector<const uint8_t>(onebyte_start, length_);
8470 // Return the two-byte content of the string. Only use if IsTwoByte()
8472 Vector<const uc16> ToUC16Vector() {
8473 DCHECK_EQ(TWO_BYTE, state_);
8474 return Vector<const uc16>(twobyte_start, length_);
8478 DCHECK(i < length_);
8479 DCHECK(state_ != NON_FLAT);
8480 if (state_ == ONE_BYTE) return onebyte_start[i];
8481 return twobyte_start[i];
8484 bool UsesSameString(const FlatContent& other) const {
8485 return onebyte_start == other.onebyte_start;
8489 enum State { NON_FLAT, ONE_BYTE, TWO_BYTE };
8491 // Constructors only used by String::GetFlatContent().
8492 explicit FlatContent(const uint8_t* start, int length)
8493 : onebyte_start(start), length_(length), state_(ONE_BYTE) {}
8494 explicit FlatContent(const uc16* start, int length)
8495 : twobyte_start(start), length_(length), state_(TWO_BYTE) { }
8496 FlatContent() : onebyte_start(NULL), length_(0), state_(NON_FLAT) { }
8499 const uint8_t* onebyte_start;
8500 const uc16* twobyte_start;
8505 friend class String;
8506 friend class IterableSubString;
8509 template <typename Char>
8510 INLINE(Vector<const Char> GetCharVector());
8512 // Get and set the length of the string.
8513 inline int length() const;
8514 inline void set_length(int value);
8516 // Get and set the length of the string using acquire loads and release
8518 inline int synchronized_length() const;
8519 inline void synchronized_set_length(int value);
8521 // Returns whether this string has only one-byte chars, i.e. all of them can
8522 // be one-byte encoded. This might be the case even if the string is
8523 // two-byte. Such strings may appear when the embedder prefers
8524 // two-byte external representations even for one-byte data.
8525 inline bool IsOneByteRepresentation() const;
8526 inline bool IsTwoByteRepresentation() const;
8528 // Cons and slices have an encoding flag that may not represent the actual
8529 // encoding of the underlying string. This is taken into account here.
8530 // Requires: this->IsFlat()
8531 inline bool IsOneByteRepresentationUnderneath();
8532 inline bool IsTwoByteRepresentationUnderneath();
8534 // NOTE: this should be considered only a hint. False negatives are
8536 inline bool HasOnlyOneByteChars();
8538 // Get and set individual two byte chars in the string.
8539 inline void Set(int index, uint16_t value);
8540 // Get individual two byte char in the string. Repeated calls
8541 // to this method are not efficient unless the string is flat.
8542 INLINE(uint16_t Get(int index));
8544 // Flattens the string. Checks first inline to see if it is
8545 // necessary. Does nothing if the string is not a cons string.
8546 // Flattening allocates a sequential string with the same data as
8547 // the given string and mutates the cons string to a degenerate
8548 // form, where the first component is the new sequential string and
8549 // the second component is the empty string. If allocation fails,
8550 // this function returns a failure. If flattening succeeds, this
8551 // function returns the sequential string that is now the first
8552 // component of the cons string.
8554 // Degenerate cons strings are handled specially by the garbage
8555 // collector (see IsShortcutCandidate).
8557 static inline Handle<String> Flatten(Handle<String> string,
8558 PretenureFlag pretenure = NOT_TENURED);
8560 // Tries to return the content of a flat string as a structure holding either
8561 // a flat vector of char or of uc16.
8562 // If the string isn't flat, and therefore doesn't have flat content, the
8563 // returned structure will report so, and can't provide a vector of either
8565 FlatContent GetFlatContent();
8567 // Returns the parent of a sliced string or first part of a flat cons string.
8568 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
8569 inline String* GetUnderlying();
8571 // String equality operations.
8572 inline bool Equals(String* other);
8573 inline static bool Equals(Handle<String> one, Handle<String> two);
8574 bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
8575 bool IsOneByteEqualTo(Vector<const uint8_t> str);
8576 bool IsTwoByteEqualTo(Vector<const uc16> str);
8578 // Return a UTF8 representation of the string. The string is null
8579 // terminated but may optionally contain nulls. Length is returned
8580 // in length_output if length_output is not a null pointer The string
8581 // should be nearly flat, otherwise the performance of this method may
8582 // be very slow (quadratic in the length). Setting robustness_flag to
8583 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8584 // handles unexpected data without causing assert failures and it does not
8585 // do any heap allocations. This is useful when printing stack traces.
8586 base::SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
8587 RobustnessFlag robustness_flag,
8588 int offset, int length,
8589 int* length_output = 0);
8590 base::SmartArrayPointer<char> ToCString(
8591 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
8592 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
8593 int* length_output = 0);
8595 // Return a 16 bit Unicode representation of the string.
8596 // The string should be nearly flat, otherwise the performance of
8597 // of this method may be very bad. Setting robustness_flag to
8598 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8599 // handles unexpected data without causing assert failures and it does not
8600 // do any heap allocations. This is useful when printing stack traces.
8601 base::SmartArrayPointer<uc16> ToWideCString(
8602 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
8604 bool ComputeArrayIndex(uint32_t* index);
8607 bool MakeExternal(v8::String::ExternalStringResource* resource);
8608 bool MakeExternal(v8::String::ExternalOneByteStringResource* resource);
8611 inline bool AsArrayIndex(uint32_t* index);
8613 DECLARE_CAST(String)
8615 void PrintOn(FILE* out);
8617 // For use during stack traces. Performs rudimentary sanity check.
8620 // Dispatched behavior.
8621 void StringShortPrint(StringStream* accumulator);
8622 void PrintUC16(std::ostream& os, int start = 0, int end = -1); // NOLINT
8623 #if defined(DEBUG) || defined(OBJECT_PRINT)
8624 char* ToAsciiArray();
8626 DECLARE_PRINTER(String)
8627 DECLARE_VERIFIER(String)
8629 inline bool IsFlat();
8631 // Layout description.
8632 static const int kLengthOffset = Name::kSize;
8633 static const int kSize = kLengthOffset + kPointerSize;
8635 // Maximum number of characters to consider when trying to convert a string
8636 // value into an array index.
8637 static const int kMaxArrayIndexSize = 10;
8638 STATIC_ASSERT(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
8641 static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
8642 static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
8643 static const int kMaxUtf16CodeUnit = 0xffff;
8644 static const uint32_t kMaxUtf16CodeUnitU = kMaxUtf16CodeUnit;
8646 // Value of hash field containing computed hash equal to zero.
8647 static const int kEmptyStringHash = kIsNotArrayIndexMask;
8649 // Maximal string length.
8650 static const int kMaxLength = (1 << 28) - 16;
8652 // Max length for computing hash. For strings longer than this limit the
8653 // string length is used as the hash value.
8654 static const int kMaxHashCalcLength = 16383;
8656 // Limit for truncation in short printing.
8657 static const int kMaxShortPrintLength = 1024;
8659 // Support for regular expressions.
8660 const uc16* GetTwoByteData(unsigned start);
8662 // Helper function for flattening strings.
8663 template <typename sinkchar>
8664 static void WriteToFlat(String* source,
8669 // The return value may point to the first aligned word containing the first
8670 // non-one-byte character, rather than directly to the non-one-byte character.
8671 // If the return value is >= the passed length, the entire string was
8673 static inline int NonAsciiStart(const char* chars, int length) {
8674 const char* start = chars;
8675 const char* limit = chars + length;
8677 if (length >= kIntptrSize) {
8678 // Check unaligned bytes.
8679 while (!IsAligned(reinterpret_cast<intptr_t>(chars), sizeof(uintptr_t))) {
8680 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8681 return static_cast<int>(chars - start);
8685 // Check aligned words.
8686 DCHECK(unibrow::Utf8::kMaxOneByteChar == 0x7F);
8687 const uintptr_t non_one_byte_mask = kUintptrAllBitsSet / 0xFF * 0x80;
8688 while (chars + sizeof(uintptr_t) <= limit) {
8689 if (*reinterpret_cast<const uintptr_t*>(chars) & non_one_byte_mask) {
8690 return static_cast<int>(chars - start);
8692 chars += sizeof(uintptr_t);
8695 // Check remaining unaligned bytes.
8696 while (chars < limit) {
8697 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8698 return static_cast<int>(chars - start);
8703 return static_cast<int>(chars - start);
8706 static inline bool IsAscii(const char* chars, int length) {
8707 return NonAsciiStart(chars, length) >= length;
8710 static inline bool IsAscii(const uint8_t* chars, int length) {
8712 NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
8715 static inline int NonOneByteStart(const uc16* chars, int length) {
8716 const uc16* limit = chars + length;
8717 const uc16* start = chars;
8718 while (chars < limit) {
8719 if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
8722 return static_cast<int>(chars - start);
8725 static inline bool IsOneByte(const uc16* chars, int length) {
8726 return NonOneByteStart(chars, length) >= length;
8729 template<class Visitor>
8730 static inline ConsString* VisitFlat(Visitor* visitor,
8734 static Handle<FixedArray> CalculateLineEnds(Handle<String> string,
8735 bool include_ending_line);
8737 // Use the hash field to forward to the canonical internalized string
8738 // when deserializing an internalized string.
8739 inline void SetForwardedInternalizedString(String* string);
8740 inline String* GetForwardedInternalizedString();
8744 friend class StringTableInsertionKey;
8746 static Handle<String> SlowFlatten(Handle<ConsString> cons,
8747 PretenureFlag tenure);
8749 // Slow case of String::Equals. This implementation works on any strings
8750 // but it is most efficient on strings that are almost flat.
8751 bool SlowEquals(String* other);
8753 static bool SlowEquals(Handle<String> one, Handle<String> two);
8755 // Slow case of AsArrayIndex.
8756 bool SlowAsArrayIndex(uint32_t* index);
8758 // Compute and set the hash code.
8759 uint32_t ComputeAndSetHash();
8761 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
8765 // The SeqString abstract class captures sequential string values.
8766 class SeqString: public String {
8768 DECLARE_CAST(SeqString)
8770 // Layout description.
8771 static const int kHeaderSize = String::kSize;
8773 // Truncate the string in-place if possible and return the result.
8774 // In case of new_length == 0, the empty string is returned without
8775 // truncating the original string.
8776 MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
8779 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
8783 // The OneByteString class captures sequential one-byte string objects.
8784 // Each character in the OneByteString is an one-byte character.
8785 class SeqOneByteString: public SeqString {
8787 static const bool kHasOneByteEncoding = true;
8789 // Dispatched behavior.
8790 inline uint16_t SeqOneByteStringGet(int index);
8791 inline void SeqOneByteStringSet(int index, uint16_t value);
8793 // Get the address of the characters in this string.
8794 inline Address GetCharsAddress();
8796 inline uint8_t* GetChars();
8798 DECLARE_CAST(SeqOneByteString)
8800 // Garbage collection support. This method is called by the
8801 // garbage collector to compute the actual size of an OneByteString
8803 inline int SeqOneByteStringSize(InstanceType instance_type);
8805 // Computes the size for an OneByteString instance of a given length.
8806 static int SizeFor(int length) {
8807 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
8810 // Maximal memory usage for a single sequential one-byte string.
8811 static const int kMaxSize = 512 * MB - 1;
8812 STATIC_ASSERT((kMaxSize - kHeaderSize) >= String::kMaxLength);
8815 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
8819 // The TwoByteString class captures sequential unicode string objects.
8820 // Each character in the TwoByteString is a two-byte uint16_t.
8821 class SeqTwoByteString: public SeqString {
8823 static const bool kHasOneByteEncoding = false;
8825 // Dispatched behavior.
8826 inline uint16_t SeqTwoByteStringGet(int index);
8827 inline void SeqTwoByteStringSet(int index, uint16_t value);
8829 // Get the address of the characters in this string.
8830 inline Address GetCharsAddress();
8832 inline uc16* GetChars();
8835 const uint16_t* SeqTwoByteStringGetData(unsigned start);
8837 DECLARE_CAST(SeqTwoByteString)
8839 // Garbage collection support. This method is called by the
8840 // garbage collector to compute the actual size of a TwoByteString
8842 inline int SeqTwoByteStringSize(InstanceType instance_type);
8844 // Computes the size for a TwoByteString instance of a given length.
8845 static int SizeFor(int length) {
8846 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
8849 // Maximal memory usage for a single sequential two-byte string.
8850 static const int kMaxSize = 512 * MB - 1;
8851 STATIC_ASSERT(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
8852 String::kMaxLength);
8855 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
8859 // The ConsString class describes string values built by using the
8860 // addition operator on strings. A ConsString is a pair where the
8861 // first and second components are pointers to other string values.
8862 // One or both components of a ConsString can be pointers to other
8863 // ConsStrings, creating a binary tree of ConsStrings where the leaves
8864 // are non-ConsString string values. The string value represented by
8865 // a ConsString can be obtained by concatenating the leaf string
8866 // values in a left-to-right depth-first traversal of the tree.
8867 class ConsString: public String {
8869 // First string of the cons cell.
8870 inline String* first();
8871 // Doesn't check that the result is a string, even in debug mode. This is
8872 // useful during GC where the mark bits confuse the checks.
8873 inline Object* unchecked_first();
8874 inline void set_first(String* first,
8875 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8877 // Second string of the cons cell.
8878 inline String* second();
8879 // Doesn't check that the result is a string, even in debug mode. This is
8880 // useful during GC where the mark bits confuse the checks.
8881 inline Object* unchecked_second();
8882 inline void set_second(String* second,
8883 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8885 // Dispatched behavior.
8886 uint16_t ConsStringGet(int index);
8888 DECLARE_CAST(ConsString)
8890 // Layout description.
8891 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
8892 static const int kSecondOffset = kFirstOffset + kPointerSize;
8893 static const int kSize = kSecondOffset + kPointerSize;
8895 // Minimum length for a cons string.
8896 static const int kMinLength = 13;
8898 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
8901 DECLARE_VERIFIER(ConsString)
8904 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
8908 // The Sliced String class describes strings that are substrings of another
8909 // sequential string. The motivation is to save time and memory when creating
8910 // a substring. A Sliced String is described as a pointer to the parent,
8911 // the offset from the start of the parent string and the length. Using
8912 // a Sliced String therefore requires unpacking of the parent string and
8913 // adding the offset to the start address. A substring of a Sliced String
8914 // are not nested since the double indirection is simplified when creating
8915 // such a substring.
8916 // Currently missing features are:
8917 // - handling externalized parent strings
8918 // - external strings as parent
8919 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
8920 class SlicedString: public String {
8922 inline String* parent();
8923 inline void set_parent(String* parent,
8924 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8925 inline int offset() const;
8926 inline void set_offset(int offset);
8928 // Dispatched behavior.
8929 uint16_t SlicedStringGet(int index);
8931 DECLARE_CAST(SlicedString)
8933 // Layout description.
8934 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
8935 static const int kOffsetOffset = kParentOffset + kPointerSize;
8936 static const int kSize = kOffsetOffset + kPointerSize;
8938 // Minimum length for a sliced string.
8939 static const int kMinLength = 13;
8941 typedef FixedBodyDescriptor<kParentOffset,
8942 kOffsetOffset + kPointerSize, kSize>
8945 DECLARE_VERIFIER(SlicedString)
8948 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
8952 // The ExternalString class describes string values that are backed by
8953 // a string resource that lies outside the V8 heap. ExternalStrings
8954 // consist of the length field common to all strings, a pointer to the
8955 // external resource. It is important to ensure (externally) that the
8956 // resource is not deallocated while the ExternalString is live in the
8959 // The API expects that all ExternalStrings are created through the
8960 // API. Therefore, ExternalStrings should not be used internally.
8961 class ExternalString: public String {
8963 DECLARE_CAST(ExternalString)
8965 // Layout description.
8966 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
8967 static const int kShortSize = kResourceOffset + kPointerSize;
8968 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
8969 static const int kSize = kResourceDataOffset + kPointerSize;
8971 static const int kMaxShortLength =
8972 (kShortSize - SeqString::kHeaderSize) / kCharSize;
8974 // Return whether external string is short (data pointer is not cached).
8975 inline bool is_short();
8977 STATIC_ASSERT(kResourceOffset == Internals::kStringResourceOffset);
8980 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
8984 // The ExternalOneByteString class is an external string backed by an
8986 class ExternalOneByteString : public ExternalString {
8988 static const bool kHasOneByteEncoding = true;
8990 typedef v8::String::ExternalOneByteStringResource Resource;
8992 // The underlying resource.
8993 inline const Resource* resource();
8994 inline void set_resource(const Resource* buffer);
8996 // Update the pointer cache to the external character array.
8997 // The cached pointer is always valid, as the external character array does =
8998 // not move during lifetime. Deserialization is the only exception, after
8999 // which the pointer cache has to be refreshed.
9000 inline void update_data_cache();
9002 inline const uint8_t* GetChars();
9004 // Dispatched behavior.
9005 inline uint16_t ExternalOneByteStringGet(int index);
9007 DECLARE_CAST(ExternalOneByteString)
9009 // Garbage collection support.
9010 inline void ExternalOneByteStringIterateBody(ObjectVisitor* v);
9012 template <typename StaticVisitor>
9013 inline void ExternalOneByteStringIterateBody();
9016 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalOneByteString);
9020 // The ExternalTwoByteString class is an external string backed by a UTF-16
9022 class ExternalTwoByteString: public ExternalString {
9024 static const bool kHasOneByteEncoding = false;
9026 typedef v8::String::ExternalStringResource Resource;
9028 // The underlying string resource.
9029 inline const Resource* resource();
9030 inline void set_resource(const Resource* buffer);
9032 // Update the pointer cache to the external character array.
9033 // The cached pointer is always valid, as the external character array does =
9034 // not move during lifetime. Deserialization is the only exception, after
9035 // which the pointer cache has to be refreshed.
9036 inline void update_data_cache();
9038 inline const uint16_t* GetChars();
9040 // Dispatched behavior.
9041 inline uint16_t ExternalTwoByteStringGet(int index);
9044 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
9046 DECLARE_CAST(ExternalTwoByteString)
9048 // Garbage collection support.
9049 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
9051 template<typename StaticVisitor>
9052 inline void ExternalTwoByteStringIterateBody();
9055 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
9059 // Utility superclass for stack-allocated objects that must be updated
9060 // on gc. It provides two ways for the gc to update instances, either
9061 // iterating or updating after gc.
9062 class Relocatable BASE_EMBEDDED {
9064 explicit inline Relocatable(Isolate* isolate);
9065 inline virtual ~Relocatable();
9066 virtual void IterateInstance(ObjectVisitor* v) { }
9067 virtual void PostGarbageCollection() { }
9069 static void PostGarbageCollectionProcessing(Isolate* isolate);
9070 static int ArchiveSpacePerThread();
9071 static char* ArchiveState(Isolate* isolate, char* to);
9072 static char* RestoreState(Isolate* isolate, char* from);
9073 static void Iterate(Isolate* isolate, ObjectVisitor* v);
9074 static void Iterate(ObjectVisitor* v, Relocatable* top);
9075 static char* Iterate(ObjectVisitor* v, char* t);
9083 // A flat string reader provides random access to the contents of a
9084 // string independent of the character width of the string. The handle
9085 // must be valid as long as the reader is being used.
9086 class FlatStringReader : public Relocatable {
9088 FlatStringReader(Isolate* isolate, Handle<String> str);
9089 FlatStringReader(Isolate* isolate, Vector<const char> input);
9090 void PostGarbageCollection();
9091 inline uc32 Get(int index);
9092 template <typename Char>
9093 inline Char Get(int index);
9094 int length() { return length_; }
9103 // This maintains an off-stack representation of the stack frames required
9104 // to traverse a ConsString, allowing an entirely iterative and restartable
9105 // traversal of the entire string
9106 class ConsStringIterator {
9108 inline ConsStringIterator() {}
9109 inline explicit ConsStringIterator(ConsString* cons_string, int offset = 0) {
9110 Reset(cons_string, offset);
9112 inline void Reset(ConsString* cons_string, int offset = 0) {
9114 // Next will always return NULL.
9115 if (cons_string == NULL) return;
9116 Initialize(cons_string, offset);
9118 // Returns NULL when complete.
9119 inline String* Next(int* offset_out) {
9121 if (depth_ == 0) return NULL;
9122 return Continue(offset_out);
9126 static const int kStackSize = 32;
9127 // Use a mask instead of doing modulo operations for stack wrapping.
9128 static const int kDepthMask = kStackSize-1;
9129 STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
9130 static inline int OffsetForDepth(int depth);
9132 inline void PushLeft(ConsString* string);
9133 inline void PushRight(ConsString* string);
9134 inline void AdjustMaximumDepth();
9136 inline bool StackBlown() { return maximum_depth_ - depth_ == kStackSize; }
9137 void Initialize(ConsString* cons_string, int offset);
9138 String* Continue(int* offset_out);
9139 String* NextLeaf(bool* blew_stack);
9140 String* Search(int* offset_out);
9142 // Stack must always contain only frames for which right traversal
9143 // has not yet been performed.
9144 ConsString* frames_[kStackSize];
9149 DISALLOW_COPY_AND_ASSIGN(ConsStringIterator);
9153 class StringCharacterStream {
9155 inline StringCharacterStream(String* string,
9157 inline uint16_t GetNext();
9158 inline bool HasMore();
9159 inline void Reset(String* string, int offset = 0);
9160 inline void VisitOneByteString(const uint8_t* chars, int length);
9161 inline void VisitTwoByteString(const uint16_t* chars, int length);
9164 ConsStringIterator iter_;
9167 const uint8_t* buffer8_;
9168 const uint16_t* buffer16_;
9170 const uint8_t* end_;
9171 DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
9175 template <typename T>
9176 class VectorIterator {
9178 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
9179 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
9180 T GetNext() { return data_[index_++]; }
9181 bool has_more() { return index_ < data_.length(); }
9183 Vector<const T> data_;
9188 // The Oddball describes objects null, undefined, true, and false.
9189 class Oddball: public HeapObject {
9191 // [to_string]: Cached to_string computed at startup.
9192 DECL_ACCESSORS(to_string, String)
9194 // [to_number]: Cached to_number computed at startup.
9195 DECL_ACCESSORS(to_number, Object)
9197 inline byte kind() const;
9198 inline void set_kind(byte kind);
9200 DECLARE_CAST(Oddball)
9202 // Dispatched behavior.
9203 DECLARE_VERIFIER(Oddball)
9205 // Initialize the fields.
9206 static void Initialize(Isolate* isolate,
9207 Handle<Oddball> oddball,
9208 const char* to_string,
9209 Handle<Object> to_number,
9212 // Layout description.
9213 static const int kToStringOffset = HeapObject::kHeaderSize;
9214 static const int kToNumberOffset = kToStringOffset + kPointerSize;
9215 static const int kKindOffset = kToNumberOffset + kPointerSize;
9216 static const int kSize = kKindOffset + kPointerSize;
9218 static const byte kFalse = 0;
9219 static const byte kTrue = 1;
9220 static const byte kNotBooleanMask = ~1;
9221 static const byte kTheHole = 2;
9222 static const byte kNull = 3;
9223 static const byte kArgumentMarker = 4;
9224 static const byte kUndefined = 5;
9225 static const byte kUninitialized = 6;
9226 static const byte kOther = 7;
9227 static const byte kException = 8;
9229 typedef FixedBodyDescriptor<kToStringOffset,
9230 kToNumberOffset + kPointerSize,
9231 kSize> BodyDescriptor;
9233 STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset);
9234 STATIC_ASSERT(kNull == Internals::kNullOddballKind);
9235 STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind);
9238 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
9242 class Cell: public HeapObject {
9244 // [value]: value of the cell.
9245 DECL_ACCESSORS(value, Object)
9249 static inline Cell* FromValueAddress(Address value) {
9250 Object* result = FromAddress(value - kValueOffset);
9251 return static_cast<Cell*>(result);
9254 inline Address ValueAddress() {
9255 return address() + kValueOffset;
9258 // Dispatched behavior.
9259 DECLARE_PRINTER(Cell)
9260 DECLARE_VERIFIER(Cell)
9262 // Layout description.
9263 static const int kValueOffset = HeapObject::kHeaderSize;
9264 static const int kSize = kValueOffset + kPointerSize;
9266 typedef FixedBodyDescriptor<kValueOffset,
9267 kValueOffset + kPointerSize,
9268 kSize> BodyDescriptor;
9271 DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9275 class PropertyCell : public HeapObject {
9277 // [property_details]: details of the global property.
9278 DECL_ACCESSORS(property_details_raw, Object)
9279 // [value]: value of the global property.
9280 DECL_ACCESSORS(value, Object)
9281 // [dependent_code]: dependent code that depends on the type of the global
9283 DECL_ACCESSORS(dependent_code, DependentCode)
9285 PropertyDetails property_details() {
9286 return PropertyDetails(Smi::cast(property_details_raw()));
9289 void set_property_details(PropertyDetails details) {
9290 set_property_details_raw(details.AsSmi());
9293 PropertyCellConstantType GetConstantType();
9295 // Computes the new type of the cell's contents for the given value, but
9296 // without actually modifying the details.
9297 static PropertyCellType UpdatedType(Handle<PropertyCell> cell,
9298 Handle<Object> value,
9299 PropertyDetails details);
9300 static void UpdateCell(Handle<GlobalDictionary> dictionary, int entry,
9301 Handle<Object> value, PropertyDetails details);
9303 static Handle<PropertyCell> InvalidateEntry(
9304 Handle<GlobalDictionary> dictionary, int entry);
9306 static void SetValueWithInvalidation(Handle<PropertyCell> cell,
9307 Handle<Object> new_value);
9309 DECLARE_CAST(PropertyCell)
9311 // Dispatched behavior.
9312 DECLARE_PRINTER(PropertyCell)
9313 DECLARE_VERIFIER(PropertyCell)
9315 // Layout description.
9316 static const int kDetailsOffset = HeapObject::kHeaderSize;
9317 static const int kValueOffset = kDetailsOffset + kPointerSize;
9318 static const int kDependentCodeOffset = kValueOffset + kPointerSize;
9319 static const int kSize = kDependentCodeOffset + kPointerSize;
9321 static const int kPointerFieldsBeginOffset = kValueOffset;
9322 static const int kPointerFieldsEndOffset = kSize;
9324 typedef FixedBodyDescriptor<kValueOffset,
9326 kSize> BodyDescriptor;
9329 DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9333 class WeakCell : public HeapObject {
9335 inline Object* value() const;
9337 // This should not be called by anyone except GC.
9338 inline void clear();
9340 // This should not be called by anyone except allocator.
9341 inline void initialize(HeapObject* value);
9343 inline bool cleared() const;
9345 DECL_ACCESSORS(next, Object)
9347 inline void clear_next(Heap* heap);
9349 inline bool next_cleared();
9351 DECLARE_CAST(WeakCell)
9353 DECLARE_PRINTER(WeakCell)
9354 DECLARE_VERIFIER(WeakCell)
9356 // Layout description.
9357 static const int kValueOffset = HeapObject::kHeaderSize;
9358 static const int kNextOffset = kValueOffset + kPointerSize;
9359 static const int kSize = kNextOffset + kPointerSize;
9361 typedef FixedBodyDescriptor<kValueOffset, kSize, kSize> BodyDescriptor;
9364 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakCell);
9368 // The JSProxy describes EcmaScript Harmony proxies
9369 class JSProxy: public JSReceiver {
9371 // [handler]: The handler property.
9372 DECL_ACCESSORS(handler, Object)
9374 // [hash]: The hash code property (undefined if not initialized yet).
9375 DECL_ACCESSORS(hash, Object)
9377 DECLARE_CAST(JSProxy)
9379 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithHandler(
9380 Handle<JSProxy> proxy,
9381 Handle<Object> receiver,
9384 // If the handler defines an accessor property with a setter, invoke it.
9385 // If it defines an accessor property without a setter, or a data property
9386 // that is read-only, throw. In all these cases set '*done' to true,
9387 // otherwise set it to false.
9389 static MaybeHandle<Object> SetPropertyViaPrototypesWithHandler(
9390 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9391 Handle<Object> value, LanguageMode language_mode, bool* done);
9393 MUST_USE_RESULT static Maybe<PropertyAttributes>
9394 GetPropertyAttributesWithHandler(Handle<JSProxy> proxy,
9395 Handle<Object> receiver,
9397 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithHandler(
9398 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9399 Handle<Object> value, LanguageMode language_mode);
9401 // Turn the proxy into an (empty) JSObject.
9402 static void Fix(Handle<JSProxy> proxy);
9404 // Initializes the body after the handler slot.
9405 inline void InitializeBody(int object_size, Object* value);
9407 // Invoke a trap by name. If the trap does not exist on this's handler,
9408 // but derived_trap is non-NULL, invoke that instead. May cause GC.
9409 MUST_USE_RESULT static MaybeHandle<Object> CallTrap(
9410 Handle<JSProxy> proxy,
9412 Handle<Object> derived_trap,
9414 Handle<Object> args[]);
9416 // Dispatched behavior.
9417 DECLARE_PRINTER(JSProxy)
9418 DECLARE_VERIFIER(JSProxy)
9420 // Layout description. We add padding so that a proxy has the same
9421 // size as a virgin JSObject. This is essential for becoming a JSObject
9423 static const int kHandlerOffset = HeapObject::kHeaderSize;
9424 static const int kHashOffset = kHandlerOffset + kPointerSize;
9425 static const int kPaddingOffset = kHashOffset + kPointerSize;
9426 static const int kSize = JSObject::kHeaderSize;
9427 static const int kHeaderSize = kPaddingOffset;
9428 static const int kPaddingSize = kSize - kPaddingOffset;
9430 STATIC_ASSERT(kPaddingSize >= 0);
9432 typedef FixedBodyDescriptor<kHandlerOffset,
9434 kSize> BodyDescriptor;
9437 friend class JSReceiver;
9439 MUST_USE_RESULT static Maybe<bool> HasPropertyWithHandler(
9440 Handle<JSProxy> proxy, Handle<Name> name);
9442 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithHandler(
9443 Handle<JSProxy> proxy, Handle<Name> name, LanguageMode language_mode);
9445 MUST_USE_RESULT Object* GetIdentityHash();
9447 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
9449 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
9453 class JSFunctionProxy: public JSProxy {
9455 // [call_trap]: The call trap.
9456 DECL_ACCESSORS(call_trap, Object)
9458 // [construct_trap]: The construct trap.
9459 DECL_ACCESSORS(construct_trap, Object)
9461 DECLARE_CAST(JSFunctionProxy)
9463 // Dispatched behavior.
9464 DECLARE_PRINTER(JSFunctionProxy)
9465 DECLARE_VERIFIER(JSFunctionProxy)
9467 // Layout description.
9468 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
9469 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
9470 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
9471 static const int kSize = JSFunction::kSize;
9472 static const int kPaddingSize = kSize - kPaddingOffset;
9474 STATIC_ASSERT(kPaddingSize >= 0);
9476 typedef FixedBodyDescriptor<kHandlerOffset,
9477 kConstructTrapOffset + kPointerSize,
9478 kSize> BodyDescriptor;
9481 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
9485 class JSCollection : public JSObject {
9487 // [table]: the backing hash table
9488 DECL_ACCESSORS(table, Object)
9490 static const int kTableOffset = JSObject::kHeaderSize;
9491 static const int kSize = kTableOffset + kPointerSize;
9494 DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollection);
9498 // The JSSet describes EcmaScript Harmony sets
9499 class JSSet : public JSCollection {
9503 // Dispatched behavior.
9504 DECLARE_PRINTER(JSSet)
9505 DECLARE_VERIFIER(JSSet)
9508 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
9512 // The JSMap describes EcmaScript Harmony maps
9513 class JSMap : public JSCollection {
9517 // Dispatched behavior.
9518 DECLARE_PRINTER(JSMap)
9519 DECLARE_VERIFIER(JSMap)
9522 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
9526 // OrderedHashTableIterator is an iterator that iterates over the keys and
9527 // values of an OrderedHashTable.
9529 // The iterator has a reference to the underlying OrderedHashTable data,
9530 // [table], as well as the current [index] the iterator is at.
9532 // When the OrderedHashTable is rehashed it adds a reference from the old table
9533 // to the new table as well as storing enough data about the changes so that the
9534 // iterator [index] can be adjusted accordingly.
9536 // When the [Next] result from the iterator is requested, the iterator checks if
9537 // there is a newer table that it needs to transition to.
9538 template<class Derived, class TableType>
9539 class OrderedHashTableIterator: public JSObject {
9541 // [table]: the backing hash table mapping keys to values.
9542 DECL_ACCESSORS(table, Object)
9544 // [index]: The index into the data table.
9545 DECL_ACCESSORS(index, Object)
9547 // [kind]: The kind of iteration this is. One of the [Kind] enum values.
9548 DECL_ACCESSORS(kind, Object)
9551 void OrderedHashTableIteratorPrint(std::ostream& os); // NOLINT
9554 static const int kTableOffset = JSObject::kHeaderSize;
9555 static const int kIndexOffset = kTableOffset + kPointerSize;
9556 static const int kKindOffset = kIndexOffset + kPointerSize;
9557 static const int kSize = kKindOffset + kPointerSize;
9565 // Whether the iterator has more elements. This needs to be called before
9566 // calling |CurrentKey| and/or |CurrentValue|.
9569 // Move the index forward one.
9571 set_index(Smi::FromInt(Smi::cast(index())->value() + 1));
9574 // Populates the array with the next key and value and then moves the iterator
9576 // This returns the |kind| or 0 if the iterator is already at the end.
9577 Smi* Next(JSArray* value_array);
9579 // Returns the current key of the iterator. This should only be called when
9580 // |HasMore| returns true.
9581 inline Object* CurrentKey();
9584 // Transitions the iterator to the non obsolete backing store. This is a NOP
9585 // if the [table] is not obsolete.
9588 DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
9592 class JSSetIterator: public OrderedHashTableIterator<JSSetIterator,
9595 // Dispatched behavior.
9596 DECLARE_PRINTER(JSSetIterator)
9597 DECLARE_VERIFIER(JSSetIterator)
9599 DECLARE_CAST(JSSetIterator)
9601 // Called by |Next| to populate the array. This allows the subclasses to
9602 // populate the array differently.
9603 inline void PopulateValueArray(FixedArray* array);
9606 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSetIterator);
9610 class JSMapIterator: public OrderedHashTableIterator<JSMapIterator,
9613 // Dispatched behavior.
9614 DECLARE_PRINTER(JSMapIterator)
9615 DECLARE_VERIFIER(JSMapIterator)
9617 DECLARE_CAST(JSMapIterator)
9619 // Called by |Next| to populate the array. This allows the subclasses to
9620 // populate the array differently.
9621 inline void PopulateValueArray(FixedArray* array);
9624 // Returns the current value of the iterator. This should only be called when
9625 // |HasMore| returns true.
9626 inline Object* CurrentValue();
9628 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMapIterator);
9632 // Base class for both JSWeakMap and JSWeakSet
9633 class JSWeakCollection: public JSObject {
9635 // [table]: the backing hash table mapping keys to values.
9636 DECL_ACCESSORS(table, Object)
9638 // [next]: linked list of encountered weak maps during GC.
9639 DECL_ACCESSORS(next, Object)
9641 static const int kTableOffset = JSObject::kHeaderSize;
9642 static const int kNextOffset = kTableOffset + kPointerSize;
9643 static const int kSize = kNextOffset + kPointerSize;
9646 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
9650 // The JSWeakMap describes EcmaScript Harmony weak maps
9651 class JSWeakMap: public JSWeakCollection {
9653 DECLARE_CAST(JSWeakMap)
9655 // Dispatched behavior.
9656 DECLARE_PRINTER(JSWeakMap)
9657 DECLARE_VERIFIER(JSWeakMap)
9660 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
9664 // The JSWeakSet describes EcmaScript Harmony weak sets
9665 class JSWeakSet: public JSWeakCollection {
9667 DECLARE_CAST(JSWeakSet)
9669 // Dispatched behavior.
9670 DECLARE_PRINTER(JSWeakSet)
9671 DECLARE_VERIFIER(JSWeakSet)
9674 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
9678 // Whether a JSArrayBuffer is a SharedArrayBuffer or not.
9679 enum class SharedFlag { kNotShared, kShared };
9682 class JSArrayBuffer: public JSObject {
9684 // [backing_store]: backing memory for this array
9685 DECL_ACCESSORS(backing_store, void)
9687 // [byte_length]: length in bytes
9688 DECL_ACCESSORS(byte_length, Object)
9690 inline uint32_t bit_field() const;
9691 inline void set_bit_field(uint32_t bits);
9693 inline bool is_external();
9694 inline void set_is_external(bool value);
9696 inline bool is_neuterable();
9697 inline void set_is_neuterable(bool value);
9699 inline bool was_neutered();
9700 inline void set_was_neutered(bool value);
9702 inline bool is_shared();
9703 inline void set_is_shared(bool value);
9705 DECLARE_CAST(JSArrayBuffer)
9709 // Dispatched behavior.
9710 DECLARE_PRINTER(JSArrayBuffer)
9711 DECLARE_VERIFIER(JSArrayBuffer)
9713 static const int kBackingStoreOffset = JSObject::kHeaderSize;
9714 static const int kByteLengthOffset = kBackingStoreOffset + kPointerSize;
9715 static const int kBitFieldSlot = kByteLengthOffset + kPointerSize;
9716 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
9717 static const int kBitFieldOffset = kBitFieldSlot;
9719 static const int kBitFieldOffset = kBitFieldSlot + kIntSize;
9721 static const int kSize = kBitFieldSlot + kPointerSize;
9723 static const int kSizeWithInternalFields =
9724 kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
9726 class IsExternal : public BitField<bool, 1, 1> {};
9727 class IsNeuterable : public BitField<bool, 2, 1> {};
9728 class WasNeutered : public BitField<bool, 3, 1> {};
9729 class IsShared : public BitField<bool, 4, 1> {};
9732 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
9736 class JSArrayBufferView: public JSObject {
9738 // [buffer]: ArrayBuffer that this typed array views.
9739 DECL_ACCESSORS(buffer, Object)
9741 // [byte_offset]: offset of typed array in bytes.
9742 DECL_ACCESSORS(byte_offset, Object)
9744 // [byte_length]: length of typed array in bytes.
9745 DECL_ACCESSORS(byte_length, Object)
9747 DECLARE_CAST(JSArrayBufferView)
9749 DECLARE_VERIFIER(JSArrayBufferView)
9751 inline bool WasNeutered() const;
9753 static const int kBufferOffset = JSObject::kHeaderSize;
9754 static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
9755 static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
9756 static const int kViewSize = kByteLengthOffset + kPointerSize;
9760 DECL_ACCESSORS(raw_byte_offset, Object)
9761 DECL_ACCESSORS(raw_byte_length, Object)
9764 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
9768 class JSTypedArray: public JSArrayBufferView {
9770 // [length]: length of typed array in elements.
9771 DECL_ACCESSORS(length, Object)
9772 inline uint32_t length_value() const;
9774 DECLARE_CAST(JSTypedArray)
9776 ExternalArrayType type();
9777 size_t element_size();
9779 Handle<JSArrayBuffer> GetBuffer();
9781 // Dispatched behavior.
9782 DECLARE_PRINTER(JSTypedArray)
9783 DECLARE_VERIFIER(JSTypedArray)
9785 static const int kLengthOffset = kViewSize + kPointerSize;
9786 static const int kSize = kLengthOffset + kPointerSize;
9788 static const int kSizeWithInternalFields =
9789 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9792 static Handle<JSArrayBuffer> MaterializeArrayBuffer(
9793 Handle<JSTypedArray> typed_array);
9795 DECL_ACCESSORS(raw_length, Object)
9798 DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
9802 class JSDataView: public JSArrayBufferView {
9804 DECLARE_CAST(JSDataView)
9806 // Dispatched behavior.
9807 DECLARE_PRINTER(JSDataView)
9808 DECLARE_VERIFIER(JSDataView)
9810 static const int kSize = kViewSize;
9812 static const int kSizeWithInternalFields =
9813 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9816 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
9820 // Foreign describes objects pointing from JavaScript to C structures.
9821 class Foreign: public HeapObject {
9823 // [address]: field containing the address.
9824 inline Address foreign_address();
9825 inline void set_foreign_address(Address value);
9827 DECLARE_CAST(Foreign)
9829 // Dispatched behavior.
9830 inline void ForeignIterateBody(ObjectVisitor* v);
9832 template<typename StaticVisitor>
9833 inline void ForeignIterateBody();
9835 // Dispatched behavior.
9836 DECLARE_PRINTER(Foreign)
9837 DECLARE_VERIFIER(Foreign)
9839 // Layout description.
9841 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
9842 static const int kSize = kForeignAddressOffset + kPointerSize;
9844 STATIC_ASSERT(kForeignAddressOffset == Internals::kForeignAddressOffset);
9847 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
9851 // The JSArray describes JavaScript Arrays
9852 // Such an array can be in one of two modes:
9853 // - fast, backing storage is a FixedArray and length <= elements.length();
9854 // Please note: push and pop can be used to grow and shrink the array.
9855 // - slow, backing storage is a HashTable with numbers as keys.
9856 class JSArray: public JSObject {
9858 // [length]: The length property.
9859 DECL_ACCESSORS(length, Object)
9861 // Overload the length setter to skip write barrier when the length
9862 // is set to a smi. This matches the set function on FixedArray.
9863 inline void set_length(Smi* length);
9865 static bool HasReadOnlyLength(Handle<JSArray> array);
9866 static bool WouldChangeReadOnlyLength(Handle<JSArray> array, uint32_t index);
9867 static MaybeHandle<Object> ReadOnlyLengthError(Handle<JSArray> array);
9869 // Initialize the array with the given capacity. The function may
9870 // fail due to out-of-memory situations, but only if the requested
9871 // capacity is non-zero.
9872 static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
9874 // If the JSArray has fast elements, and new_length would result in
9875 // normalization, returns true.
9876 bool SetLengthWouldNormalize(uint32_t new_length);
9877 static inline bool SetLengthWouldNormalize(Heap* heap, uint32_t new_length);
9879 // Initializes the array to a certain length.
9880 inline bool AllowsSetLength();
9882 static void SetLength(Handle<JSArray> array, uint32_t length);
9883 // Same as above but will also queue splice records if |array| is observed.
9884 static MaybeHandle<Object> ObservableSetLength(Handle<JSArray> array,
9887 // Set the content of the array to the content of storage.
9888 static inline void SetContent(Handle<JSArray> array,
9889 Handle<FixedArrayBase> storage);
9891 DECLARE_CAST(JSArray)
9893 // Dispatched behavior.
9894 DECLARE_PRINTER(JSArray)
9895 DECLARE_VERIFIER(JSArray)
9897 // Number of element slots to pre-allocate for an empty array.
9898 static const int kPreallocatedArrayElements = 4;
9900 // Layout description.
9901 static const int kLengthOffset = JSObject::kHeaderSize;
9902 static const int kSize = kLengthOffset + kPointerSize;
9905 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
9909 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
9910 Handle<Map> initial_map);
9913 // JSRegExpResult is just a JSArray with a specific initial map.
9914 // This initial map adds in-object properties for "index" and "input"
9915 // properties, as assigned by RegExp.prototype.exec, which allows
9916 // faster creation of RegExp exec results.
9917 // This class just holds constants used when creating the result.
9918 // After creation the result must be treated as a JSArray in all regards.
9919 class JSRegExpResult: public JSArray {
9921 // Offsets of object fields.
9922 static const int kIndexOffset = JSArray::kSize;
9923 static const int kInputOffset = kIndexOffset + kPointerSize;
9924 static const int kSize = kInputOffset + kPointerSize;
9925 // Indices of in-object properties.
9926 static const int kIndexIndex = 0;
9927 static const int kInputIndex = 1;
9929 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
9933 class AccessorInfo: public Struct {
9935 DECL_ACCESSORS(name, Object)
9936 DECL_ACCESSORS(flag, Smi)
9937 DECL_ACCESSORS(expected_receiver_type, Object)
9939 inline bool all_can_read();
9940 inline void set_all_can_read(bool value);
9942 inline bool all_can_write();
9943 inline void set_all_can_write(bool value);
9945 inline bool is_special_data_property();
9946 inline void set_is_special_data_property(bool value);
9948 inline PropertyAttributes property_attributes();
9949 inline void set_property_attributes(PropertyAttributes attributes);
9951 // Checks whether the given receiver is compatible with this accessor.
9952 static bool IsCompatibleReceiverMap(Isolate* isolate,
9953 Handle<AccessorInfo> info,
9955 inline bool IsCompatibleReceiver(Object* receiver);
9957 DECLARE_CAST(AccessorInfo)
9959 // Dispatched behavior.
9960 DECLARE_VERIFIER(AccessorInfo)
9962 // Append all descriptors to the array that are not already there.
9963 // Return number added.
9964 static int AppendUnique(Handle<Object> descriptors,
9965 Handle<FixedArray> array,
9966 int valid_descriptors);
9968 static const int kNameOffset = HeapObject::kHeaderSize;
9969 static const int kFlagOffset = kNameOffset + kPointerSize;
9970 static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
9971 static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
9974 inline bool HasExpectedReceiverType() {
9975 return expected_receiver_type()->IsFunctionTemplateInfo();
9977 // Bit positions in flag.
9978 static const int kAllCanReadBit = 0;
9979 static const int kAllCanWriteBit = 1;
9980 static const int kSpecialDataProperty = 2;
9981 class AttributesField : public BitField<PropertyAttributes, 3, 3> {};
9983 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
9987 // An accessor must have a getter, but can have no setter.
9989 // When setting a property, V8 searches accessors in prototypes.
9990 // If an accessor was found and it does not have a setter,
9991 // the request is ignored.
9993 // If the accessor in the prototype has the READ_ONLY property attribute, then
9994 // a new value is added to the derived object when the property is set.
9995 // This shadows the accessor in the prototype.
9996 class ExecutableAccessorInfo: public AccessorInfo {
9998 DECL_ACCESSORS(getter, Object)
9999 DECL_ACCESSORS(setter, Object)
10000 DECL_ACCESSORS(data, Object)
10002 DECLARE_CAST(ExecutableAccessorInfo)
10004 // Dispatched behavior.
10005 DECLARE_PRINTER(ExecutableAccessorInfo)
10006 DECLARE_VERIFIER(ExecutableAccessorInfo)
10008 static const int kGetterOffset = AccessorInfo::kSize;
10009 static const int kSetterOffset = kGetterOffset + kPointerSize;
10010 static const int kDataOffset = kSetterOffset + kPointerSize;
10011 static const int kSize = kDataOffset + kPointerSize;
10013 static void ClearSetter(Handle<ExecutableAccessorInfo> info);
10016 DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
10020 // Support for JavaScript accessors: A pair of a getter and a setter. Each
10021 // accessor can either be
10022 // * a pointer to a JavaScript function or proxy: a real accessor
10023 // * undefined: considered an accessor by the spec, too, strangely enough
10024 // * the hole: an accessor which has not been set
10025 // * a pointer to a map: a transition used to ensure map sharing
10026 class AccessorPair: public Struct {
10028 DECL_ACCESSORS(getter, Object)
10029 DECL_ACCESSORS(setter, Object)
10031 DECLARE_CAST(AccessorPair)
10033 static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
10035 Object* get(AccessorComponent component) {
10036 return component == ACCESSOR_GETTER ? getter() : setter();
10039 void set(AccessorComponent component, Object* value) {
10040 if (component == ACCESSOR_GETTER) {
10047 // Note: Returns undefined instead in case of a hole.
10048 Object* GetComponent(AccessorComponent component);
10050 // Set both components, skipping arguments which are a JavaScript null.
10051 void SetComponents(Object* getter, Object* setter) {
10052 if (!getter->IsNull()) set_getter(getter);
10053 if (!setter->IsNull()) set_setter(setter);
10056 bool Equals(AccessorPair* pair) {
10057 return (this == pair) || pair->Equals(getter(), setter());
10060 bool Equals(Object* getter_value, Object* setter_value) {
10061 return (getter() == getter_value) && (setter() == setter_value);
10064 bool ContainsAccessor() {
10065 return IsJSAccessor(getter()) || IsJSAccessor(setter());
10068 // Dispatched behavior.
10069 DECLARE_PRINTER(AccessorPair)
10070 DECLARE_VERIFIER(AccessorPair)
10072 static const int kGetterOffset = HeapObject::kHeaderSize;
10073 static const int kSetterOffset = kGetterOffset + kPointerSize;
10074 static const int kSize = kSetterOffset + kPointerSize;
10077 // Strangely enough, in addition to functions and harmony proxies, the spec
10078 // requires us to consider undefined as a kind of accessor, too:
10080 // Object.defineProperty(obj, "foo", {get: undefined});
10081 // assertTrue("foo" in obj);
10082 bool IsJSAccessor(Object* obj) {
10083 return obj->IsSpecFunction() || obj->IsUndefined();
10086 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
10090 class AccessCheckInfo: public Struct {
10092 DECL_ACCESSORS(named_callback, Object)
10093 DECL_ACCESSORS(indexed_callback, Object)
10094 DECL_ACCESSORS(data, Object)
10096 DECLARE_CAST(AccessCheckInfo)
10098 // Dispatched behavior.
10099 DECLARE_PRINTER(AccessCheckInfo)
10100 DECLARE_VERIFIER(AccessCheckInfo)
10102 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
10103 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
10104 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
10105 static const int kSize = kDataOffset + kPointerSize;
10108 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
10112 class InterceptorInfo: public Struct {
10114 DECL_ACCESSORS(getter, Object)
10115 DECL_ACCESSORS(setter, Object)
10116 DECL_ACCESSORS(query, Object)
10117 DECL_ACCESSORS(deleter, Object)
10118 DECL_ACCESSORS(enumerator, Object)
10119 DECL_ACCESSORS(data, Object)
10120 DECL_BOOLEAN_ACCESSORS(can_intercept_symbols)
10121 DECL_BOOLEAN_ACCESSORS(all_can_read)
10122 DECL_BOOLEAN_ACCESSORS(non_masking)
10124 inline int flags() const;
10125 inline void set_flags(int flags);
10127 DECLARE_CAST(InterceptorInfo)
10129 // Dispatched behavior.
10130 DECLARE_PRINTER(InterceptorInfo)
10131 DECLARE_VERIFIER(InterceptorInfo)
10133 static const int kGetterOffset = HeapObject::kHeaderSize;
10134 static const int kSetterOffset = kGetterOffset + kPointerSize;
10135 static const int kQueryOffset = kSetterOffset + kPointerSize;
10136 static const int kDeleterOffset = kQueryOffset + kPointerSize;
10137 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
10138 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
10139 static const int kFlagsOffset = kDataOffset + kPointerSize;
10140 static const int kSize = kFlagsOffset + kPointerSize;
10142 static const int kCanInterceptSymbolsBit = 0;
10143 static const int kAllCanReadBit = 1;
10144 static const int kNonMasking = 2;
10147 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
10151 class CallHandlerInfo: public Struct {
10153 DECL_ACCESSORS(callback, Object)
10154 DECL_ACCESSORS(data, Object)
10156 DECLARE_CAST(CallHandlerInfo)
10158 // Dispatched behavior.
10159 DECLARE_PRINTER(CallHandlerInfo)
10160 DECLARE_VERIFIER(CallHandlerInfo)
10162 static const int kCallbackOffset = HeapObject::kHeaderSize;
10163 static const int kDataOffset = kCallbackOffset + kPointerSize;
10164 static const int kSize = kDataOffset + kPointerSize;
10167 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
10171 class TemplateInfo: public Struct {
10173 DECL_ACCESSORS(tag, Object)
10174 inline int number_of_properties() const;
10175 inline void set_number_of_properties(int value);
10176 DECL_ACCESSORS(property_list, Object)
10177 DECL_ACCESSORS(property_accessors, Object)
10179 DECLARE_VERIFIER(TemplateInfo)
10181 static const int kTagOffset = HeapObject::kHeaderSize;
10182 static const int kNumberOfProperties = kTagOffset + kPointerSize;
10183 static const int kPropertyListOffset = kNumberOfProperties + kPointerSize;
10184 static const int kPropertyAccessorsOffset =
10185 kPropertyListOffset + kPointerSize;
10186 static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
10189 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
10193 class FunctionTemplateInfo: public TemplateInfo {
10195 DECL_ACCESSORS(serial_number, Object)
10196 DECL_ACCESSORS(call_code, Object)
10197 DECL_ACCESSORS(prototype_template, Object)
10198 DECL_ACCESSORS(parent_template, Object)
10199 DECL_ACCESSORS(named_property_handler, Object)
10200 DECL_ACCESSORS(indexed_property_handler, Object)
10201 DECL_ACCESSORS(instance_template, Object)
10202 DECL_ACCESSORS(class_name, Object)
10203 DECL_ACCESSORS(signature, Object)
10204 DECL_ACCESSORS(instance_call_handler, Object)
10205 DECL_ACCESSORS(access_check_info, Object)
10206 DECL_ACCESSORS(flag, Smi)
10208 inline int length() const;
10209 inline void set_length(int value);
10211 // Following properties use flag bits.
10212 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
10213 DECL_BOOLEAN_ACCESSORS(undetectable)
10214 // If the bit is set, object instances created by this function
10215 // requires access check.
10216 DECL_BOOLEAN_ACCESSORS(needs_access_check)
10217 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
10218 DECL_BOOLEAN_ACCESSORS(remove_prototype)
10219 DECL_BOOLEAN_ACCESSORS(do_not_cache)
10220 DECL_BOOLEAN_ACCESSORS(instantiated)
10221 DECL_BOOLEAN_ACCESSORS(accept_any_receiver)
10223 DECLARE_CAST(FunctionTemplateInfo)
10225 // Dispatched behavior.
10226 DECLARE_PRINTER(FunctionTemplateInfo)
10227 DECLARE_VERIFIER(FunctionTemplateInfo)
10229 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
10230 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
10231 static const int kPrototypeTemplateOffset =
10232 kCallCodeOffset + kPointerSize;
10233 static const int kParentTemplateOffset =
10234 kPrototypeTemplateOffset + kPointerSize;
10235 static const int kNamedPropertyHandlerOffset =
10236 kParentTemplateOffset + kPointerSize;
10237 static const int kIndexedPropertyHandlerOffset =
10238 kNamedPropertyHandlerOffset + kPointerSize;
10239 static const int kInstanceTemplateOffset =
10240 kIndexedPropertyHandlerOffset + kPointerSize;
10241 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
10242 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
10243 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
10244 static const int kAccessCheckInfoOffset =
10245 kInstanceCallHandlerOffset + kPointerSize;
10246 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
10247 static const int kLengthOffset = kFlagOffset + kPointerSize;
10248 static const int kSize = kLengthOffset + kPointerSize;
10250 // Returns true if |object| is an instance of this function template.
10251 bool IsTemplateFor(Object* object);
10252 bool IsTemplateFor(Map* map);
10254 // Returns the holder JSObject if the function can legally be called with this
10255 // receiver. Returns Heap::null_value() if the call is illegal.
10256 Object* GetCompatibleReceiver(Isolate* isolate, Object* receiver);
10259 // Bit position in the flag, from least significant bit position.
10260 static const int kHiddenPrototypeBit = 0;
10261 static const int kUndetectableBit = 1;
10262 static const int kNeedsAccessCheckBit = 2;
10263 static const int kReadOnlyPrototypeBit = 3;
10264 static const int kRemovePrototypeBit = 4;
10265 static const int kDoNotCacheBit = 5;
10266 static const int kInstantiatedBit = 6;
10267 static const int kAcceptAnyReceiver = 7;
10269 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
10273 class ObjectTemplateInfo: public TemplateInfo {
10275 DECL_ACCESSORS(constructor, Object)
10276 DECL_ACCESSORS(internal_field_count, Object)
10278 DECLARE_CAST(ObjectTemplateInfo)
10280 // Dispatched behavior.
10281 DECLARE_PRINTER(ObjectTemplateInfo)
10282 DECLARE_VERIFIER(ObjectTemplateInfo)
10284 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10285 static const int kInternalFieldCountOffset =
10286 kConstructorOffset + kPointerSize;
10287 static const int kSize = kInternalFieldCountOffset + kPointerSize;
10291 class TypeSwitchInfo: public Struct {
10293 DECL_ACCESSORS(types, Object)
10295 DECLARE_CAST(TypeSwitchInfo)
10297 // Dispatched behavior.
10298 DECLARE_PRINTER(TypeSwitchInfo)
10299 DECLARE_VERIFIER(TypeSwitchInfo)
10301 static const int kTypesOffset = Struct::kHeaderSize;
10302 static const int kSize = kTypesOffset + kPointerSize;
10306 // The DebugInfo class holds additional information for a function being
10308 class DebugInfo: public Struct {
10310 // The shared function info for the source being debugged.
10311 DECL_ACCESSORS(shared, SharedFunctionInfo)
10312 // Code object for the patched code. This code object is the code object
10313 // currently active for the function.
10314 DECL_ACCESSORS(code, Code)
10315 // Fixed array holding status information for each active break point.
10316 DECL_ACCESSORS(break_points, FixedArray)
10318 // Check if there is a break point at a code position.
10319 bool HasBreakPoint(int code_position);
10320 // Get the break point info object for a code position.
10321 Object* GetBreakPointInfo(int code_position);
10322 // Clear a break point.
10323 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
10325 Handle<Object> break_point_object);
10326 // Set a break point.
10327 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
10328 int source_position, int statement_position,
10329 Handle<Object> break_point_object);
10330 // Get the break point objects for a code position.
10331 Handle<Object> GetBreakPointObjects(int code_position);
10332 // Find the break point info holding this break point object.
10333 static Handle<Object> FindBreakPointInfo(Handle<DebugInfo> debug_info,
10334 Handle<Object> break_point_object);
10335 // Get the number of break points for this function.
10336 int GetBreakPointCount();
10338 DECLARE_CAST(DebugInfo)
10340 // Dispatched behavior.
10341 DECLARE_PRINTER(DebugInfo)
10342 DECLARE_VERIFIER(DebugInfo)
10344 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
10345 static const int kCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
10346 static const int kBreakPointsStateIndex = kCodeIndex + kPointerSize;
10347 static const int kSize = kBreakPointsStateIndex + kPointerSize;
10349 static const int kEstimatedNofBreakPointsInFunction = 16;
10352 static const int kNoBreakPointInfo = -1;
10354 // Lookup the index in the break_points array for a code position.
10355 int GetBreakPointInfoIndex(int code_position);
10357 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
10361 // The BreakPointInfo class holds information for break points set in a
10362 // function. The DebugInfo object holds a BreakPointInfo object for each code
10363 // position with one or more break points.
10364 class BreakPointInfo: public Struct {
10366 // The position in the code for the break point.
10367 DECL_ACCESSORS(code_position, Smi)
10368 // The position in the source for the break position.
10369 DECL_ACCESSORS(source_position, Smi)
10370 // The position in the source for the last statement before this break
10372 DECL_ACCESSORS(statement_position, Smi)
10373 // List of related JavaScript break points.
10374 DECL_ACCESSORS(break_point_objects, Object)
10376 // Removes a break point.
10377 static void ClearBreakPoint(Handle<BreakPointInfo> info,
10378 Handle<Object> break_point_object);
10379 // Set a break point.
10380 static void SetBreakPoint(Handle<BreakPointInfo> info,
10381 Handle<Object> break_point_object);
10382 // Check if break point info has this break point object.
10383 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
10384 Handle<Object> break_point_object);
10385 // Get the number of break points for this code position.
10386 int GetBreakPointCount();
10388 DECLARE_CAST(BreakPointInfo)
10390 // Dispatched behavior.
10391 DECLARE_PRINTER(BreakPointInfo)
10392 DECLARE_VERIFIER(BreakPointInfo)
10394 static const int kCodePositionIndex = Struct::kHeaderSize;
10395 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
10396 static const int kStatementPositionIndex =
10397 kSourcePositionIndex + kPointerSize;
10398 static const int kBreakPointObjectsIndex =
10399 kStatementPositionIndex + kPointerSize;
10400 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
10403 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
10407 #undef DECL_BOOLEAN_ACCESSORS
10408 #undef DECL_ACCESSORS
10409 #undef DECLARE_CAST
10410 #undef DECLARE_VERIFIER
10412 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
10413 V(kStringTable, "string_table", "(Internalized strings)") \
10414 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
10415 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
10416 V(kSmiRootList, "smi_root_list", "(Smi roots)") \
10417 V(kInternalizedString, "internalized_string", "(Internal string)") \
10418 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
10419 V(kTop, "top", "(Isolate)") \
10420 V(kRelocatable, "relocatable", "(Relocatable)") \
10421 V(kDebug, "debug", "(Debugger)") \
10422 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
10423 V(kHandleScope, "handlescope", "(Handle scope)") \
10424 V(kBuiltins, "builtins", "(Builtins)") \
10425 V(kGlobalHandles, "globalhandles", "(Global handles)") \
10426 V(kEternalHandles, "eternalhandles", "(Eternal handles)") \
10427 V(kThreadManager, "threadmanager", "(Thread manager)") \
10428 V(kStrongRoots, "strong roots", "(Strong roots)") \
10429 V(kExtensions, "Extensions", "(Extensions)")
10431 class VisitorSynchronization : public AllStatic {
10433 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
10435 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
10438 #undef DECLARE_ENUM
10440 static const char* const kTags[kNumberOfSyncTags];
10441 static const char* const kTagNames[kNumberOfSyncTags];
10444 // Abstract base class for visiting, and optionally modifying, the
10445 // pointers contained in Objects. Used in GC and serialization/deserialization.
10446 class ObjectVisitor BASE_EMBEDDED {
10448 virtual ~ObjectVisitor() {}
10450 // Visits a contiguous arrays of pointers in the half-open range
10451 // [start, end). Any or all of the values may be modified on return.
10452 virtual void VisitPointers(Object** start, Object** end) = 0;
10454 // Handy shorthand for visiting a single pointer.
10455 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
10457 // Visit weak next_code_link in Code object.
10458 virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
10460 // To allow lazy clearing of inline caches the visitor has
10461 // a rich interface for iterating over Code objects..
10463 // Visits a code target in the instruction stream.
10464 virtual void VisitCodeTarget(RelocInfo* rinfo);
10466 // Visits a code entry in a JS function.
10467 virtual void VisitCodeEntry(Address entry_address);
10469 // Visits a global property cell reference in the instruction stream.
10470 virtual void VisitCell(RelocInfo* rinfo);
10472 // Visits a runtime entry in the instruction stream.
10473 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
10475 // Visits the resource of an one-byte or two-byte string.
10476 virtual void VisitExternalOneByteString(
10477 v8::String::ExternalOneByteStringResource** resource) {}
10478 virtual void VisitExternalTwoByteString(
10479 v8::String::ExternalStringResource** resource) {}
10481 // Visits a debug call target in the instruction stream.
10482 virtual void VisitDebugTarget(RelocInfo* rinfo);
10484 // Visits the byte sequence in a function's prologue that contains information
10485 // about the code's age.
10486 virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
10488 // Visit pointer embedded into a code object.
10489 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
10491 // Visits an external reference embedded into a code object.
10492 virtual void VisitExternalReference(RelocInfo* rinfo);
10494 // Visits an external reference.
10495 virtual void VisitExternalReference(Address* p) {}
10497 // Visits an (encoded) internal reference.
10498 virtual void VisitInternalReference(RelocInfo* rinfo) {}
10500 // Visits a handle that has an embedder-assigned class ID.
10501 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
10503 // Intended for serialization/deserialization checking: insert, or
10504 // check for the presence of, a tag at this position in the stream.
10505 // Also used for marking up GC roots in heap snapshots.
10506 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
10510 class StructBodyDescriptor : public
10511 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
10513 static inline int SizeOf(Map* map, HeapObject* object) {
10514 return map->instance_size();
10519 // BooleanBit is a helper class for setting and getting a bit in an
10521 class BooleanBit : public AllStatic {
10523 static inline bool get(Smi* smi, int bit_position) {
10524 return get(smi->value(), bit_position);
10527 static inline bool get(int value, int bit_position) {
10528 return (value & (1 << bit_position)) != 0;
10531 static inline Smi* set(Smi* smi, int bit_position, bool v) {
10532 return Smi::FromInt(set(smi->value(), bit_position, v));
10535 static inline int set(int value, int bit_position, bool v) {
10537 value |= (1 << bit_position);
10539 value &= ~(1 << bit_position);
10545 } } // namespace v8::internal
10547 #endif // V8_OBJECTS_H_