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 the name of a certain context slot by its index.
3938 String* ContextSlotName(int slot_index);
3940 // Lookup support for serialized scope info. Returns the
3941 // parameter index for a given parameter name if the parameter is present;
3942 // otherwise returns a value < 0. The name must be an internalized string.
3943 int ParameterIndex(String* name);
3945 // Lookup support for serialized scope info. Returns the function context
3946 // slot index if the function name is present and context-allocated (named
3947 // function expressions, only), otherwise returns a value < 0. The name
3948 // must be an internalized string.
3949 int FunctionContextSlotIndex(String* name, VariableMode* mode);
3951 // Lookup support for serialized scope info. Returns the receiver context
3952 // slot index if scope has a "this" binding, and the binding is
3953 // context-allocated. Otherwise returns a value < 0.
3954 int ReceiverContextSlotIndex();
3956 FunctionKind function_kind();
3958 // Copies all the context locals into an object used to materialize a scope.
3959 static void CopyContextLocalsToScopeObject(Handle<ScopeInfo> scope_info,
3960 Handle<Context> context,
3961 Handle<JSObject> scope_object);
3964 static Handle<ScopeInfo> Create(Isolate* isolate, Zone* zone, Scope* scope);
3965 static Handle<ScopeInfo> CreateGlobalThisBinding(Isolate* isolate);
3967 // Serializes empty scope info.
3968 static ScopeInfo* Empty(Isolate* isolate);
3974 // The layout of the static part of a ScopeInfo is as follows. Each entry is
3975 // numeric and occupies one array slot.
3976 // 1. A set of properties of the scope
3977 // 2. The number of parameters. This only applies to function scopes. For
3978 // non-function scopes this is 0.
3979 // 3. The number of non-parameter variables allocated on the stack.
3980 // 4. The number of non-parameter and parameter variables allocated in the
3982 #define FOR_EACH_NUMERIC_FIELD(V) \
3985 V(StackLocalCount) \
3986 V(ContextLocalCount) \
3987 V(ContextGlobalCount) \
3988 V(StrongModeFreeVariableCount)
3990 #define FIELD_ACCESSORS(name) \
3991 void Set##name(int value) { \
3992 set(k##name, Smi::FromInt(value)); \
3995 if (length() > 0) { \
3996 return Smi::cast(get(k##name))->value(); \
4001 FOR_EACH_NUMERIC_FIELD(FIELD_ACCESSORS)
4002 #undef FIELD_ACCESSORS
4006 #define DECL_INDEX(name) k##name,
4007 FOR_EACH_NUMERIC_FIELD(DECL_INDEX)
4009 #undef FOR_EACH_NUMERIC_FIELD
4013 // The layout of the variable part of a ScopeInfo is as follows:
4014 // 1. ParameterEntries:
4015 // This part stores the names of the parameters for function scopes. One
4016 // slot is used per parameter, so in total this part occupies
4017 // ParameterCount() slots in the array. For other scopes than function
4018 // scopes ParameterCount() is 0.
4019 // 2. StackLocalFirstSlot:
4020 // Index of a first stack slot for stack local. Stack locals belonging to
4021 // this scope are located on a stack at slots starting from this index.
4022 // 3. StackLocalEntries:
4023 // Contains the names of local variables that are allocated on the stack,
4024 // in increasing order of the stack slot index. First local variable has
4025 // a stack slot index defined in StackLocalFirstSlot (point 2 above).
4026 // One slot is used per stack local, so in total this part occupies
4027 // StackLocalCount() slots in the array.
4028 // 4. ContextLocalNameEntries:
4029 // Contains the names of local variables and parameters that are allocated
4030 // in the context. They are stored in increasing order of the context slot
4031 // index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
4032 // context local, so in total this part occupies ContextLocalCount() slots
4034 // 5. ContextLocalInfoEntries:
4035 // Contains the variable modes and initialization flags corresponding to
4036 // the context locals in ContextLocalNameEntries. One slot is used per
4037 // context local, so in total this part occupies ContextLocalCount()
4038 // slots in the array.
4039 // 6. StrongModeFreeVariableNameEntries:
4040 // Stores the names of strong mode free variables.
4041 // 7. StrongModeFreeVariablePositionEntries:
4042 // Stores the locations (start and end position) of strong mode free
4044 // 8. RecieverEntryIndex:
4045 // If the scope binds a "this" value, one slot is reserved to hold the
4046 // context or stack slot index for the variable.
4047 // 9. FunctionNameEntryIndex:
4048 // If the scope belongs to a named function expression this part contains
4049 // information about the function variable. It always occupies two array
4050 // slots: a. The name of the function variable.
4051 // b. The context or stack slot index for the variable.
4052 int ParameterEntriesIndex();
4053 int StackLocalFirstSlotIndex();
4054 int StackLocalEntriesIndex();
4055 int ContextLocalNameEntriesIndex();
4056 int ContextGlobalNameEntriesIndex();
4057 int ContextLocalInfoEntriesIndex();
4058 int ContextGlobalInfoEntriesIndex();
4059 int StrongModeFreeVariableNameEntriesIndex();
4060 int StrongModeFreeVariablePositionEntriesIndex();
4061 int ReceiverEntryIndex();
4062 int FunctionNameEntryIndex();
4064 int Lookup(Handle<String> name, int start, int end, VariableMode* mode,
4065 VariableLocation* location, InitializationFlag* init_flag,
4066 MaybeAssignedFlag* maybe_assigned_flag);
4068 // Used for the function name variable for named function expressions, and for
4070 enum VariableAllocationInfo { NONE, STACK, CONTEXT, UNUSED };
4072 // Properties of scopes.
4073 class ScopeTypeField : public BitField<ScopeType, 0, 4> {};
4074 class CallsEvalField : public BitField<bool, ScopeTypeField::kNext, 1> {};
4075 STATIC_ASSERT(LANGUAGE_END == 3);
4076 class LanguageModeField
4077 : public BitField<LanguageMode, CallsEvalField::kNext, 2> {};
4078 class ReceiverVariableField
4079 : public BitField<VariableAllocationInfo, LanguageModeField::kNext, 2> {};
4080 class FunctionVariableField
4081 : public BitField<VariableAllocationInfo, ReceiverVariableField::kNext,
4083 class FunctionVariableMode
4084 : public BitField<VariableMode, FunctionVariableField::kNext, 3> {};
4085 class AsmModuleField : public BitField<bool, FunctionVariableMode::kNext, 1> {
4087 class AsmFunctionField : public BitField<bool, AsmModuleField::kNext, 1> {};
4088 class IsSimpleParameterListField
4089 : public BitField<bool, AsmFunctionField::kNext, 1> {};
4090 class FunctionKindField
4091 : public BitField<FunctionKind, IsSimpleParameterListField::kNext, 8> {};
4093 // BitFields representing the encoded information for context locals in the
4094 // ContextLocalInfoEntries part.
4095 class ContextLocalMode: public BitField<VariableMode, 0, 3> {};
4096 class ContextLocalInitFlag: public BitField<InitializationFlag, 3, 1> {};
4097 class ContextLocalMaybeAssignedFlag
4098 : public BitField<MaybeAssignedFlag, 4, 1> {};
4102 // The cache for maps used by normalized (dictionary mode) objects.
4103 // Such maps do not have property descriptors, so a typical program
4104 // needs very limited number of distinct normalized maps.
4105 class NormalizedMapCache: public FixedArray {
4107 static Handle<NormalizedMapCache> New(Isolate* isolate);
4109 MUST_USE_RESULT MaybeHandle<Map> Get(Handle<Map> fast_map,
4110 PropertyNormalizationMode mode);
4111 void Set(Handle<Map> fast_map, Handle<Map> normalized_map);
4115 DECLARE_CAST(NormalizedMapCache)
4117 static inline bool IsNormalizedMapCache(const Object* obj);
4119 DECLARE_VERIFIER(NormalizedMapCache)
4121 static const int kEntries = 64;
4123 static inline int GetIndex(Handle<Map> map);
4125 // The following declarations hide base class methods.
4126 Object* get(int index);
4127 void set(int index, Object* value);
4131 // ByteArray represents fixed sized byte arrays. Used for the relocation info
4132 // that is attached to code objects.
4133 class ByteArray: public FixedArrayBase {
4135 inline int Size() { return RoundUp(length() + kHeaderSize, kPointerSize); }
4137 // Setter and getter.
4138 inline byte get(int index);
4139 inline void set(int index, byte value);
4141 // Treat contents as an int array.
4142 inline int get_int(int index);
4144 static int SizeFor(int length) {
4145 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4147 // We use byte arrays for free blocks in the heap. Given a desired size in
4148 // bytes that is a multiple of the word size and big enough to hold a byte
4149 // array, this function returns the number of elements a byte array should
4151 static int LengthFor(int size_in_bytes) {
4152 DCHECK(IsAligned(size_in_bytes, kPointerSize));
4153 DCHECK(size_in_bytes >= kHeaderSize);
4154 return size_in_bytes - kHeaderSize;
4157 // Returns data start address.
4158 inline Address GetDataStartAddress();
4160 // Returns a pointer to the ByteArray object for a given data start address.
4161 static inline ByteArray* FromDataStartAddress(Address address);
4163 DECLARE_CAST(ByteArray)
4165 // Dispatched behavior.
4166 inline int ByteArraySize() {
4167 return SizeFor(this->length());
4169 DECLARE_PRINTER(ByteArray)
4170 DECLARE_VERIFIER(ByteArray)
4172 // Layout description.
4173 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4175 // Maximal memory consumption for a single ByteArray.
4176 static const int kMaxSize = 512 * MB;
4177 // Maximal length of a single ByteArray.
4178 static const int kMaxLength = kMaxSize - kHeaderSize;
4181 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4185 // BytecodeArray represents a sequence of interpreter bytecodes.
4186 class BytecodeArray : public FixedArrayBase {
4188 static int SizeFor(int length) {
4189 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4192 // Setter and getter
4193 inline byte get(int index);
4194 inline void set(int index, byte value);
4196 // Returns data start address.
4197 inline Address GetFirstBytecodeAddress();
4199 // Accessors for frame size and the number of locals
4200 inline int frame_size() const;
4201 inline void set_frame_size(int value);
4203 DECLARE_CAST(BytecodeArray)
4205 // Dispatched behavior.
4206 inline int BytecodeArraySize() { return SizeFor(this->length()); }
4208 DECLARE_PRINTER(BytecodeArray)
4209 DECLARE_VERIFIER(BytecodeArray)
4211 void Disassemble(std::ostream& os);
4213 // Layout description.
4214 static const int kFrameSizeOffset = FixedArrayBase::kHeaderSize;
4215 static const int kHeaderSize = kFrameSizeOffset + kIntSize;
4217 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4219 // Maximal memory consumption for a single BytecodeArray.
4220 static const int kMaxSize = 512 * MB;
4221 // Maximal length of a single BytecodeArray.
4222 static const int kMaxLength = kMaxSize - kHeaderSize;
4225 DISALLOW_IMPLICIT_CONSTRUCTORS(BytecodeArray);
4229 // FreeSpace are fixed-size free memory blocks used by the heap and GC.
4230 // They look like heap objects (are heap object tagged and have a map) so that
4231 // the heap remains iterable. They have a size and a next pointer.
4232 // The next pointer is the raw address of the next FreeSpace object (or NULL)
4233 // in the free list.
4234 class FreeSpace: public HeapObject {
4236 // [size]: size of the free space including the header.
4237 inline int size() const;
4238 inline void set_size(int value);
4240 inline int nobarrier_size() const;
4241 inline void nobarrier_set_size(int value);
4243 inline int Size() { return size(); }
4245 // Accessors for the next field.
4246 inline FreeSpace* next();
4247 inline FreeSpace** next_address();
4248 inline void set_next(FreeSpace* next);
4250 inline static FreeSpace* cast(HeapObject* obj);
4252 // Dispatched behavior.
4253 DECLARE_PRINTER(FreeSpace)
4254 DECLARE_VERIFIER(FreeSpace)
4256 // Layout description.
4257 // Size is smi tagged when it is stored.
4258 static const int kSizeOffset = HeapObject::kHeaderSize;
4259 static const int kNextOffset = POINTER_SIZE_ALIGN(kSizeOffset + kPointerSize);
4262 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
4266 // V has parameters (Type, type, TYPE, C type, element_size)
4267 #define TYPED_ARRAYS(V) \
4268 V(Uint8, uint8, UINT8, uint8_t, 1) \
4269 V(Int8, int8, INT8, int8_t, 1) \
4270 V(Uint16, uint16, UINT16, uint16_t, 2) \
4271 V(Int16, int16, INT16, int16_t, 2) \
4272 V(Uint32, uint32, UINT32, uint32_t, 4) \
4273 V(Int32, int32, INT32, int32_t, 4) \
4274 V(Float32, float32, FLOAT32, float, 4) \
4275 V(Float64, float64, FLOAT64, double, 8) \
4276 V(Uint8Clamped, uint8_clamped, UINT8_CLAMPED, uint8_t, 1)
4279 class FixedTypedArrayBase: public FixedArrayBase {
4281 // [base_pointer]: Either points to the FixedTypedArrayBase itself or nullptr.
4282 DECL_ACCESSORS(base_pointer, Object)
4284 // [external_pointer]: Contains the offset between base_pointer and the start
4285 // of the data. If the base_pointer is a nullptr, the external_pointer
4286 // therefore points to the actual backing store.
4287 DECL_ACCESSORS(external_pointer, void)
4289 // Dispatched behavior.
4290 inline void FixedTypedArrayBaseIterateBody(ObjectVisitor* v);
4292 template <typename StaticVisitor>
4293 inline void FixedTypedArrayBaseIterateBody();
4295 DECLARE_CAST(FixedTypedArrayBase)
4297 static const int kBasePointerOffset = FixedArrayBase::kHeaderSize;
4298 static const int kExternalPointerOffset = kBasePointerOffset + kPointerSize;
4299 static const int kHeaderSize =
4300 DOUBLE_POINTER_ALIGN(kExternalPointerOffset + kPointerSize);
4302 static const int kDataOffset = kHeaderSize;
4306 static inline int TypedArraySize(InstanceType type, int length);
4307 inline int TypedArraySize(InstanceType type);
4309 // Use with care: returns raw pointer into heap.
4310 inline void* DataPtr();
4312 inline int DataSize();
4315 static inline int ElementSize(InstanceType type);
4317 inline int DataSize(InstanceType type);
4319 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
4323 template <class Traits>
4324 class FixedTypedArray: public FixedTypedArrayBase {
4326 typedef typename Traits::ElementType ElementType;
4327 static const InstanceType kInstanceType = Traits::kInstanceType;
4329 DECLARE_CAST(FixedTypedArray<Traits>)
4331 inline ElementType get_scalar(int index);
4332 static inline Handle<Object> get(Handle<FixedTypedArray> array, int index);
4333 inline void set(int index, ElementType value);
4335 static inline ElementType from_int(int value);
4336 static inline ElementType from_double(double value);
4338 // This accessor applies the correct conversion from Smi, HeapNumber
4340 void SetValue(uint32_t index, Object* value);
4342 DECLARE_PRINTER(FixedTypedArray)
4343 DECLARE_VERIFIER(FixedTypedArray)
4346 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
4349 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size) \
4350 class Type##ArrayTraits { \
4351 public: /* NOLINT */ \
4352 typedef elementType ElementType; \
4353 static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE; \
4354 static const char* Designator() { return #type " array"; } \
4355 static inline Handle<Object> ToHandle(Isolate* isolate, \
4356 elementType scalar); \
4357 static inline elementType defaultValue(); \
4360 typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
4362 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
4364 #undef FIXED_TYPED_ARRAY_TRAITS
4367 // DeoptimizationInputData is a fixed array used to hold the deoptimization
4368 // data for code generated by the Hydrogen/Lithium compiler. It also
4369 // contains information about functions that were inlined. If N different
4370 // functions were inlined then first N elements of the literal array will
4371 // contain these functions.
4374 class DeoptimizationInputData: public FixedArray {
4376 // Layout description. Indices in the array.
4377 static const int kTranslationByteArrayIndex = 0;
4378 static const int kInlinedFunctionCountIndex = 1;
4379 static const int kLiteralArrayIndex = 2;
4380 static const int kOsrAstIdIndex = 3;
4381 static const int kOsrPcOffsetIndex = 4;
4382 static const int kOptimizationIdIndex = 5;
4383 static const int kSharedFunctionInfoIndex = 6;
4384 static const int kWeakCellCacheIndex = 7;
4385 static const int kFirstDeoptEntryIndex = 8;
4387 // Offsets of deopt entry elements relative to the start of the entry.
4388 static const int kAstIdRawOffset = 0;
4389 static const int kTranslationIndexOffset = 1;
4390 static const int kArgumentsStackHeightOffset = 2;
4391 static const int kPcOffset = 3;
4392 static const int kDeoptEntrySize = 4;
4394 // Simple element accessors.
4395 #define DEFINE_ELEMENT_ACCESSORS(name, type) \
4397 return type::cast(get(k##name##Index)); \
4399 void Set##name(type* value) { \
4400 set(k##name##Index, value); \
4403 DEFINE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
4404 DEFINE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
4405 DEFINE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
4406 DEFINE_ELEMENT_ACCESSORS(OsrAstId, Smi)
4407 DEFINE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
4408 DEFINE_ELEMENT_ACCESSORS(OptimizationId, Smi)
4409 DEFINE_ELEMENT_ACCESSORS(SharedFunctionInfo, Object)
4410 DEFINE_ELEMENT_ACCESSORS(WeakCellCache, Object)
4412 #undef DEFINE_ELEMENT_ACCESSORS
4414 // Accessors for elements of the ith deoptimization entry.
4415 #define DEFINE_ENTRY_ACCESSORS(name, type) \
4416 type* name(int i) { \
4417 return type::cast(get(IndexForEntry(i) + k##name##Offset)); \
4419 void Set##name(int i, type* value) { \
4420 set(IndexForEntry(i) + k##name##Offset, value); \
4423 DEFINE_ENTRY_ACCESSORS(AstIdRaw, Smi)
4424 DEFINE_ENTRY_ACCESSORS(TranslationIndex, Smi)
4425 DEFINE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
4426 DEFINE_ENTRY_ACCESSORS(Pc, Smi)
4428 #undef DEFINE_DEOPT_ENTRY_ACCESSORS
4430 BailoutId AstId(int i) {
4431 return BailoutId(AstIdRaw(i)->value());
4434 void SetAstId(int i, BailoutId value) {
4435 SetAstIdRaw(i, Smi::FromInt(value.ToInt()));
4439 return (length() - kFirstDeoptEntryIndex) / kDeoptEntrySize;
4442 // Allocates a DeoptimizationInputData.
4443 static Handle<DeoptimizationInputData> New(Isolate* isolate,
4444 int deopt_entry_count,
4445 PretenureFlag pretenure);
4447 DECLARE_CAST(DeoptimizationInputData)
4449 #ifdef ENABLE_DISASSEMBLER
4450 void DeoptimizationInputDataPrint(std::ostream& os); // NOLINT
4454 static int IndexForEntry(int i) {
4455 return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
4459 static int LengthFor(int entry_count) { return IndexForEntry(entry_count); }
4463 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
4464 // data for code generated by the full compiler.
4465 // The format of the these objects is
4466 // [i * 2]: Ast ID for ith deoptimization.
4467 // [i * 2 + 1]: PC and state of ith deoptimization
4468 class DeoptimizationOutputData: public FixedArray {
4470 int DeoptPoints() { return length() / 2; }
4472 BailoutId AstId(int index) {
4473 return BailoutId(Smi::cast(get(index * 2))->value());
4476 void SetAstId(int index, BailoutId id) {
4477 set(index * 2, Smi::FromInt(id.ToInt()));
4480 Smi* PcAndState(int index) { return Smi::cast(get(1 + index * 2)); }
4481 void SetPcAndState(int index, Smi* offset) { set(1 + index * 2, offset); }
4483 static int LengthOfFixedArray(int deopt_points) {
4484 return deopt_points * 2;
4487 // Allocates a DeoptimizationOutputData.
4488 static Handle<DeoptimizationOutputData> New(Isolate* isolate,
4489 int number_of_deopt_points,
4490 PretenureFlag pretenure);
4492 DECLARE_CAST(DeoptimizationOutputData)
4494 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4495 void DeoptimizationOutputDataPrint(std::ostream& os); // NOLINT
4500 // HandlerTable is a fixed array containing entries for exception handlers in
4501 // the code object it is associated with. The tables comes in two flavors:
4502 // 1) Based on ranges: Used for unoptimized code. Contains one entry per
4503 // exception handler and a range representing the try-block covered by that
4504 // handler. Layout looks as follows:
4505 // [ range-start , range-end , handler-offset , stack-depth ]
4506 // 2) Based on return addresses: Used for turbofanned code. Contains one entry
4507 // per call-site that could throw an exception. Layout looks as follows:
4508 // [ return-address-offset , handler-offset ]
4509 class HandlerTable : public FixedArray {
4511 // Conservative prediction whether a given handler will locally catch an
4512 // exception or cause a re-throw to outside the code boundary. Since this is
4513 // undecidable it is merely an approximation (e.g. useful for debugger).
4514 enum CatchPrediction { UNCAUGHT, CAUGHT };
4516 // Accessors for handler table based on ranges.
4517 void SetRangeStart(int index, int value) {
4518 set(index * kRangeEntrySize + kRangeStartIndex, Smi::FromInt(value));
4520 void SetRangeEnd(int index, int value) {
4521 set(index * kRangeEntrySize + kRangeEndIndex, Smi::FromInt(value));
4523 void SetRangeHandler(int index, int offset, CatchPrediction prediction) {
4524 int value = HandlerOffsetField::encode(offset) |
4525 HandlerPredictionField::encode(prediction);
4526 set(index * kRangeEntrySize + kRangeHandlerIndex, Smi::FromInt(value));
4528 void SetRangeDepth(int index, int value) {
4529 set(index * kRangeEntrySize + kRangeDepthIndex, Smi::FromInt(value));
4532 // Accessors for handler table based on return addresses.
4533 void SetReturnOffset(int index, int value) {
4534 set(index * kReturnEntrySize + kReturnOffsetIndex, Smi::FromInt(value));
4536 void SetReturnHandler(int index, int offset, CatchPrediction prediction) {
4537 int value = HandlerOffsetField::encode(offset) |
4538 HandlerPredictionField::encode(prediction);
4539 set(index * kReturnEntrySize + kReturnHandlerIndex, Smi::FromInt(value));
4542 // Lookup handler in a table based on ranges.
4543 int LookupRange(int pc_offset, int* stack_depth, CatchPrediction* prediction);
4545 // Lookup handler in a table based on return addresses.
4546 int LookupReturn(int pc_offset, CatchPrediction* prediction);
4548 // Returns the required length of the underlying fixed array.
4549 static int LengthForRange(int entries) { return entries * kRangeEntrySize; }
4550 static int LengthForReturn(int entries) { return entries * kReturnEntrySize; }
4552 DECLARE_CAST(HandlerTable)
4554 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4555 void HandlerTableRangePrint(std::ostream& os); // NOLINT
4556 void HandlerTableReturnPrint(std::ostream& os); // NOLINT
4560 // Layout description for handler table based on ranges.
4561 static const int kRangeStartIndex = 0;
4562 static const int kRangeEndIndex = 1;
4563 static const int kRangeHandlerIndex = 2;
4564 static const int kRangeDepthIndex = 3;
4565 static const int kRangeEntrySize = 4;
4567 // Layout description for handler table based on return addresses.
4568 static const int kReturnOffsetIndex = 0;
4569 static const int kReturnHandlerIndex = 1;
4570 static const int kReturnEntrySize = 2;
4572 // Encoding of the {handler} field.
4573 class HandlerPredictionField : public BitField<CatchPrediction, 0, 1> {};
4574 class HandlerOffsetField : public BitField<int, 1, 30> {};
4578 // Code describes objects with on-the-fly generated machine code.
4579 class Code: public HeapObject {
4581 // Opaque data type for encapsulating code flags like kind, inline
4582 // cache state, and arguments count.
4583 typedef uint32_t Flags;
4585 #define NON_IC_KIND_LIST(V) \
4587 V(OPTIMIZED_FUNCTION) \
4593 #define IC_KIND_LIST(V) \
4604 #define CODE_KIND_LIST(V) \
4605 NON_IC_KIND_LIST(V) \
4609 #define DEFINE_CODE_KIND_ENUM(name) name,
4610 CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
4611 #undef DEFINE_CODE_KIND_ENUM
4615 // No more than 16 kinds. The value is currently encoded in four bits in
4617 STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
4619 static const char* Kind2String(Kind kind);
4627 static const int kPrologueOffsetNotSet = -1;
4629 #ifdef ENABLE_DISASSEMBLER
4631 static const char* ICState2String(InlineCacheState state);
4632 static const char* StubType2String(StubType type);
4633 static void PrintExtraICState(std::ostream& os, // NOLINT
4634 Kind kind, ExtraICState extra);
4635 void Disassemble(const char* name, std::ostream& os); // NOLINT
4636 #endif // ENABLE_DISASSEMBLER
4638 // [instruction_size]: Size of the native instructions
4639 inline int instruction_size() const;
4640 inline void set_instruction_size(int value);
4642 // [relocation_info]: Code relocation information
4643 DECL_ACCESSORS(relocation_info, ByteArray)
4644 void InvalidateRelocation();
4645 void InvalidateEmbeddedObjects();
4647 // [handler_table]: Fixed array containing offsets of exception handlers.
4648 DECL_ACCESSORS(handler_table, FixedArray)
4650 // [deoptimization_data]: Array containing data for deopt.
4651 DECL_ACCESSORS(deoptimization_data, FixedArray)
4653 // [raw_type_feedback_info]: This field stores various things, depending on
4654 // the kind of the code object.
4655 // FUNCTION => type feedback information.
4656 // STUB and ICs => major/minor key as Smi.
4657 DECL_ACCESSORS(raw_type_feedback_info, Object)
4658 inline Object* type_feedback_info();
4659 inline void set_type_feedback_info(
4660 Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
4661 inline uint32_t stub_key();
4662 inline void set_stub_key(uint32_t key);
4664 // [next_code_link]: Link for lists of optimized or deoptimized code.
4665 // Note that storage for this field is overlapped with typefeedback_info.
4666 DECL_ACCESSORS(next_code_link, Object)
4668 // [gc_metadata]: Field used to hold GC related metadata. The contents of this
4669 // field does not have to be traced during garbage collection since
4670 // it is only used by the garbage collector itself.
4671 DECL_ACCESSORS(gc_metadata, Object)
4673 // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
4674 // at the moment when this object was created.
4675 inline void set_ic_age(int count);
4676 inline int ic_age() const;
4678 // [prologue_offset]: Offset of the function prologue, used for aging
4679 // FUNCTIONs and OPTIMIZED_FUNCTIONs.
4680 inline int prologue_offset() const;
4681 inline void set_prologue_offset(int offset);
4683 // [constant_pool offset]: Offset of the constant pool.
4684 // Valid for FLAG_enable_embedded_constant_pool only
4685 inline int constant_pool_offset() const;
4686 inline void set_constant_pool_offset(int offset);
4688 // Unchecked accessors to be used during GC.
4689 inline ByteArray* unchecked_relocation_info();
4691 inline int relocation_size();
4693 // [flags]: Various code flags.
4694 inline Flags flags();
4695 inline void set_flags(Flags flags);
4697 // [flags]: Access to specific code flags.
4699 inline InlineCacheState ic_state(); // Only valid for IC stubs.
4700 inline ExtraICState extra_ic_state(); // Only valid for IC stubs.
4702 inline StubType type(); // Only valid for monomorphic IC stubs.
4704 // Testers for IC stub kinds.
4705 inline bool is_inline_cache_stub();
4706 inline bool is_debug_stub();
4707 inline bool is_handler() { return kind() == HANDLER; }
4708 inline bool is_load_stub() { return kind() == LOAD_IC; }
4709 inline bool is_keyed_load_stub() { return kind() == KEYED_LOAD_IC; }
4710 inline bool is_store_stub() { return kind() == STORE_IC; }
4711 inline bool is_keyed_store_stub() { return kind() == KEYED_STORE_IC; }
4712 inline bool is_call_stub() { return kind() == CALL_IC; }
4713 inline bool is_binary_op_stub() { return kind() == BINARY_OP_IC; }
4714 inline bool is_compare_ic_stub() { return kind() == COMPARE_IC; }
4715 inline bool is_compare_nil_ic_stub() { return kind() == COMPARE_NIL_IC; }
4716 inline bool is_to_boolean_ic_stub() { return kind() == TO_BOOLEAN_IC; }
4717 inline bool is_keyed_stub();
4718 inline bool is_optimized_code() { return kind() == OPTIMIZED_FUNCTION; }
4719 inline bool embeds_maps_weakly() {
4721 return (k == LOAD_IC || k == STORE_IC || k == KEYED_LOAD_IC ||
4722 k == KEYED_STORE_IC || k == COMPARE_NIL_IC) &&
4723 ic_state() == MONOMORPHIC;
4726 inline bool IsCodeStubOrIC();
4728 inline void set_raw_kind_specific_flags1(int value);
4729 inline void set_raw_kind_specific_flags2(int value);
4731 // [is_crankshafted]: For kind STUB or ICs, tells whether or not a code
4732 // object was generated by either the hydrogen or the TurboFan optimizing
4733 // compiler (but it may not be an optimized function).
4734 inline bool is_crankshafted();
4735 inline bool is_hydrogen_stub(); // Crankshafted, but not a function.
4736 inline void set_is_crankshafted(bool value);
4738 // [is_turbofanned]: For kind STUB or OPTIMIZED_FUNCTION, tells whether the
4739 // code object was generated by the TurboFan optimizing compiler.
4740 inline bool is_turbofanned();
4741 inline void set_is_turbofanned(bool value);
4743 // [can_have_weak_objects]: For kind OPTIMIZED_FUNCTION, tells whether the
4744 // embedded objects in code should be treated weakly.
4745 inline bool can_have_weak_objects();
4746 inline void set_can_have_weak_objects(bool value);
4748 // [has_deoptimization_support]: For FUNCTION kind, tells if it has
4749 // deoptimization support.
4750 inline bool has_deoptimization_support();
4751 inline void set_has_deoptimization_support(bool value);
4753 // [has_debug_break_slots]: For FUNCTION kind, tells if it has
4754 // been compiled with debug break slots.
4755 inline bool has_debug_break_slots();
4756 inline void set_has_debug_break_slots(bool value);
4758 // [has_reloc_info_for_serialization]: For FUNCTION kind, tells if its
4759 // reloc info includes runtime and external references to support
4760 // serialization/deserialization.
4761 inline bool has_reloc_info_for_serialization();
4762 inline void set_has_reloc_info_for_serialization(bool value);
4764 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
4765 // how long the function has been marked for OSR and therefore which
4766 // level of loop nesting we are willing to do on-stack replacement
4768 inline void set_allow_osr_at_loop_nesting_level(int level);
4769 inline int allow_osr_at_loop_nesting_level();
4771 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
4772 // the code object was seen on the stack with no IC patching going on.
4773 inline int profiler_ticks();
4774 inline void set_profiler_ticks(int ticks);
4776 // [builtin_index]: For BUILTIN kind, tells which builtin index it has.
4777 // For builtins, tells which builtin index it has.
4778 // Note that builtins can have a code kind other than BUILTIN, which means
4779 // that for arbitrary code objects, this index value may be random garbage.
4780 // To verify in that case, compare the code object to the indexed builtin.
4781 inline int builtin_index();
4782 inline void set_builtin_index(int id);
4784 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
4785 // reserved in the code prologue.
4786 inline unsigned stack_slots();
4787 inline void set_stack_slots(unsigned slots);
4789 // [safepoint_table_start]: For kind OPTIMIZED_FUNCTION, the offset in
4790 // the instruction stream where the safepoint table starts.
4791 inline unsigned safepoint_table_offset();
4792 inline void set_safepoint_table_offset(unsigned offset);
4794 // [back_edge_table_start]: For kind FUNCTION, the offset in the
4795 // instruction stream where the back edge table starts.
4796 inline unsigned back_edge_table_offset();
4797 inline void set_back_edge_table_offset(unsigned offset);
4799 inline bool back_edges_patched_for_osr();
4801 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
4802 inline uint16_t to_boolean_state();
4804 // [has_function_cache]: For kind STUB tells whether there is a function
4805 // cache is passed to the stub.
4806 inline bool has_function_cache();
4807 inline void set_has_function_cache(bool flag);
4810 // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
4811 // the code is going to be deoptimized because of dead embedded maps.
4812 inline bool marked_for_deoptimization();
4813 inline void set_marked_for_deoptimization(bool flag);
4815 // [constant_pool]: The constant pool for this function.
4816 inline Address constant_pool();
4818 // Get the safepoint entry for the given pc.
4819 SafepointEntry GetSafepointEntry(Address pc);
4821 // Find an object in a stub with a specified map
4822 Object* FindNthObject(int n, Map* match_map);
4824 // Find the first allocation site in an IC stub.
4825 AllocationSite* FindFirstAllocationSite();
4827 // Find the first map in an IC stub.
4828 Map* FindFirstMap();
4829 void FindAllMaps(MapHandleList* maps);
4831 // Find the first handler in an IC stub.
4832 Code* FindFirstHandler();
4834 // Find |length| handlers and put them into |code_list|. Returns false if not
4835 // enough handlers can be found.
4836 bool FindHandlers(CodeHandleList* code_list, int length = -1);
4838 // Find the handler for |map|.
4839 MaybeHandle<Code> FindHandlerForMap(Map* map);
4841 // Find the first name in an IC stub.
4842 Name* FindFirstName();
4844 class FindAndReplacePattern;
4845 // For each (map-to-find, object-to-replace) pair in the pattern, this
4846 // function replaces the corresponding placeholder in the code with the
4847 // object-to-replace. The function assumes that pairs in the pattern come in
4848 // the same order as the placeholders in the code.
4849 // If the placeholder is a weak cell, then the value of weak cell is matched
4850 // against the map-to-find.
4851 void FindAndReplace(const FindAndReplacePattern& pattern);
4853 // The entire code object including its header is copied verbatim to the
4854 // snapshot so that it can be written in one, fast, memcpy during
4855 // deserialization. The deserializer will overwrite some pointers, rather
4856 // like a runtime linker, but the random allocation addresses used in the
4857 // mksnapshot process would still be present in the unlinked snapshot data,
4858 // which would make snapshot production non-reproducible. This method wipes
4859 // out the to-be-overwritten header data for reproducible snapshots.
4860 inline void WipeOutHeader();
4862 // Flags operations.
4863 static inline Flags ComputeFlags(
4864 Kind kind, InlineCacheState ic_state = UNINITIALIZED,
4865 ExtraICState extra_ic_state = kNoExtraICState, StubType type = NORMAL,
4866 CacheHolderFlag holder = kCacheOnReceiver);
4868 static inline Flags ComputeMonomorphicFlags(
4869 Kind kind, ExtraICState extra_ic_state = kNoExtraICState,
4870 CacheHolderFlag holder = kCacheOnReceiver, StubType type = NORMAL);
4872 static inline Flags ComputeHandlerFlags(
4873 Kind handler_kind, StubType type = NORMAL,
4874 CacheHolderFlag holder = kCacheOnReceiver);
4876 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
4877 static inline StubType ExtractTypeFromFlags(Flags flags);
4878 static inline CacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
4879 static inline Kind ExtractKindFromFlags(Flags flags);
4880 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
4882 static inline Flags RemoveTypeFromFlags(Flags flags);
4883 static inline Flags RemoveTypeAndHolderFromFlags(Flags flags);
4885 // Convert a target address into a code object.
4886 static inline Code* GetCodeFromTargetAddress(Address address);
4888 // Convert an entry address into an object.
4889 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
4891 // Returns the address of the first instruction.
4892 inline byte* instruction_start();
4894 // Returns the address right after the last instruction.
4895 inline byte* instruction_end();
4897 // Returns the size of the instructions, padding, and relocation information.
4898 inline int body_size();
4900 // Returns the address of the first relocation info (read backwards!).
4901 inline byte* relocation_start();
4903 // Code entry point.
4904 inline byte* entry();
4906 // Returns true if pc is inside this object's instructions.
4907 inline bool contains(byte* pc);
4909 // Relocate the code by delta bytes. Called to signal that this code
4910 // object has been moved by delta bytes.
4911 void Relocate(intptr_t delta);
4913 // Migrate code described by desc.
4914 void CopyFrom(const CodeDesc& desc);
4916 // Returns the object size for a given body (used for allocation).
4917 static int SizeFor(int body_size) {
4918 DCHECK_SIZE_TAG_ALIGNED(body_size);
4919 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
4922 // Calculate the size of the code object to report for log events. This takes
4923 // the layout of the code object into account.
4924 int ExecutableSize() {
4925 // Check that the assumptions about the layout of the code object holds.
4926 DCHECK_EQ(static_cast<int>(instruction_start() - address()),
4928 return instruction_size() + Code::kHeaderSize;
4931 // Locating source position.
4932 int SourcePosition(Address pc);
4933 int SourceStatementPosition(Address pc);
4937 // Dispatched behavior.
4938 int CodeSize() { return SizeFor(body_size()); }
4939 inline void CodeIterateBody(ObjectVisitor* v);
4941 template<typename StaticVisitor>
4942 inline void CodeIterateBody(Heap* heap);
4944 DECLARE_PRINTER(Code)
4945 DECLARE_VERIFIER(Code)
4947 void ClearInlineCaches();
4948 void ClearInlineCaches(Kind kind);
4950 BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
4951 uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
4953 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
4955 kToBeExecutedOnceCodeAge = -3,
4956 kNotExecutedCodeAge = -2,
4957 kExecutedOnceCodeAge = -1,
4959 CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
4961 kFirstCodeAge = kToBeExecutedOnceCodeAge,
4962 kLastCodeAge = kAfterLastCodeAge - 1,
4963 kCodeAgeCount = kAfterLastCodeAge - kFirstCodeAge - 1,
4964 kIsOldCodeAge = kSexagenarianCodeAge,
4965 kPreAgedCodeAge = kIsOldCodeAge - 1
4967 #undef DECLARE_CODE_AGE_ENUM
4969 // Code aging. Indicates how many full GCs this code has survived without
4970 // being entered through the prologue. Used to determine when it is
4971 // relatively safe to flush this code object and replace it with the lazy
4972 // compilation stub.
4973 static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
4974 static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
4975 void MakeYoung(Isolate* isolate);
4976 void MarkToBeExecutedOnce(Isolate* isolate);
4977 void MakeOlder(MarkingParity);
4978 static bool IsYoungSequence(Isolate* isolate, byte* sequence);
4981 static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
4982 return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
4985 void PrintDeoptLocation(FILE* out, Address pc);
4986 bool CanDeoptAt(Address pc);
4989 void VerifyEmbeddedObjectsDependency();
4993 enum VerifyMode { kNoContextSpecificPointers, kNoContextRetainingPointers };
4994 void VerifyEmbeddedObjects(VerifyMode mode = kNoContextRetainingPointers);
4997 inline bool CanContainWeakObjects() {
4998 // is_turbofanned() implies !can_have_weak_objects().
4999 DCHECK(!is_optimized_code() || !is_turbofanned() ||
5000 !can_have_weak_objects());
5001 return is_optimized_code() && can_have_weak_objects();
5004 inline bool IsWeakObject(Object* object) {
5005 return (CanContainWeakObjects() && IsWeakObjectInOptimizedCode(object));
5008 static inline bool IsWeakObjectInOptimizedCode(Object* object);
5010 static Handle<WeakCell> WeakCellFor(Handle<Code> code);
5011 WeakCell* CachedWeakCell();
5013 // Max loop nesting marker used to postpose OSR. We don't take loop
5014 // nesting that is deeper than 5 levels into account.
5015 static const int kMaxLoopNestingMarker = 6;
5017 static const int kConstantPoolSize =
5018 FLAG_enable_embedded_constant_pool ? kIntSize : 0;
5020 // Layout description.
5021 static const int kRelocationInfoOffset = HeapObject::kHeaderSize;
5022 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
5023 static const int kDeoptimizationDataOffset =
5024 kHandlerTableOffset + kPointerSize;
5025 // For FUNCTION kind, we store the type feedback info here.
5026 static const int kTypeFeedbackInfoOffset =
5027 kDeoptimizationDataOffset + kPointerSize;
5028 static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
5029 static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
5030 static const int kInstructionSizeOffset = kGCMetadataOffset + kPointerSize;
5031 static const int kICAgeOffset = kInstructionSizeOffset + kIntSize;
5032 static const int kFlagsOffset = kICAgeOffset + kIntSize;
5033 static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
5034 static const int kKindSpecificFlags2Offset =
5035 kKindSpecificFlags1Offset + kIntSize;
5036 // Note: We might be able to squeeze this into the flags above.
5037 static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
5038 static const int kConstantPoolOffset = kPrologueOffset + kIntSize;
5039 static const int kHeaderPaddingStart =
5040 kConstantPoolOffset + kConstantPoolSize;
5042 // Add padding to align the instruction start following right after
5043 // the Code object header.
5044 static const int kHeaderSize =
5045 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
5047 // Byte offsets within kKindSpecificFlags1Offset.
5048 static const int kFullCodeFlags = kKindSpecificFlags1Offset;
5049 class FullCodeFlagsHasDeoptimizationSupportField:
5050 public BitField<bool, 0, 1> {}; // NOLINT
5051 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
5052 class FullCodeFlagsHasRelocInfoForSerialization
5053 : public BitField<bool, 2, 1> {};
5054 // Bit 3 in this bitfield is unused.
5055 class ProfilerTicksField : public BitField<int, 4, 28> {};
5057 // Flags layout. BitField<type, shift, size>.
5058 class ICStateField : public BitField<InlineCacheState, 0, 4> {};
5059 class TypeField : public BitField<StubType, 4, 1> {};
5060 class CacheHolderField : public BitField<CacheHolderFlag, 5, 2> {};
5061 class KindField : public BitField<Kind, 7, 4> {};
5062 class ExtraICStateField: public BitField<ExtraICState, 11,
5063 PlatformSmiTagging::kSmiValueSize - 11 + 1> {}; // NOLINT
5065 // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
5066 static const int kStackSlotsFirstBit = 0;
5067 static const int kStackSlotsBitCount = 24;
5068 static const int kHasFunctionCacheBit =
5069 kStackSlotsFirstBit + kStackSlotsBitCount;
5070 static const int kMarkedForDeoptimizationBit = kHasFunctionCacheBit + 1;
5071 static const int kIsTurbofannedBit = kMarkedForDeoptimizationBit + 1;
5072 static const int kCanHaveWeakObjects = kIsTurbofannedBit + 1;
5074 STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
5075 STATIC_ASSERT(kCanHaveWeakObjects + 1 <= 32);
5077 class StackSlotsField: public BitField<int,
5078 kStackSlotsFirstBit, kStackSlotsBitCount> {}; // NOLINT
5079 class HasFunctionCacheField : public BitField<bool, kHasFunctionCacheBit, 1> {
5081 class MarkedForDeoptimizationField
5082 : public BitField<bool, kMarkedForDeoptimizationBit, 1> {}; // NOLINT
5083 class IsTurbofannedField : public BitField<bool, kIsTurbofannedBit, 1> {
5085 class CanHaveWeakObjectsField
5086 : public BitField<bool, kCanHaveWeakObjects, 1> {}; // NOLINT
5088 // KindSpecificFlags2 layout (ALL)
5089 static const int kIsCrankshaftedBit = 0;
5090 class IsCrankshaftedField: public BitField<bool,
5091 kIsCrankshaftedBit, 1> {}; // NOLINT
5093 // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
5094 static const int kSafepointTableOffsetFirstBit = kIsCrankshaftedBit + 1;
5095 static const int kSafepointTableOffsetBitCount = 30;
5097 STATIC_ASSERT(kSafepointTableOffsetFirstBit +
5098 kSafepointTableOffsetBitCount <= 32);
5099 STATIC_ASSERT(1 + kSafepointTableOffsetBitCount <= 32);
5101 class SafepointTableOffsetField: public BitField<int,
5102 kSafepointTableOffsetFirstBit,
5103 kSafepointTableOffsetBitCount> {}; // NOLINT
5105 // KindSpecificFlags2 layout (FUNCTION)
5106 class BackEdgeTableOffsetField: public BitField<int,
5107 kIsCrankshaftedBit + 1, 27> {}; // NOLINT
5108 class AllowOSRAtLoopNestingLevelField: public BitField<int,
5109 kIsCrankshaftedBit + 1 + 27, 4> {}; // NOLINT
5110 STATIC_ASSERT(AllowOSRAtLoopNestingLevelField::kMax >= kMaxLoopNestingMarker);
5112 static const int kArgumentsBits = 16;
5113 static const int kMaxArguments = (1 << kArgumentsBits) - 1;
5115 // This constant should be encodable in an ARM instruction.
5116 static const int kFlagsNotUsedInLookup =
5117 TypeField::kMask | CacheHolderField::kMask;
5120 friend class RelocIterator;
5121 friend class Deoptimizer; // For FindCodeAgeSequence.
5123 void ClearInlineCaches(Kind* kind);
5126 byte* FindCodeAgeSequence();
5127 static void GetCodeAgeAndParity(Code* code, Age* age,
5128 MarkingParity* parity);
5129 static void GetCodeAgeAndParity(Isolate* isolate, byte* sequence, Age* age,
5130 MarkingParity* parity);
5131 static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
5133 // Code aging -- platform-specific
5134 static void PatchPlatformCodeAge(Isolate* isolate,
5135 byte* sequence, Age age,
5136 MarkingParity parity);
5138 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5142 // This class describes the layout of dependent codes array of a map. The
5143 // array is partitioned into several groups of dependent codes. Each group
5144 // contains codes with the same dependency on the map. The array has the
5145 // following layout for n dependency groups:
5147 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5148 // | C1 | C2 | ... | Cn | group 1 | group 2 | ... | group n | undefined |
5149 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5151 // The first n elements are Smis, each of them specifies the number of codes
5152 // in the corresponding group. The subsequent elements contain grouped code
5153 // objects in weak cells. The suffix of the array can be filled with the
5154 // undefined value if the number of codes is less than the length of the
5155 // array. The order of the code objects within a group is not preserved.
5157 // All code indexes used in the class are counted starting from the first
5158 // code object of the first group. In other words, code index 0 corresponds
5159 // to array index n = kCodesStartIndex.
5161 class DependentCode: public FixedArray {
5163 enum DependencyGroup {
5164 // Group of code that weakly embed this map and depend on being
5165 // deoptimized when the map is garbage collected.
5167 // Group of code that embed a transition to this map, and depend on being
5168 // deoptimized when the transition is replaced by a new version.
5170 // Group of code that omit run-time prototype checks for prototypes
5171 // described by this map. The group is deoptimized whenever an object
5172 // described by this map changes shape (and transitions to a new map),
5173 // possibly invalidating the assumptions embedded in the code.
5174 kPrototypeCheckGroup,
5175 // Group of code that depends on global property values in property cells
5176 // not being changed.
5177 kPropertyCellChangedGroup,
5178 // Group of code that omit run-time type checks for the field(s) introduced
5181 // Group of code that omit run-time type checks for initial maps of
5183 kInitialMapChangedGroup,
5184 // Group of code that depends on tenuring information in AllocationSites
5185 // not being changed.
5186 kAllocationSiteTenuringChangedGroup,
5187 // Group of code that depends on element transition information in
5188 // AllocationSites not being changed.
5189 kAllocationSiteTransitionChangedGroup
5192 static const int kGroupCount = kAllocationSiteTransitionChangedGroup + 1;
5194 // Array for holding the index of the first code object of each group.
5195 // The last element stores the total number of code objects.
5196 class GroupStartIndexes {
5198 explicit GroupStartIndexes(DependentCode* entries);
5199 void Recompute(DependentCode* entries);
5200 int at(int i) { return start_indexes_[i]; }
5201 int number_of_entries() { return start_indexes_[kGroupCount]; }
5203 int start_indexes_[kGroupCount + 1];
5206 bool Contains(DependencyGroup group, WeakCell* code_cell);
5208 static Handle<DependentCode> InsertCompilationDependencies(
5209 Handle<DependentCode> entries, DependencyGroup group,
5210 Handle<Foreign> info);
5212 static Handle<DependentCode> InsertWeakCode(Handle<DependentCode> entries,
5213 DependencyGroup group,
5214 Handle<WeakCell> code_cell);
5216 void UpdateToFinishedCode(DependencyGroup group, Foreign* info,
5217 WeakCell* code_cell);
5219 void RemoveCompilationDependencies(DependentCode::DependencyGroup group,
5222 void DeoptimizeDependentCodeGroup(Isolate* isolate,
5223 DependentCode::DependencyGroup group);
5225 bool MarkCodeForDeoptimization(Isolate* isolate,
5226 DependentCode::DependencyGroup group);
5228 // The following low-level accessors should only be used by this class
5229 // and the mark compact collector.
5230 inline int number_of_entries(DependencyGroup group);
5231 inline void set_number_of_entries(DependencyGroup group, int value);
5232 inline Object* object_at(int i);
5233 inline void set_object_at(int i, Object* object);
5234 inline void clear_at(int i);
5235 inline void copy(int from, int to);
5236 DECLARE_CAST(DependentCode)
5238 static const char* DependencyGroupName(DependencyGroup group);
5239 static void SetMarkedForDeoptimization(Code* code, DependencyGroup group);
5242 static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5243 DependencyGroup group,
5244 Handle<Object> object);
5245 static Handle<DependentCode> EnsureSpace(Handle<DependentCode> entries);
5246 // Make a room at the end of the given group by moving out the first
5247 // code objects of the subsequent groups.
5248 inline void ExtendGroup(DependencyGroup group);
5249 // Compact by removing cleared weak cells and return true if there was
5250 // any cleared weak cell.
5252 static int Grow(int number_of_entries) {
5253 if (number_of_entries < 5) return number_of_entries + 1;
5254 return number_of_entries * 5 / 4;
5256 static const int kCodesStartIndex = kGroupCount;
5260 class PrototypeInfo;
5263 // All heap objects have a Map that describes their structure.
5264 // A Map contains information about:
5265 // - Size information about the object
5266 // - How to iterate over an object (for garbage collection)
5267 class Map: public HeapObject {
5270 // Size in bytes or kVariableSizeSentinel if instances do not have
5272 inline int instance_size();
5273 inline void set_instance_size(int value);
5275 // Only to clear an unused byte, remove once byte is used.
5276 inline void clear_unused();
5278 // Count of properties allocated in the object.
5279 inline int inobject_properties();
5280 inline void set_inobject_properties(int value);
5283 inline InstanceType instance_type();
5284 inline void set_instance_type(InstanceType value);
5286 // Tells how many unused property fields are available in the
5287 // instance (only used for JSObject in fast mode).
5288 inline int unused_property_fields();
5289 inline void set_unused_property_fields(int value);
5292 inline byte bit_field() const;
5293 inline void set_bit_field(byte value);
5296 inline byte bit_field2() const;
5297 inline void set_bit_field2(byte value);
5300 inline uint32_t bit_field3() const;
5301 inline void set_bit_field3(uint32_t bits);
5303 class EnumLengthBits: public BitField<int,
5304 0, kDescriptorIndexBitCount> {}; // NOLINT
5305 class NumberOfOwnDescriptorsBits: public BitField<int,
5306 kDescriptorIndexBitCount, kDescriptorIndexBitCount> {}; // NOLINT
5307 STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
5308 class DictionaryMap : public BitField<bool, 20, 1> {};
5309 class OwnsDescriptors : public BitField<bool, 21, 1> {};
5310 class HasInstanceCallHandler : public BitField<bool, 22, 1> {};
5311 class Deprecated : public BitField<bool, 23, 1> {};
5312 class IsUnstable : public BitField<bool, 24, 1> {};
5313 class IsMigrationTarget : public BitField<bool, 25, 1> {};
5314 class IsStrong : public BitField<bool, 26, 1> {};
5317 // Keep this bit field at the very end for better code in
5318 // Builtins::kJSConstructStubGeneric stub.
5319 // This counter is used for in-object slack tracking and for map aging.
5320 // The in-object slack tracking is considered enabled when the counter is
5321 // in the range [kSlackTrackingCounterStart, kSlackTrackingCounterEnd].
5322 class Counter : public BitField<int, 28, 4> {};
5323 static const int kSlackTrackingCounterStart = 14;
5324 static const int kSlackTrackingCounterEnd = 8;
5325 static const int kRetainingCounterStart = kSlackTrackingCounterEnd - 1;
5326 static const int kRetainingCounterEnd = 0;
5328 // Tells whether the object in the prototype property will be used
5329 // for instances created from this function. If the prototype
5330 // property is set to a value that is not a JSObject, the prototype
5331 // property will not be used to create instances of the function.
5332 // See ECMA-262, 13.2.2.
5333 inline void set_non_instance_prototype(bool value);
5334 inline bool has_non_instance_prototype();
5336 // Tells whether function has special prototype property. If not, prototype
5337 // property will not be created when accessed (will return undefined),
5338 // and construction from this function will not be allowed.
5339 inline void set_function_with_prototype(bool value);
5340 inline bool function_with_prototype();
5342 // Tells whether the instance with this map should be ignored by the
5343 // Object.getPrototypeOf() function and the __proto__ accessor.
5344 inline void set_is_hidden_prototype() {
5345 set_bit_field(bit_field() | (1 << kIsHiddenPrototype));
5348 inline bool is_hidden_prototype() {
5349 return ((1 << kIsHiddenPrototype) & bit_field()) != 0;
5352 // Records and queries whether the instance has a named interceptor.
5353 inline void set_has_named_interceptor() {
5354 set_bit_field(bit_field() | (1 << kHasNamedInterceptor));
5357 inline bool has_named_interceptor() {
5358 return ((1 << kHasNamedInterceptor) & bit_field()) != 0;
5361 // Records and queries whether the instance has an indexed interceptor.
5362 inline void set_has_indexed_interceptor() {
5363 set_bit_field(bit_field() | (1 << kHasIndexedInterceptor));
5366 inline bool has_indexed_interceptor() {
5367 return ((1 << kHasIndexedInterceptor) & bit_field()) != 0;
5370 // Tells whether the instance is undetectable.
5371 // An undetectable object is a special class of JSObject: 'typeof' operator
5372 // returns undefined, ToBoolean returns false. Otherwise it behaves like
5373 // a normal JS object. It is useful for implementing undetectable
5374 // document.all in Firefox & Safari.
5375 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
5376 inline void set_is_undetectable() {
5377 set_bit_field(bit_field() | (1 << kIsUndetectable));
5380 inline bool is_undetectable() {
5381 return ((1 << kIsUndetectable) & bit_field()) != 0;
5384 // Tells whether the instance has a call-as-function handler.
5385 inline void set_is_observed() {
5386 set_bit_field(bit_field() | (1 << kIsObserved));
5389 inline bool is_observed() {
5390 return ((1 << kIsObserved) & bit_field()) != 0;
5393 inline void set_is_strong();
5394 inline bool is_strong();
5395 inline void set_is_extensible(bool value);
5396 inline bool is_extensible();
5397 inline void set_is_prototype_map(bool value);
5398 inline bool is_prototype_map() const;
5400 inline void set_elements_kind(ElementsKind elements_kind) {
5401 DCHECK(static_cast<int>(elements_kind) < kElementsKindCount);
5402 DCHECK(kElementsKindCount <= (1 << Map::ElementsKindBits::kSize));
5403 set_bit_field2(Map::ElementsKindBits::update(bit_field2(), elements_kind));
5404 DCHECK(this->elements_kind() == elements_kind);
5407 inline ElementsKind elements_kind() {
5408 return Map::ElementsKindBits::decode(bit_field2());
5411 // Tells whether the instance has fast elements that are only Smis.
5412 inline bool has_fast_smi_elements() {
5413 return IsFastSmiElementsKind(elements_kind());
5416 // Tells whether the instance has fast elements.
5417 inline bool has_fast_object_elements() {
5418 return IsFastObjectElementsKind(elements_kind());
5421 inline bool has_fast_smi_or_object_elements() {
5422 return IsFastSmiOrObjectElementsKind(elements_kind());
5425 inline bool has_fast_double_elements() {
5426 return IsFastDoubleElementsKind(elements_kind());
5429 inline bool has_fast_elements() {
5430 return IsFastElementsKind(elements_kind());
5433 inline bool has_sloppy_arguments_elements() {
5434 return IsSloppyArgumentsElements(elements_kind());
5437 inline bool has_fixed_typed_array_elements() {
5438 return IsFixedTypedArrayElementsKind(elements_kind());
5441 inline bool has_dictionary_elements() {
5442 return IsDictionaryElementsKind(elements_kind());
5445 static bool IsValidElementsTransition(ElementsKind from_kind,
5446 ElementsKind to_kind);
5448 // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
5449 // map with DICTIONARY_ELEMENTS was found in the prototype chain.
5450 bool DictionaryElementsInPrototypeChainOnly();
5452 inline Map* ElementsTransitionMap();
5454 inline FixedArrayBase* GetInitialElements();
5456 // [raw_transitions]: Provides access to the transitions storage field.
5457 // Don't call set_raw_transitions() directly to overwrite transitions, use
5458 // the TransitionArray::ReplaceTransitions() wrapper instead!
5459 DECL_ACCESSORS(raw_transitions, Object)
5460 // [prototype_info]: Per-prototype metadata. Aliased with transitions
5461 // (which prototype maps don't have).
5462 DECL_ACCESSORS(prototype_info, Object)
5463 // PrototypeInfo is created lazily using this helper (which installs it on
5464 // the given prototype's map).
5465 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5466 Handle<JSObject> prototype, Isolate* isolate);
5468 // [prototype chain validity cell]: Associated with a prototype object,
5469 // stored in that object's map's PrototypeInfo, indicates that prototype
5470 // chains through this object are currently valid. The cell will be
5471 // invalidated and replaced when the prototype chain changes.
5472 static Handle<Cell> GetOrCreatePrototypeChainValidityCell(Handle<Map> map,
5474 static const int kPrototypeChainValid = 0;
5475 static const int kPrototypeChainInvalid = 1;
5478 Map* FindFieldOwner(int descriptor);
5480 inline int GetInObjectPropertyOffset(int index);
5482 int NumberOfFields();
5484 // TODO(ishell): candidate with JSObject::MigrateToMap().
5485 bool InstancesNeedRewriting(Map* target, int target_number_of_fields,
5486 int target_inobject, int target_unused,
5487 int* old_number_of_fields);
5488 // TODO(ishell): moveit!
5489 static Handle<Map> GeneralizeAllFieldRepresentations(Handle<Map> map);
5490 MUST_USE_RESULT static Handle<HeapType> GeneralizeFieldType(
5491 Handle<HeapType> type1,
5492 Handle<HeapType> type2,
5494 static void GeneralizeFieldType(Handle<Map> map, int modify_index,
5495 Representation new_representation,
5496 Handle<HeapType> new_field_type);
5497 static Handle<Map> ReconfigureProperty(Handle<Map> map, int modify_index,
5498 PropertyKind new_kind,
5499 PropertyAttributes new_attributes,
5500 Representation new_representation,
5501 Handle<HeapType> new_field_type,
5502 StoreMode store_mode);
5503 static Handle<Map> CopyGeneralizeAllRepresentations(
5504 Handle<Map> map, int modify_index, StoreMode store_mode,
5505 PropertyKind kind, PropertyAttributes attributes, const char* reason);
5507 static Handle<Map> PrepareForDataProperty(Handle<Map> old_map,
5508 int descriptor_number,
5509 Handle<Object> value);
5511 static Handle<Map> Normalize(Handle<Map> map, PropertyNormalizationMode mode,
5512 const char* reason);
5514 // Returns the constructor name (the name (possibly, inferred name) of the
5515 // function that was used to instantiate the object).
5516 String* constructor_name();
5518 // Tells whether the map is used for JSObjects in dictionary mode (ie
5519 // normalized objects, ie objects for which HasFastProperties returns false).
5520 // A map can never be used for both dictionary mode and fast mode JSObjects.
5521 // False by default and for HeapObjects that are not JSObjects.
5522 inline void set_dictionary_map(bool value);
5523 inline bool is_dictionary_map();
5525 // Tells whether the instance needs security checks when accessing its
5527 inline void set_is_access_check_needed(bool access_check_needed);
5528 inline bool is_access_check_needed();
5530 // Returns true if map has a non-empty stub code cache.
5531 inline bool has_code_cache();
5533 // [prototype]: implicit prototype object.
5534 DECL_ACCESSORS(prototype, Object)
5535 // TODO(jkummerow): make set_prototype private.
5536 static void SetPrototype(
5537 Handle<Map> map, Handle<Object> prototype,
5538 PrototypeOptimizationMode proto_mode = FAST_PROTOTYPE);
5540 // [constructor]: points back to the function responsible for this map.
5541 // The field overlaps with the back pointer. All maps in a transition tree
5542 // have the same constructor, so maps with back pointers can walk the
5543 // back pointer chain until they find the map holding their constructor.
5544 DECL_ACCESSORS(constructor_or_backpointer, Object)
5545 inline Object* GetConstructor() const;
5546 inline void SetConstructor(Object* constructor,
5547 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5548 // [back pointer]: points back to the parent map from which a transition
5549 // leads to this map. The field overlaps with the constructor (see above).
5550 inline Object* GetBackPointer();
5551 inline void SetBackPointer(Object* value,
5552 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5554 // [instance descriptors]: describes the object.
5555 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
5557 // [layout descriptor]: describes the object layout.
5558 DECL_ACCESSORS(layout_descriptor, LayoutDescriptor)
5559 // |layout descriptor| accessor which can be used from GC.
5560 inline LayoutDescriptor* layout_descriptor_gc_safe();
5561 inline bool HasFastPointerLayout() const;
5563 // |layout descriptor| accessor that is safe to call even when
5564 // FLAG_unbox_double_fields is disabled (in this case Map does not contain
5565 // |layout_descriptor| field at all).
5566 inline LayoutDescriptor* GetLayoutDescriptor();
5568 inline void UpdateDescriptors(DescriptorArray* descriptors,
5569 LayoutDescriptor* layout_descriptor);
5570 inline void InitializeDescriptors(DescriptorArray* descriptors,
5571 LayoutDescriptor* layout_descriptor);
5573 // [stub cache]: contains stubs compiled for this map.
5574 DECL_ACCESSORS(code_cache, Object)
5576 // [dependent code]: list of optimized codes that weakly embed this map.
5577 DECL_ACCESSORS(dependent_code, DependentCode)
5579 // [weak cell cache]: cache that stores a weak cell pointing to this map.
5580 DECL_ACCESSORS(weak_cell_cache, Object)
5582 inline PropertyDetails GetLastDescriptorDetails();
5585 int number_of_own_descriptors = NumberOfOwnDescriptors();
5586 DCHECK(number_of_own_descriptors > 0);
5587 return number_of_own_descriptors - 1;
5590 int NumberOfOwnDescriptors() {
5591 return NumberOfOwnDescriptorsBits::decode(bit_field3());
5594 void SetNumberOfOwnDescriptors(int number) {
5595 DCHECK(number <= instance_descriptors()->number_of_descriptors());
5596 set_bit_field3(NumberOfOwnDescriptorsBits::update(bit_field3(), number));
5599 inline Cell* RetrieveDescriptorsPointer();
5602 return EnumLengthBits::decode(bit_field3());
5605 void SetEnumLength(int length) {
5606 if (length != kInvalidEnumCacheSentinel) {
5607 DCHECK(length >= 0);
5608 DCHECK(length == 0 || instance_descriptors()->HasEnumCache());
5609 DCHECK(length <= NumberOfOwnDescriptors());
5611 set_bit_field3(EnumLengthBits::update(bit_field3(), length));
5614 inline bool owns_descriptors();
5615 inline void set_owns_descriptors(bool owns_descriptors);
5616 inline bool has_instance_call_handler();
5617 inline void set_has_instance_call_handler();
5618 inline void mark_unstable();
5619 inline bool is_stable();
5620 inline void set_migration_target(bool value);
5621 inline bool is_migration_target();
5622 inline void set_counter(int value);
5623 inline int counter();
5624 inline void deprecate();
5625 inline bool is_deprecated();
5626 inline bool CanBeDeprecated();
5627 // Returns a non-deprecated version of the input. If the input was not
5628 // deprecated, it is directly returned. Otherwise, the non-deprecated version
5629 // is found by re-transitioning from the root of the transition tree using the
5630 // descriptor array of the map. Returns MaybeHandle<Map>() if no updated map
5632 static MaybeHandle<Map> TryUpdate(Handle<Map> map) WARN_UNUSED_RESULT;
5634 // Returns a non-deprecated version of the input. This method may deprecate
5635 // existing maps along the way if encodings conflict. Not for use while
5636 // gathering type feedback. Use TryUpdate in those cases instead.
5637 static Handle<Map> Update(Handle<Map> map);
5639 static Handle<Map> CopyDropDescriptors(Handle<Map> map);
5640 static Handle<Map> CopyInsertDescriptor(Handle<Map> map,
5641 Descriptor* descriptor,
5642 TransitionFlag flag);
5644 MUST_USE_RESULT static MaybeHandle<Map> CopyWithField(
5647 Handle<HeapType> type,
5648 PropertyAttributes attributes,
5649 Representation representation,
5650 TransitionFlag flag);
5652 MUST_USE_RESULT static MaybeHandle<Map> CopyWithConstant(
5655 Handle<Object> constant,
5656 PropertyAttributes attributes,
5657 TransitionFlag flag);
5659 // Returns a new map with all transitions dropped from the given map and
5660 // the ElementsKind set.
5661 static Handle<Map> TransitionElementsTo(Handle<Map> map,
5662 ElementsKind to_kind);
5664 static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
5666 static Handle<Map> CopyAsElementsKind(Handle<Map> map,
5668 TransitionFlag flag);
5670 static Handle<Map> CopyForObserved(Handle<Map> map);
5672 static Handle<Map> CopyForPreventExtensions(Handle<Map> map,
5673 PropertyAttributes attrs_to_add,
5674 Handle<Symbol> transition_marker,
5675 const char* reason);
5677 static Handle<Map> FixProxy(Handle<Map> map, InstanceType type, int size);
5680 // Maximal number of fast properties. Used to restrict the number of map
5681 // transitions to avoid an explosion in the number of maps for objects used as
5683 inline bool TooManyFastProperties(StoreFromKeyed store_mode);
5684 static Handle<Map> TransitionToDataProperty(Handle<Map> map,
5686 Handle<Object> value,
5687 PropertyAttributes attributes,
5688 StoreFromKeyed store_mode);
5689 static Handle<Map> TransitionToAccessorProperty(
5690 Handle<Map> map, Handle<Name> name, AccessorComponent component,
5691 Handle<Object> accessor, PropertyAttributes attributes);
5692 static Handle<Map> ReconfigureExistingProperty(Handle<Map> map,
5695 PropertyAttributes attributes);
5697 inline void AppendDescriptor(Descriptor* desc);
5699 // Returns a copy of the map, prepared for inserting into the transition
5700 // tree (if the |map| owns descriptors then the new one will share
5701 // descriptors with |map|).
5702 static Handle<Map> CopyForTransition(Handle<Map> map, const char* reason);
5704 // Returns a copy of the map, with all transitions dropped from the
5705 // instance descriptors.
5706 static Handle<Map> Copy(Handle<Map> map, const char* reason);
5707 static Handle<Map> Create(Isolate* isolate, int inobject_properties);
5709 // Returns the next free property index (only valid for FAST MODE).
5710 int NextFreePropertyIndex();
5712 // Returns the number of properties described in instance_descriptors
5713 // filtering out properties with the specified attributes.
5714 int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
5715 PropertyAttributes filter = NONE);
5719 // Code cache operations.
5721 // Clears the code cache.
5722 inline void ClearCodeCache(Heap* heap);
5724 // Update code cache.
5725 static void UpdateCodeCache(Handle<Map> map,
5729 // Extend the descriptor array of the map with the list of descriptors.
5730 // In case of duplicates, the latest descriptor is used.
5731 static void AppendCallbackDescriptors(Handle<Map> map,
5732 Handle<Object> descriptors);
5734 static inline int SlackForArraySize(int old_size, int size_limit);
5736 static void EnsureDescriptorSlack(Handle<Map> map, int slack);
5738 // Returns the found code or undefined if absent.
5739 Object* FindInCodeCache(Name* name, Code::Flags flags);
5741 // Returns the non-negative index of the code object if it is in the
5742 // cache and -1 otherwise.
5743 int IndexInCodeCache(Object* name, Code* code);
5745 // Removes a code object from the code cache at the given index.
5746 void RemoveFromCodeCache(Name* name, Code* code, int index);
5748 // Computes a hash value for this map, to be used in HashTables and such.
5751 // Returns the map that this map transitions to if its elements_kind
5752 // is changed to |elements_kind|, or NULL if no such map is cached yet.
5753 // |safe_to_add_transitions| is set to false if adding transitions is not
5755 Map* LookupElementsTransitionMap(ElementsKind elements_kind);
5757 // Returns the transitioned map for this map with the most generic
5758 // elements_kind that's found in |candidates|, or null handle if no match is
5760 static Handle<Map> FindTransitionedMap(Handle<Map> map,
5761 MapHandleList* candidates);
5763 bool CanTransition() {
5764 // Only JSObject and subtypes have map transitions and back pointers.
5765 STATIC_ASSERT(LAST_TYPE == LAST_JS_OBJECT_TYPE);
5766 return instance_type() >= FIRST_JS_OBJECT_TYPE;
5769 bool IsJSObjectMap() {
5770 return instance_type() >= FIRST_JS_OBJECT_TYPE;
5772 bool IsJSArrayMap() { return instance_type() == JS_ARRAY_TYPE; }
5773 bool IsStringMap() { return instance_type() < FIRST_NONSTRING_TYPE; }
5774 bool IsJSProxyMap() {
5775 InstanceType type = instance_type();
5776 return FIRST_JS_PROXY_TYPE <= type && type <= LAST_JS_PROXY_TYPE;
5778 bool IsJSGlobalProxyMap() {
5779 return instance_type() == JS_GLOBAL_PROXY_TYPE;
5781 bool IsJSGlobalObjectMap() {
5782 return instance_type() == JS_GLOBAL_OBJECT_TYPE;
5784 bool IsGlobalObjectMap() {
5785 const InstanceType type = instance_type();
5786 return type == JS_GLOBAL_OBJECT_TYPE || type == JS_BUILTINS_OBJECT_TYPE;
5789 inline bool CanOmitMapChecks();
5791 static void AddDependentCode(Handle<Map> map,
5792 DependentCode::DependencyGroup group,
5795 bool IsMapInArrayPrototypeChain();
5797 static Handle<WeakCell> WeakCellForMap(Handle<Map> map);
5799 // Dispatched behavior.
5800 DECLARE_PRINTER(Map)
5801 DECLARE_VERIFIER(Map)
5804 void DictionaryMapVerify();
5805 void VerifyOmittedMapChecks();
5808 inline int visitor_id();
5809 inline void set_visitor_id(int visitor_id);
5811 static Handle<Map> TransitionToPrototype(Handle<Map> map,
5812 Handle<Object> prototype,
5813 PrototypeOptimizationMode mode);
5815 static const int kMaxPreAllocatedPropertyFields = 255;
5817 // Layout description.
5818 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
5819 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
5820 static const int kBitField3Offset = kInstanceAttributesOffset + kIntSize;
5821 static const int kPrototypeOffset = kBitField3Offset + kPointerSize;
5822 static const int kConstructorOrBackPointerOffset =
5823 kPrototypeOffset + kPointerSize;
5824 // When there is only one transition, it is stored directly in this field;
5825 // otherwise a transition array is used.
5826 // For prototype maps, this slot is used to store this map's PrototypeInfo
5828 static const int kTransitionsOrPrototypeInfoOffset =
5829 kConstructorOrBackPointerOffset + kPointerSize;
5830 static const int kDescriptorsOffset =
5831 kTransitionsOrPrototypeInfoOffset + kPointerSize;
5832 #if V8_DOUBLE_FIELDS_UNBOXING
5833 static const int kLayoutDecriptorOffset = kDescriptorsOffset + kPointerSize;
5834 static const int kCodeCacheOffset = kLayoutDecriptorOffset + kPointerSize;
5836 static const int kLayoutDecriptorOffset = 1; // Must not be ever accessed.
5837 static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
5839 static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
5840 static const int kWeakCellCacheOffset = kDependentCodeOffset + kPointerSize;
5841 static const int kSize = kWeakCellCacheOffset + kPointerSize;
5843 // Layout of pointer fields. Heap iteration code relies on them
5844 // being continuously allocated.
5845 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
5846 static const int kPointerFieldsEndOffset = kSize;
5848 // Byte offsets within kInstanceSizesOffset.
5849 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
5850 static const int kInObjectPropertiesByte = 1;
5851 static const int kInObjectPropertiesOffset =
5852 kInstanceSizesOffset + kInObjectPropertiesByte;
5853 // Note there is one byte available for use here.
5854 static const int kUnusedByte = 2;
5855 static const int kUnusedOffset = kInstanceSizesOffset + kUnusedByte;
5856 static const int kVisitorIdByte = 3;
5857 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
5859 // Byte offsets within kInstanceAttributesOffset attributes.
5860 #if V8_TARGET_LITTLE_ENDIAN
5861 // Order instance type and bit field together such that they can be loaded
5862 // together as a 16-bit word with instance type in the lower 8 bits regardless
5863 // of endianess. Also provide endian-independent offset to that 16-bit word.
5864 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
5865 static const int kBitFieldOffset = kInstanceAttributesOffset + 1;
5867 static const int kBitFieldOffset = kInstanceAttributesOffset + 0;
5868 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 1;
5870 static const int kInstanceTypeAndBitFieldOffset =
5871 kInstanceAttributesOffset + 0;
5872 static const int kBitField2Offset = kInstanceAttributesOffset + 2;
5873 static const int kUnusedPropertyFieldsByte = 3;
5874 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 3;
5876 STATIC_ASSERT(kInstanceTypeAndBitFieldOffset ==
5877 Internals::kMapInstanceTypeAndBitFieldOffset);
5879 // Bit positions for bit field.
5880 static const int kHasNonInstancePrototype = 0;
5881 static const int kIsHiddenPrototype = 1;
5882 static const int kHasNamedInterceptor = 2;
5883 static const int kHasIndexedInterceptor = 3;
5884 static const int kIsUndetectable = 4;
5885 static const int kIsObserved = 5;
5886 static const int kIsAccessCheckNeeded = 6;
5887 class FunctionWithPrototype: public BitField<bool, 7, 1> {};
5889 // Bit positions for bit field 2
5890 static const int kIsExtensible = 0;
5891 static const int kStringWrapperSafeForDefaultValueOf = 1;
5892 class IsPrototypeMapBits : public BitField<bool, 2, 1> {};
5893 class ElementsKindBits: public BitField<ElementsKind, 3, 5> {};
5895 // Derived values from bit field 2
5896 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
5897 (FAST_ELEMENTS + 1) << Map::ElementsKindBits::kShift) - 1;
5898 static const int8_t kMaximumBitField2FastSmiElementValue =
5899 static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
5900 Map::ElementsKindBits::kShift) - 1;
5901 static const int8_t kMaximumBitField2FastHoleyElementValue =
5902 static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
5903 Map::ElementsKindBits::kShift) - 1;
5904 static const int8_t kMaximumBitField2FastHoleySmiElementValue =
5905 static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
5906 Map::ElementsKindBits::kShift) - 1;
5908 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
5909 kPointerFieldsEndOffset,
5910 kSize> BodyDescriptor;
5912 // Compares this map to another to see if they describe equivalent objects.
5913 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
5914 // it had exactly zero inobject properties.
5915 // The "shared" flags of both this map and |other| are ignored.
5916 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
5918 // Returns true if given field is unboxed double.
5919 inline bool IsUnboxedDoubleField(FieldIndex index);
5922 static void TraceTransition(const char* what, Map* from, Map* to, Name* name);
5923 static void TraceAllTransitions(Map* map);
5926 static inline Handle<Map> CopyInstallDescriptorsForTesting(
5927 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5928 Handle<LayoutDescriptor> layout_descriptor);
5931 static void ConnectTransition(Handle<Map> parent, Handle<Map> child,
5932 Handle<Name> name, SimpleTransitionFlag flag);
5934 bool EquivalentToForTransition(Map* other);
5935 static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
5936 static Handle<Map> ShareDescriptor(Handle<Map> map,
5937 Handle<DescriptorArray> descriptors,
5938 Descriptor* descriptor);
5939 static Handle<Map> CopyInstallDescriptors(
5940 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5941 Handle<LayoutDescriptor> layout_descriptor);
5942 static Handle<Map> CopyAddDescriptor(Handle<Map> map,
5943 Descriptor* descriptor,
5944 TransitionFlag flag);
5945 static Handle<Map> CopyReplaceDescriptors(
5946 Handle<Map> map, Handle<DescriptorArray> descriptors,
5947 Handle<LayoutDescriptor> layout_descriptor, TransitionFlag flag,
5948 MaybeHandle<Name> maybe_name, const char* reason,
5949 SimpleTransitionFlag simple_flag);
5951 static Handle<Map> CopyReplaceDescriptor(Handle<Map> map,
5952 Handle<DescriptorArray> descriptors,
5953 Descriptor* descriptor,
5955 TransitionFlag flag);
5956 static MUST_USE_RESULT MaybeHandle<Map> TryReconfigureExistingProperty(
5957 Handle<Map> map, int descriptor, PropertyKind kind,
5958 PropertyAttributes attributes, const char** reason);
5960 static Handle<Map> CopyNormalized(Handle<Map> map,
5961 PropertyNormalizationMode mode);
5963 // Fires when the layout of an object with a leaf map changes.
5964 // This includes adding transitions to the leaf map or changing
5965 // the descriptor array.
5966 inline void NotifyLeafMapLayoutChange();
5968 void DeprecateTransitionTree();
5969 bool DeprecateTarget(PropertyKind kind, Name* key,
5970 PropertyAttributes attributes,
5971 DescriptorArray* new_descriptors,
5972 LayoutDescriptor* new_layout_descriptor);
5974 Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
5976 // Update field type of the given descriptor to new representation and new
5977 // type. The type must be prepared for storing in descriptor array:
5978 // it must be either a simple type or a map wrapped in a weak cell.
5979 void UpdateFieldType(int descriptor_number, Handle<Name> name,
5980 Representation new_representation,
5981 Handle<Object> new_wrapped_type);
5983 void PrintReconfiguration(FILE* file, int modify_index, PropertyKind kind,
5984 PropertyAttributes attributes);
5985 void PrintGeneralization(FILE* file,
5990 bool constant_to_field,
5991 Representation old_representation,
5992 Representation new_representation,
5993 HeapType* old_field_type,
5994 HeapType* new_field_type);
5996 static const int kFastPropertiesSoftLimit = 12;
5997 static const int kMaxFastProperties = 128;
5999 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
6003 // An abstract superclass, a marker class really, for simple structure classes.
6004 // It doesn't carry much functionality but allows struct classes to be
6005 // identified in the type system.
6006 class Struct: public HeapObject {
6008 inline void InitializeBody(int object_size);
6009 DECLARE_CAST(Struct)
6013 // A simple one-element struct, useful where smis need to be boxed.
6014 class Box : public Struct {
6016 // [value]: the boxed contents.
6017 DECL_ACCESSORS(value, Object)
6021 // Dispatched behavior.
6022 DECLARE_PRINTER(Box)
6023 DECLARE_VERIFIER(Box)
6025 static const int kValueOffset = HeapObject::kHeaderSize;
6026 static const int kSize = kValueOffset + kPointerSize;
6029 DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
6033 // Container for metadata stored on each prototype map.
6034 class PrototypeInfo : public Struct {
6036 // [prototype_users]: WeakFixedArray containing maps using this prototype,
6037 // or Smi(0) if uninitialized.
6038 DECL_ACCESSORS(prototype_users, Object)
6039 // [validity_cell]: Cell containing the validity bit for prototype chains
6040 // going through this object, or Smi(0) if uninitialized.
6041 DECL_ACCESSORS(validity_cell, Object)
6042 // [constructor_name]: User-friendly name of the original constructor.
6043 DECL_ACCESSORS(constructor_name, Object)
6045 DECLARE_CAST(PrototypeInfo)
6047 // Dispatched behavior.
6048 DECLARE_PRINTER(PrototypeInfo)
6049 DECLARE_VERIFIER(PrototypeInfo)
6051 static const int kPrototypeUsersOffset = HeapObject::kHeaderSize;
6052 static const int kValidityCellOffset = kPrototypeUsersOffset + kPointerSize;
6053 static const int kConstructorNameOffset = kValidityCellOffset + kPointerSize;
6054 static const int kSize = kConstructorNameOffset + kPointerSize;
6057 DISALLOW_IMPLICIT_CONSTRUCTORS(PrototypeInfo);
6061 // Script describes a script which has been added to the VM.
6062 class Script: public Struct {
6071 // Script compilation types.
6072 enum CompilationType {
6073 COMPILATION_TYPE_HOST = 0,
6074 COMPILATION_TYPE_EVAL = 1
6077 // Script compilation state.
6078 enum CompilationState {
6079 COMPILATION_STATE_INITIAL = 0,
6080 COMPILATION_STATE_COMPILED = 1
6083 // [source]: the script source.
6084 DECL_ACCESSORS(source, Object)
6086 // [name]: the script name.
6087 DECL_ACCESSORS(name, Object)
6089 // [id]: the script id.
6090 DECL_ACCESSORS(id, Smi)
6092 // [line_offset]: script line offset in resource from where it was extracted.
6093 DECL_ACCESSORS(line_offset, Smi)
6095 // [column_offset]: script column offset in resource from where it was
6097 DECL_ACCESSORS(column_offset, Smi)
6099 // [context_data]: context data for the context this script was compiled in.
6100 DECL_ACCESSORS(context_data, Object)
6102 // [wrapper]: the wrapper cache. This is either undefined or a WeakCell.
6103 DECL_ACCESSORS(wrapper, HeapObject)
6105 // [type]: the script type.
6106 DECL_ACCESSORS(type, Smi)
6108 // [line_ends]: FixedArray of line ends positions.
6109 DECL_ACCESSORS(line_ends, Object)
6111 // [eval_from_shared]: for eval scripts the shared funcion info for the
6112 // function from which eval was called.
6113 DECL_ACCESSORS(eval_from_shared, Object)
6115 // [eval_from_instructions_offset]: the instruction offset in the code for the
6116 // function from which eval was called where eval was called.
6117 DECL_ACCESSORS(eval_from_instructions_offset, Smi)
6119 // [shared_function_infos]: weak fixed array containing all shared
6120 // function infos created from this script.
6121 DECL_ACCESSORS(shared_function_infos, Object)
6123 // [flags]: Holds an exciting bitfield.
6124 DECL_ACCESSORS(flags, Smi)
6126 // [source_url]: sourceURL from magic comment
6127 DECL_ACCESSORS(source_url, Object)
6129 // [source_url]: sourceMappingURL magic comment
6130 DECL_ACCESSORS(source_mapping_url, Object)
6132 // [compilation_type]: how the the script was compiled. Encoded in the
6134 inline CompilationType compilation_type();
6135 inline void set_compilation_type(CompilationType type);
6137 // [compilation_state]: determines whether the script has already been
6138 // compiled. Encoded in the 'flags' field.
6139 inline CompilationState compilation_state();
6140 inline void set_compilation_state(CompilationState state);
6142 // [origin_options]: optional attributes set by the embedder via ScriptOrigin,
6143 // and used by the embedder to make decisions about the script. V8 just passes
6144 // this through. Encoded in the 'flags' field.
6145 inline v8::ScriptOriginOptions origin_options();
6146 inline void set_origin_options(ScriptOriginOptions origin_options);
6148 DECLARE_CAST(Script)
6150 // If script source is an external string, check that the underlying
6151 // resource is accessible. Otherwise, always return true.
6152 inline bool HasValidSource();
6154 // Convert code position into column number.
6155 static int GetColumnNumber(Handle<Script> script, int code_pos);
6157 // Convert code position into (zero-based) line number.
6158 // The non-handlified version does not allocate, but may be much slower.
6159 static int GetLineNumber(Handle<Script> script, int code_pos);
6160 int GetLineNumber(int code_pos);
6162 static Handle<Object> GetNameOrSourceURL(Handle<Script> script);
6164 // Init line_ends array with code positions of line ends inside script source.
6165 static void InitLineEnds(Handle<Script> script);
6167 // Get the JS object wrapping the given script; create it if none exists.
6168 static Handle<JSObject> GetWrapper(Handle<Script> script);
6170 // Look through the list of existing shared function infos to find one
6171 // that matches the function literal. Return empty handle if not found.
6172 MaybeHandle<SharedFunctionInfo> FindSharedFunctionInfo(FunctionLiteral* fun);
6174 // Dispatched behavior.
6175 DECLARE_PRINTER(Script)
6176 DECLARE_VERIFIER(Script)
6178 static const int kSourceOffset = HeapObject::kHeaderSize;
6179 static const int kNameOffset = kSourceOffset + kPointerSize;
6180 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
6181 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
6182 static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
6183 static const int kWrapperOffset = kContextOffset + kPointerSize;
6184 static const int kTypeOffset = kWrapperOffset + kPointerSize;
6185 static const int kLineEndsOffset = kTypeOffset + kPointerSize;
6186 static const int kIdOffset = kLineEndsOffset + kPointerSize;
6187 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
6188 static const int kEvalFrominstructionsOffsetOffset =
6189 kEvalFromSharedOffset + kPointerSize;
6190 static const int kSharedFunctionInfosOffset =
6191 kEvalFrominstructionsOffsetOffset + kPointerSize;
6192 static const int kFlagsOffset = kSharedFunctionInfosOffset + kPointerSize;
6193 static const int kSourceUrlOffset = kFlagsOffset + kPointerSize;
6194 static const int kSourceMappingUrlOffset = kSourceUrlOffset + kPointerSize;
6195 static const int kSize = kSourceMappingUrlOffset + kPointerSize;
6198 int GetLineNumberWithArray(int code_pos);
6200 // Bit positions in the flags field.
6201 static const int kCompilationTypeBit = 0;
6202 static const int kCompilationStateBit = 1;
6203 static const int kOriginOptionsShift = 2;
6204 static const int kOriginOptionsSize = 3;
6205 static const int kOriginOptionsMask = ((1 << kOriginOptionsSize) - 1)
6206 << kOriginOptionsShift;
6208 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6212 // List of builtin functions we want to identify to improve code
6215 // Each entry has a name of a global object property holding an object
6216 // optionally followed by ".prototype", a name of a builtin function
6217 // on the object (the one the id is set for), and a label.
6219 // Installation of ids for the selected builtin functions is handled
6220 // by the bootstrapper.
6221 #define FUNCTIONS_WITH_ID_LIST(V) \
6222 V(Array.prototype, indexOf, ArrayIndexOf) \
6223 V(Array.prototype, lastIndexOf, ArrayLastIndexOf) \
6224 V(Array.prototype, push, ArrayPush) \
6225 V(Array.prototype, pop, ArrayPop) \
6226 V(Array.prototype, shift, ArrayShift) \
6227 V(Function.prototype, apply, FunctionApply) \
6228 V(Function.prototype, call, FunctionCall) \
6229 V(String.prototype, charCodeAt, StringCharCodeAt) \
6230 V(String.prototype, charAt, StringCharAt) \
6231 V(String, fromCharCode, StringFromCharCode) \
6232 V(Math, random, MathRandom) \
6233 V(Math, floor, MathFloor) \
6234 V(Math, round, MathRound) \
6235 V(Math, ceil, MathCeil) \
6236 V(Math, abs, MathAbs) \
6237 V(Math, log, MathLog) \
6238 V(Math, exp, MathExp) \
6239 V(Math, sqrt, MathSqrt) \
6240 V(Math, pow, MathPow) \
6241 V(Math, max, MathMax) \
6242 V(Math, min, MathMin) \
6243 V(Math, cos, MathCos) \
6244 V(Math, sin, MathSin) \
6245 V(Math, tan, MathTan) \
6246 V(Math, acos, MathAcos) \
6247 V(Math, asin, MathAsin) \
6248 V(Math, atan, MathAtan) \
6249 V(Math, atan2, MathAtan2) \
6250 V(Math, imul, MathImul) \
6251 V(Math, clz32, MathClz32) \
6252 V(Math, fround, MathFround)
6254 #define ATOMIC_FUNCTIONS_WITH_ID_LIST(V) \
6255 V(Atomics, load, AtomicsLoad) \
6256 V(Atomics, store, AtomicsStore)
6258 enum BuiltinFunctionId {
6260 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
6262 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6263 ATOMIC_FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6264 #undef DECLARE_FUNCTION_ID
6265 // Fake id for a special case of Math.pow. Note, it continues the
6266 // list of math functions.
6271 // Result of searching in an optimized code map of a SharedFunctionInfo. Note
6272 // that both {code} and {literals} can be NULL to pass search result status.
6273 struct CodeAndLiterals {
6274 Code* code; // Cached optimized code.
6275 FixedArray* literals; // Cached literals array.
6279 // SharedFunctionInfo describes the JSFunction information that can be
6280 // shared by multiple instances of the function.
6281 class SharedFunctionInfo: public HeapObject {
6283 // [name]: Function name.
6284 DECL_ACCESSORS(name, Object)
6286 // [code]: Function code.
6287 DECL_ACCESSORS(code, Code)
6288 inline void ReplaceCode(Code* code);
6290 // [optimized_code_map]: Map from native context to optimized code
6291 // and a shared literals array or Smi(0) if none.
6292 DECL_ACCESSORS(optimized_code_map, Object)
6294 // Returns entry from optimized code map for specified context and OSR entry.
6295 // Note that {code == nullptr} indicates no matching entry has been found,
6296 // whereas {literals == nullptr} indicates the code is context-independent.
6297 CodeAndLiterals SearchOptimizedCodeMap(Context* native_context,
6298 BailoutId osr_ast_id);
6300 // Clear optimized code map.
6301 void ClearOptimizedCodeMap();
6303 // Removed a specific optimized code object from the optimized code map.
6304 void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
6306 // Trims the optimized code map after entries have been removed.
6307 void TrimOptimizedCodeMap(int shrink_by);
6309 // Add a new entry to the optimized code map for context-independent code.
6310 static void AddSharedCodeToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6313 // Add a new entry to the optimized code map for context-dependent code.
6314 static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6315 Handle<Context> native_context,
6317 Handle<FixedArray> literals,
6318 BailoutId osr_ast_id);
6320 // Set up the link between shared function info and the script. The shared
6321 // function info is added to the list on the script.
6322 static void SetScript(Handle<SharedFunctionInfo> shared,
6323 Handle<Object> script_object);
6325 // Layout description of the optimized code map.
6326 static const int kNextMapIndex = 0;
6327 static const int kSharedCodeIndex = 1;
6328 static const int kEntriesStart = 2;
6329 static const int kContextOffset = 0;
6330 static const int kCachedCodeOffset = 1;
6331 static const int kLiteralsOffset = 2;
6332 static const int kOsrAstIdOffset = 3;
6333 static const int kEntryLength = 4;
6334 static const int kInitialLength = kEntriesStart + kEntryLength;
6336 // [scope_info]: Scope info.
6337 DECL_ACCESSORS(scope_info, ScopeInfo)
6339 // [construct stub]: Code stub for constructing instances of this function.
6340 DECL_ACCESSORS(construct_stub, Code)
6342 // Returns if this function has been compiled to native code yet.
6343 inline bool is_compiled();
6345 // [length]: The function length - usually the number of declared parameters.
6346 // Use up to 2^30 parameters.
6347 inline int length() const;
6348 inline void set_length(int value);
6350 // [internal formal parameter count]: The declared number of parameters.
6351 // For subclass constructors, also includes new.target.
6352 // The size of function's frame is internal_formal_parameter_count + 1.
6353 inline int internal_formal_parameter_count() const;
6354 inline void set_internal_formal_parameter_count(int value);
6356 // Set the formal parameter count so the function code will be
6357 // called without using argument adaptor frames.
6358 inline void DontAdaptArguments();
6360 // [expected_nof_properties]: Expected number of properties for the function.
6361 inline int expected_nof_properties() const;
6362 inline void set_expected_nof_properties(int value);
6364 // [feedback_vector] - accumulates ast node feedback from full-codegen and
6365 // (increasingly) from crankshafted code where sufficient feedback isn't
6367 DECL_ACCESSORS(feedback_vector, TypeFeedbackVector)
6369 // Unconditionally clear the type feedback vector (including vector ICs).
6370 void ClearTypeFeedbackInfo();
6372 // Clear the type feedback vector with a more subtle policy at GC time.
6373 void ClearTypeFeedbackInfoAtGCTime();
6376 // [unique_id] - For --trace-maps purposes, an identifier that's persistent
6377 // even if the GC moves this SharedFunctionInfo.
6378 inline int unique_id() const;
6379 inline void set_unique_id(int value);
6382 // [instance class name]: class name for instances.
6383 DECL_ACCESSORS(instance_class_name, Object)
6385 // [function data]: This field holds some additional data for function.
6386 // Currently it has one of:
6387 // - a FunctionTemplateInfo to make benefit the API [IsApiFunction()].
6388 // - a Smi identifying a builtin function [HasBuiltinFunctionId()].
6389 // - a BytecodeArray for the interpreter [HasBytecodeArray()].
6390 // In the long run we don't want all functions to have this field but
6391 // we can fix that when we have a better model for storing hidden data
6393 DECL_ACCESSORS(function_data, Object)
6395 inline bool IsApiFunction();
6396 inline FunctionTemplateInfo* get_api_func_data();
6397 inline bool HasBuiltinFunctionId();
6398 inline BuiltinFunctionId builtin_function_id();
6399 inline bool HasBytecodeArray();
6400 inline BytecodeArray* bytecode_array();
6402 // [script info]: Script from which the function originates.
6403 DECL_ACCESSORS(script, Object)
6405 // [num_literals]: Number of literals used by this function.
6406 inline int num_literals() const;
6407 inline void set_num_literals(int value);
6409 // [start_position_and_type]: Field used to store both the source code
6410 // position, whether or not the function is a function expression,
6411 // and whether or not the function is a toplevel function. The two
6412 // least significants bit indicates whether the function is an
6413 // expression and the rest contains the source code position.
6414 inline int start_position_and_type() const;
6415 inline void set_start_position_and_type(int value);
6417 // The function is subject to debugging if a debug info is attached.
6418 inline bool HasDebugInfo();
6419 inline DebugInfo* GetDebugInfo();
6421 // A function has debug code if the compiled code has debug break slots.
6422 inline bool HasDebugCode();
6424 // [debug info]: Debug information.
6425 DECL_ACCESSORS(debug_info, Object)
6427 // [inferred name]: Name inferred from variable or property
6428 // assignment of this function. Used to facilitate debugging and
6429 // profiling of JavaScript code written in OO style, where almost
6430 // all functions are anonymous but are assigned to object
6432 DECL_ACCESSORS(inferred_name, String)
6434 // The function's name if it is non-empty, otherwise the inferred name.
6435 String* DebugName();
6437 // Position of the 'function' token in the script source.
6438 inline int function_token_position() const;
6439 inline void set_function_token_position(int function_token_position);
6441 // Position of this function in the script source.
6442 inline int start_position() const;
6443 inline void set_start_position(int start_position);
6445 // End position of this function in the script source.
6446 inline int end_position() const;
6447 inline void set_end_position(int end_position);
6449 // Is this function a function expression in the source code.
6450 DECL_BOOLEAN_ACCESSORS(is_expression)
6452 // Is this function a top-level function (scripts, evals).
6453 DECL_BOOLEAN_ACCESSORS(is_toplevel)
6455 // Bit field containing various information collected by the compiler to
6456 // drive optimization.
6457 inline int compiler_hints() const;
6458 inline void set_compiler_hints(int value);
6460 inline int ast_node_count() const;
6461 inline void set_ast_node_count(int count);
6463 inline int profiler_ticks() const;
6464 inline void set_profiler_ticks(int ticks);
6466 // Inline cache age is used to infer whether the function survived a context
6467 // disposal or not. In the former case we reset the opt_count.
6468 inline int ic_age();
6469 inline void set_ic_age(int age);
6471 // Indicates if this function can be lazy compiled.
6472 // This is used to determine if we can safely flush code from a function
6473 // when doing GC if we expect that the function will no longer be used.
6474 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
6476 // Indicates if this function can be lazy compiled without a context.
6477 // This is used to determine if we can force compilation without reaching
6478 // the function through program execution but through other means (e.g. heap
6479 // iteration by the debugger).
6480 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
6482 // Indicates whether optimizations have been disabled for this
6483 // shared function info. If a function is repeatedly optimized or if
6484 // we cannot optimize the function we disable optimization to avoid
6485 // spending time attempting to optimize it again.
6486 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
6488 // Indicates the language mode.
6489 inline LanguageMode language_mode();
6490 inline void set_language_mode(LanguageMode language_mode);
6492 // False if the function definitely does not allocate an arguments object.
6493 DECL_BOOLEAN_ACCESSORS(uses_arguments)
6495 // Indicates that this function uses a super property (or an eval that may
6496 // use a super property).
6497 // This is needed to set up the [[HomeObject]] on the function instance.
6498 DECL_BOOLEAN_ACCESSORS(needs_home_object)
6500 // True if the function has any duplicated parameter names.
6501 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
6503 // Indicates whether the function is a native function.
6504 // These needs special treatment in .call and .apply since
6505 // null passed as the receiver should not be translated to the
6507 DECL_BOOLEAN_ACCESSORS(native)
6509 // Indicate that this function should always be inlined in optimized code.
6510 DECL_BOOLEAN_ACCESSORS(force_inline)
6512 // Indicates that the function was created by the Function function.
6513 // Though it's anonymous, toString should treat it as if it had the name
6514 // "anonymous". We don't set the name itself so that the system does not
6515 // see a binding for it.
6516 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
6518 // Indicates whether the function is a bound function created using
6519 // the bind function.
6520 DECL_BOOLEAN_ACCESSORS(bound)
6522 // Indicates that the function is anonymous (the name field can be set
6523 // through the API, which does not change this flag).
6524 DECL_BOOLEAN_ACCESSORS(is_anonymous)
6526 // Is this a function or top-level/eval code.
6527 DECL_BOOLEAN_ACCESSORS(is_function)
6529 // Indicates that code for this function cannot be compiled with Crankshaft.
6530 DECL_BOOLEAN_ACCESSORS(dont_crankshaft)
6532 // Indicates that code for this function cannot be flushed.
6533 DECL_BOOLEAN_ACCESSORS(dont_flush)
6535 // Indicates that this function is a generator.
6536 DECL_BOOLEAN_ACCESSORS(is_generator)
6538 // Indicates that this function is an arrow function.
6539 DECL_BOOLEAN_ACCESSORS(is_arrow)
6541 // Indicates that this function is a concise method.
6542 DECL_BOOLEAN_ACCESSORS(is_concise_method)
6544 // Indicates that this function is an accessor (getter or setter).
6545 DECL_BOOLEAN_ACCESSORS(is_accessor_function)
6547 // Indicates that this function is a default constructor.
6548 DECL_BOOLEAN_ACCESSORS(is_default_constructor)
6550 // Indicates that this function is an asm function.
6551 DECL_BOOLEAN_ACCESSORS(asm_function)
6553 // Indicates that the the shared function info is deserialized from cache.
6554 DECL_BOOLEAN_ACCESSORS(deserialized)
6556 // Indicates that the the shared function info has never been compiled before.
6557 DECL_BOOLEAN_ACCESSORS(never_compiled)
6559 inline FunctionKind kind();
6560 inline void set_kind(FunctionKind kind);
6562 // Indicates whether or not the code in the shared function support
6564 inline bool has_deoptimization_support();
6566 // Enable deoptimization support through recompiled code.
6567 void EnableDeoptimizationSupport(Code* recompiled);
6569 // Disable (further) attempted optimization of all functions sharing this
6570 // shared function info.
6571 void DisableOptimization(BailoutReason reason);
6573 inline BailoutReason disable_optimization_reason();
6575 // Lookup the bailout ID and DCHECK that it exists in the non-optimized
6576 // code, returns whether it asserted (i.e., always true if assertions are
6578 bool VerifyBailoutId(BailoutId id);
6580 // [source code]: Source code for the function.
6581 bool HasSourceCode() const;
6582 Handle<Object> GetSourceCode();
6584 // Number of times the function was optimized.
6585 inline int opt_count();
6586 inline void set_opt_count(int opt_count);
6588 // Number of times the function was deoptimized.
6589 inline void set_deopt_count(int value);
6590 inline int deopt_count();
6591 inline void increment_deopt_count();
6593 // Number of time we tried to re-enable optimization after it
6594 // was disabled due to high number of deoptimizations.
6595 inline void set_opt_reenable_tries(int value);
6596 inline int opt_reenable_tries();
6598 inline void TryReenableOptimization();
6600 // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
6601 inline void set_counters(int value);
6602 inline int counters() const;
6604 // Stores opt_count and bailout_reason as bit-fields.
6605 inline void set_opt_count_and_bailout_reason(int value);
6606 inline int opt_count_and_bailout_reason() const;
6608 void set_disable_optimization_reason(BailoutReason reason) {
6609 set_opt_count_and_bailout_reason(
6610 DisabledOptimizationReasonBits::update(opt_count_and_bailout_reason(),
6614 // Tells whether this function should be subject to debugging.
6615 inline bool IsSubjectToDebugging();
6617 // Check whether or not this function is inlineable.
6618 bool IsInlineable();
6620 // Source size of this function.
6623 // Calculate the instance size.
6624 int CalculateInstanceSize();
6626 // Calculate the number of in-object properties.
6627 int CalculateInObjectProperties();
6629 inline bool is_simple_parameter_list();
6631 // Initialize a SharedFunctionInfo from a parsed function literal.
6632 static void InitFromFunctionLiteral(Handle<SharedFunctionInfo> shared_info,
6633 FunctionLiteral* lit);
6635 // Dispatched behavior.
6636 DECLARE_PRINTER(SharedFunctionInfo)
6637 DECLARE_VERIFIER(SharedFunctionInfo)
6639 void ResetForNewContext(int new_ic_age);
6641 DECLARE_CAST(SharedFunctionInfo)
6644 static const int kDontAdaptArgumentsSentinel = -1;
6646 // Layout description.
6648 static const int kNameOffset = HeapObject::kHeaderSize;
6649 static const int kCodeOffset = kNameOffset + kPointerSize;
6650 static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
6651 static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
6652 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
6653 static const int kInstanceClassNameOffset =
6654 kConstructStubOffset + kPointerSize;
6655 static const int kFunctionDataOffset =
6656 kInstanceClassNameOffset + kPointerSize;
6657 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
6658 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
6659 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
6660 static const int kFeedbackVectorOffset =
6661 kInferredNameOffset + kPointerSize;
6663 static const int kUniqueIdOffset = kFeedbackVectorOffset + kPointerSize;
6664 static const int kLastPointerFieldOffset = kUniqueIdOffset;
6666 // Just to not break the postmortrem support with conditional offsets
6667 static const int kUniqueIdOffset = kFeedbackVectorOffset;
6668 static const int kLastPointerFieldOffset = kFeedbackVectorOffset;
6671 #if V8_HOST_ARCH_32_BIT
6673 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6674 static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
6675 static const int kExpectedNofPropertiesOffset =
6676 kFormalParameterCountOffset + kPointerSize;
6677 static const int kNumLiteralsOffset =
6678 kExpectedNofPropertiesOffset + kPointerSize;
6679 static const int kStartPositionAndTypeOffset =
6680 kNumLiteralsOffset + kPointerSize;
6681 static const int kEndPositionOffset =
6682 kStartPositionAndTypeOffset + kPointerSize;
6683 static const int kFunctionTokenPositionOffset =
6684 kEndPositionOffset + kPointerSize;
6685 static const int kCompilerHintsOffset =
6686 kFunctionTokenPositionOffset + kPointerSize;
6687 static const int kOptCountAndBailoutReasonOffset =
6688 kCompilerHintsOffset + kPointerSize;
6689 static const int kCountersOffset =
6690 kOptCountAndBailoutReasonOffset + kPointerSize;
6691 static const int kAstNodeCountOffset =
6692 kCountersOffset + kPointerSize;
6693 static const int kProfilerTicksOffset =
6694 kAstNodeCountOffset + kPointerSize;
6697 static const int kSize = kProfilerTicksOffset + kPointerSize;
6699 // The only reason to use smi fields instead of int fields
6700 // is to allow iteration without maps decoding during
6701 // garbage collections.
6702 // To avoid wasting space on 64-bit architectures we use
6703 // the following trick: we group integer fields into pairs
6704 // The least significant integer in each pair is shifted left by 1.
6705 // By doing this we guarantee that LSB of each kPointerSize aligned
6706 // word is not set and thus this word cannot be treated as pointer
6707 // to HeapObject during old space traversal.
6708 #if V8_TARGET_LITTLE_ENDIAN
6709 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6710 static const int kFormalParameterCountOffset =
6711 kLengthOffset + kIntSize;
6713 static const int kExpectedNofPropertiesOffset =
6714 kFormalParameterCountOffset + kIntSize;
6715 static const int kNumLiteralsOffset =
6716 kExpectedNofPropertiesOffset + kIntSize;
6718 static const int kEndPositionOffset =
6719 kNumLiteralsOffset + kIntSize;
6720 static const int kStartPositionAndTypeOffset =
6721 kEndPositionOffset + kIntSize;
6723 static const int kFunctionTokenPositionOffset =
6724 kStartPositionAndTypeOffset + kIntSize;
6725 static const int kCompilerHintsOffset =
6726 kFunctionTokenPositionOffset + kIntSize;
6728 static const int kOptCountAndBailoutReasonOffset =
6729 kCompilerHintsOffset + kIntSize;
6730 static const int kCountersOffset =
6731 kOptCountAndBailoutReasonOffset + kIntSize;
6733 static const int kAstNodeCountOffset =
6734 kCountersOffset + kIntSize;
6735 static const int kProfilerTicksOffset =
6736 kAstNodeCountOffset + kIntSize;
6739 static const int kSize = kProfilerTicksOffset + kIntSize;
6741 #elif V8_TARGET_BIG_ENDIAN
6742 static const int kFormalParameterCountOffset =
6743 kLastPointerFieldOffset + kPointerSize;
6744 static const int kLengthOffset = kFormalParameterCountOffset + kIntSize;
6746 static const int kNumLiteralsOffset = kLengthOffset + kIntSize;
6747 static const int kExpectedNofPropertiesOffset = kNumLiteralsOffset + kIntSize;
6749 static const int kStartPositionAndTypeOffset =
6750 kExpectedNofPropertiesOffset + kIntSize;
6751 static const int kEndPositionOffset = kStartPositionAndTypeOffset + kIntSize;
6753 static const int kCompilerHintsOffset = kEndPositionOffset + kIntSize;
6754 static const int kFunctionTokenPositionOffset =
6755 kCompilerHintsOffset + kIntSize;
6757 static const int kCountersOffset = kFunctionTokenPositionOffset + kIntSize;
6758 static const int kOptCountAndBailoutReasonOffset = kCountersOffset + kIntSize;
6760 static const int kProfilerTicksOffset =
6761 kOptCountAndBailoutReasonOffset + kIntSize;
6762 static const int kAstNodeCountOffset = kProfilerTicksOffset + kIntSize;
6765 static const int kSize = kAstNodeCountOffset + kIntSize;
6768 #error Unknown byte ordering
6769 #endif // Big endian
6773 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
6775 typedef FixedBodyDescriptor<kNameOffset,
6776 kLastPointerFieldOffset + kPointerSize,
6777 kSize> BodyDescriptor;
6779 // Bit positions in start_position_and_type.
6780 // The source code start position is in the 30 most significant bits of
6781 // the start_position_and_type field.
6782 static const int kIsExpressionBit = 0;
6783 static const int kIsTopLevelBit = 1;
6784 static const int kStartPositionShift = 2;
6785 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
6787 // Bit positions in compiler_hints.
6788 enum CompilerHints {
6789 kAllowLazyCompilation,
6790 kAllowLazyCompilationWithoutContext,
6791 kOptimizationDisabled,
6792 kStrictModeFunction,
6793 kStrongModeFunction,
6796 kHasDuplicateParameters,
6801 kNameShouldPrintAsAnonymous,
6808 kIsAccessorFunction,
6809 kIsDefaultConstructor,
6810 kIsSubclassConstructor,
6816 kCompilerHintsCount // Pseudo entry
6818 // Add hints for other modes when they're added.
6819 STATIC_ASSERT(LANGUAGE_END == 3);
6821 class FunctionKindBits : public BitField<FunctionKind, kIsArrow, 8> {};
6823 class DeoptCountBits : public BitField<int, 0, 4> {};
6824 class OptReenableTriesBits : public BitField<int, 4, 18> {};
6825 class ICAgeBits : public BitField<int, 22, 8> {};
6827 class OptCountBits : public BitField<int, 0, 22> {};
6828 class DisabledOptimizationReasonBits : public BitField<int, 22, 8> {};
6831 #if V8_HOST_ARCH_32_BIT
6832 // On 32 bit platforms, compiler hints is a smi.
6833 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
6834 static const int kCompilerHintsSize = kPointerSize;
6836 // On 64 bit platforms, compiler hints is not a smi, see comment above.
6837 static const int kCompilerHintsSmiTagSize = 0;
6838 static const int kCompilerHintsSize = kIntSize;
6841 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
6842 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
6845 // Constants for optimizing codegen for strict mode function and
6847 // Allows to use byte-width instructions.
6848 static const int kStrictModeBitWithinByte =
6849 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6850 static const int kStrongModeBitWithinByte =
6851 (kStrongModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6853 static const int kNativeBitWithinByte =
6854 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
6856 #if defined(V8_TARGET_LITTLE_ENDIAN)
6857 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6858 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6859 static const int kStrongModeByteOffset =
6860 kCompilerHintsOffset +
6861 (kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6862 static const int kNativeByteOffset = kCompilerHintsOffset +
6863 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
6864 #elif defined(V8_TARGET_BIG_ENDIAN)
6865 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6866 (kCompilerHintsSize - 1) -
6867 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6868 static const int kStrongModeByteOffset =
6869 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6870 ((kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6871 static const int kNativeByteOffset = kCompilerHintsOffset +
6872 (kCompilerHintsSize - 1) -
6873 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
6875 #error Unknown byte ordering
6879 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
6883 // Printing support.
6884 struct SourceCodeOf {
6885 explicit SourceCodeOf(SharedFunctionInfo* v, int max = -1)
6886 : value(v), max_length(max) {}
6887 const SharedFunctionInfo* value;
6892 std::ostream& operator<<(std::ostream& os, const SourceCodeOf& v);
6895 class JSGeneratorObject: public JSObject {
6897 // [function]: The function corresponding to this generator object.
6898 DECL_ACCESSORS(function, JSFunction)
6900 // [context]: The context of the suspended computation.
6901 DECL_ACCESSORS(context, Context)
6903 // [receiver]: The receiver of the suspended computation.
6904 DECL_ACCESSORS(receiver, Object)
6906 // [continuation]: Offset into code of continuation.
6908 // A positive offset indicates a suspended generator. The special
6909 // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
6910 // cannot be resumed.
6911 inline int continuation() const;
6912 inline void set_continuation(int continuation);
6913 inline bool is_closed();
6914 inline bool is_executing();
6915 inline bool is_suspended();
6917 // [operand_stack]: Saved operand stack.
6918 DECL_ACCESSORS(operand_stack, FixedArray)
6920 DECLARE_CAST(JSGeneratorObject)
6922 // Dispatched behavior.
6923 DECLARE_PRINTER(JSGeneratorObject)
6924 DECLARE_VERIFIER(JSGeneratorObject)
6926 // Magic sentinel values for the continuation.
6927 static const int kGeneratorExecuting = -1;
6928 static const int kGeneratorClosed = 0;
6930 // Layout description.
6931 static const int kFunctionOffset = JSObject::kHeaderSize;
6932 static const int kContextOffset = kFunctionOffset + kPointerSize;
6933 static const int kReceiverOffset = kContextOffset + kPointerSize;
6934 static const int kContinuationOffset = kReceiverOffset + kPointerSize;
6935 static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
6936 static const int kSize = kOperandStackOffset + kPointerSize;
6938 // Resume mode, for use by runtime functions.
6939 enum ResumeMode { NEXT, THROW };
6941 // Yielding from a generator returns an object with the following inobject
6942 // properties. See Context::iterator_result_map() for the map.
6943 static const int kResultValuePropertyIndex = 0;
6944 static const int kResultDonePropertyIndex = 1;
6945 static const int kResultPropertyCount = 2;
6947 static const int kResultValuePropertyOffset = JSObject::kHeaderSize;
6948 static const int kResultDonePropertyOffset =
6949 kResultValuePropertyOffset + kPointerSize;
6950 static const int kResultSize = kResultDonePropertyOffset + kPointerSize;
6953 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
6957 // Representation for module instance objects.
6958 class JSModule: public JSObject {
6960 // [context]: the context holding the module's locals, or undefined if none.
6961 DECL_ACCESSORS(context, Object)
6963 // [scope_info]: Scope info.
6964 DECL_ACCESSORS(scope_info, ScopeInfo)
6966 DECLARE_CAST(JSModule)
6968 // Dispatched behavior.
6969 DECLARE_PRINTER(JSModule)
6970 DECLARE_VERIFIER(JSModule)
6972 // Layout description.
6973 static const int kContextOffset = JSObject::kHeaderSize;
6974 static const int kScopeInfoOffset = kContextOffset + kPointerSize;
6975 static const int kSize = kScopeInfoOffset + kPointerSize;
6978 DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
6982 // JSFunction describes JavaScript functions.
6983 class JSFunction: public JSObject {
6985 // [prototype_or_initial_map]:
6986 DECL_ACCESSORS(prototype_or_initial_map, Object)
6988 // [shared]: The information about the function that
6989 // can be shared by instances.
6990 DECL_ACCESSORS(shared, SharedFunctionInfo)
6992 // [context]: The context for this function.
6993 inline Context* context();
6994 inline void set_context(Object* context);
6995 inline JSObject* global_proxy();
6997 // [code]: The generated code object for this function. Executed
6998 // when the function is invoked, e.g. foo() or new foo(). See
6999 // [[Call]] and [[Construct]] description in ECMA-262, section
7001 inline Code* code();
7002 inline void set_code(Code* code);
7003 inline void set_code_no_write_barrier(Code* code);
7004 inline void ReplaceCode(Code* code);
7006 // Tells whether this function is builtin.
7007 inline bool IsBuiltin();
7009 // Tells whether this function inlines the given shared function info.
7010 bool Inlines(SharedFunctionInfo* candidate);
7012 // Tells whether this function should be subject to debugging.
7013 inline bool IsSubjectToDebugging();
7015 // Tells whether or not the function needs arguments adaption.
7016 inline bool NeedsArgumentsAdaption();
7018 // Tells whether or not this function has been optimized.
7019 inline bool IsOptimized();
7021 // Mark this function for lazy recompilation. The function will be
7022 // recompiled the next time it is executed.
7023 void MarkForOptimization();
7024 void AttemptConcurrentOptimization();
7026 // Tells whether or not the function is already marked for lazy
7028 inline bool IsMarkedForOptimization();
7029 inline bool IsMarkedForConcurrentOptimization();
7031 // Tells whether or not the function is on the concurrent recompilation queue.
7032 inline bool IsInOptimizationQueue();
7034 // Inobject slack tracking is the way to reclaim unused inobject space.
7036 // The instance size is initially determined by adding some slack to
7037 // expected_nof_properties (to allow for a few extra properties added
7038 // after the constructor). There is no guarantee that the extra space
7039 // will not be wasted.
7041 // Here is the algorithm to reclaim the unused inobject space:
7042 // - Detect the first constructor call for this JSFunction.
7043 // When it happens enter the "in progress" state: initialize construction
7044 // counter in the initial_map.
7045 // - While the tracking is in progress create objects filled with
7046 // one_pointer_filler_map instead of undefined_value. This way they can be
7047 // resized quickly and safely.
7048 // - Once enough objects have been created compute the 'slack'
7049 // (traverse the map transition tree starting from the
7050 // initial_map and find the lowest value of unused_property_fields).
7051 // - Traverse the transition tree again and decrease the instance size
7052 // of every map. Existing objects will resize automatically (they are
7053 // filled with one_pointer_filler_map). All further allocations will
7054 // use the adjusted instance size.
7055 // - SharedFunctionInfo's expected_nof_properties left unmodified since
7056 // allocations made using different closures could actually create different
7057 // kind of objects (see prototype inheritance pattern).
7059 // Important: inobject slack tracking is not attempted during the snapshot
7062 // True if the initial_map is set and the object constructions countdown
7063 // counter is not zero.
7064 static const int kGenerousAllocationCount =
7065 Map::kSlackTrackingCounterStart - Map::kSlackTrackingCounterEnd + 1;
7066 inline bool IsInobjectSlackTrackingInProgress();
7068 // Starts the tracking.
7069 // Initializes object constructions countdown counter in the initial map.
7070 void StartInobjectSlackTracking();
7072 // Completes the tracking.
7073 void CompleteInobjectSlackTracking();
7075 // [literals_or_bindings]: Fixed array holding either
7076 // the materialized literals or the bindings of a bound function.
7078 // If the function contains object, regexp or array literals, the
7079 // literals array prefix contains the object, regexp, and array
7080 // function to be used when creating these literals. This is
7081 // necessary so that we do not dynamically lookup the object, regexp
7082 // or array functions. Performing a dynamic lookup, we might end up
7083 // using the functions from a new context that we should not have
7086 // On bound functions, the array is a (copy-on-write) fixed-array containing
7087 // the function that was bound, bound this-value and any bound
7088 // arguments. Bound functions never contain literals.
7089 DECL_ACCESSORS(literals_or_bindings, FixedArray)
7091 inline FixedArray* literals();
7092 inline void set_literals(FixedArray* literals);
7094 inline FixedArray* function_bindings();
7095 inline void set_function_bindings(FixedArray* bindings);
7097 // The initial map for an object created by this constructor.
7098 inline Map* initial_map();
7099 static void SetInitialMap(Handle<JSFunction> function, Handle<Map> map,
7100 Handle<Object> prototype);
7101 inline bool has_initial_map();
7102 static void EnsureHasInitialMap(Handle<JSFunction> function);
7104 // Get and set the prototype property on a JSFunction. If the
7105 // function has an initial map the prototype is set on the initial
7106 // map. Otherwise, the prototype is put in the initial map field
7107 // until an initial map is needed.
7108 inline bool has_prototype();
7109 inline bool has_instance_prototype();
7110 inline Object* prototype();
7111 inline Object* instance_prototype();
7112 static void SetPrototype(Handle<JSFunction> function,
7113 Handle<Object> value);
7114 static void SetInstancePrototype(Handle<JSFunction> function,
7115 Handle<Object> value);
7117 // Creates a new closure for the fucntion with the same bindings,
7118 // bound values, and prototype. An equivalent of spec operations
7119 // ``CloneMethod`` and ``CloneBoundFunction``.
7120 static Handle<JSFunction> CloneClosure(Handle<JSFunction> function);
7122 // After prototype is removed, it will not be created when accessed, and
7123 // [[Construct]] from this function will not be allowed.
7124 bool RemovePrototype();
7125 inline bool should_have_prototype();
7127 // Accessor for this function's initial map's [[class]]
7128 // property. This is primarily used by ECMA native functions. This
7129 // method sets the class_name field of this function's initial map
7130 // to a given value. It creates an initial map if this function does
7131 // not have one. Note that this method does not copy the initial map
7132 // if it has one already, but simply replaces it with the new value.
7133 // Instances created afterwards will have a map whose [[class]] is
7134 // set to 'value', but there is no guarantees on instances created
7136 void SetInstanceClassName(String* name);
7138 // Returns if this function has been compiled to native code yet.
7139 inline bool is_compiled();
7141 // Returns `false` if formal parameters include rest parameters, optional
7142 // parameters, or destructuring parameters.
7143 // TODO(caitp): make this a flag set during parsing
7144 inline bool is_simple_parameter_list();
7146 // [next_function_link]: Links functions into various lists, e.g. the list
7147 // of optimized functions hanging off the native_context. The CodeFlusher
7148 // uses this link to chain together flushing candidates. Treated weakly
7149 // by the garbage collector.
7150 DECL_ACCESSORS(next_function_link, Object)
7152 // Prints the name of the function using PrintF.
7153 void PrintName(FILE* out = stdout);
7155 DECLARE_CAST(JSFunction)
7157 // Iterates the objects, including code objects indirectly referenced
7158 // through pointers to the first instruction in the code object.
7159 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
7161 // Dispatched behavior.
7162 DECLARE_PRINTER(JSFunction)
7163 DECLARE_VERIFIER(JSFunction)
7165 // Returns the number of allocated literals.
7166 inline int NumberOfLiterals();
7168 // Used for flags such as --hydrogen-filter.
7169 bool PassesFilter(const char* raw_filter);
7171 // The function's name if it is configured, otherwise shared function info
7173 static Handle<String> GetDebugName(Handle<JSFunction> function);
7175 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
7176 // kSize) is weak and has special handling during garbage collection.
7177 static const int kCodeEntryOffset = JSObject::kHeaderSize;
7178 static const int kPrototypeOrInitialMapOffset =
7179 kCodeEntryOffset + kPointerSize;
7180 static const int kSharedFunctionInfoOffset =
7181 kPrototypeOrInitialMapOffset + kPointerSize;
7182 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
7183 static const int kLiteralsOffset = kContextOffset + kPointerSize;
7184 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
7185 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
7186 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
7188 // Layout of the bound-function binding array.
7189 static const int kBoundFunctionIndex = 0;
7190 static const int kBoundThisIndex = 1;
7191 static const int kBoundArgumentsStartIndex = 2;
7194 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7198 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7199 // and the prototype is hidden. JSGlobalProxy always delegates
7200 // property accesses to its prototype if the prototype is not null.
7202 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7204 // Accessing a JSGlobalProxy requires security check.
7206 class JSGlobalProxy : public JSObject {
7208 // [native_context]: the owner native context of this global proxy object.
7209 // It is null value if this object is not used by any context.
7210 DECL_ACCESSORS(native_context, Object)
7212 // [hash]: The hash code property (undefined if not initialized yet).
7213 DECL_ACCESSORS(hash, Object)
7215 DECLARE_CAST(JSGlobalProxy)
7217 inline bool IsDetachedFrom(GlobalObject* global) const;
7219 // Dispatched behavior.
7220 DECLARE_PRINTER(JSGlobalProxy)
7221 DECLARE_VERIFIER(JSGlobalProxy)
7223 // Layout description.
7224 static const int kNativeContextOffset = JSObject::kHeaderSize;
7225 static const int kHashOffset = kNativeContextOffset + kPointerSize;
7226 static const int kSize = kHashOffset + kPointerSize;
7229 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7233 // Common super class for JavaScript global objects and the special
7234 // builtins global objects.
7235 class GlobalObject: public JSObject {
7237 // [builtins]: the object holding the runtime routines written in JS.
7238 DECL_ACCESSORS(builtins, JSBuiltinsObject)
7240 // [native context]: the natives corresponding to this global object.
7241 DECL_ACCESSORS(native_context, Context)
7243 // [global proxy]: the global proxy object of the context
7244 DECL_ACCESSORS(global_proxy, JSObject)
7246 DECLARE_CAST(GlobalObject)
7248 static void InvalidatePropertyCell(Handle<GlobalObject> object,
7250 // Ensure that the global object has a cell for the given property name.
7251 static Handle<PropertyCell> EnsurePropertyCell(Handle<GlobalObject> global,
7254 // Layout description.
7255 static const int kBuiltinsOffset = JSObject::kHeaderSize;
7256 static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7257 static const int kGlobalProxyOffset = kNativeContextOffset + kPointerSize;
7258 static const int kHeaderSize = kGlobalProxyOffset + kPointerSize;
7261 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7265 // JavaScript global object.
7266 class JSGlobalObject: public GlobalObject {
7268 DECLARE_CAST(JSGlobalObject)
7270 inline bool IsDetached();
7272 // Dispatched behavior.
7273 DECLARE_PRINTER(JSGlobalObject)
7274 DECLARE_VERIFIER(JSGlobalObject)
7276 // Layout description.
7277 static const int kSize = GlobalObject::kHeaderSize;
7280 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7284 // Builtins global object which holds the runtime routines written in
7286 class JSBuiltinsObject: public GlobalObject {
7288 // Accessors for the runtime routines written in JavaScript.
7289 inline Object* javascript_builtin(Builtins::JavaScript id);
7290 inline void set_javascript_builtin(Builtins::JavaScript id, Object* value);
7292 DECLARE_CAST(JSBuiltinsObject)
7294 // Dispatched behavior.
7295 DECLARE_PRINTER(JSBuiltinsObject)
7296 DECLARE_VERIFIER(JSBuiltinsObject)
7298 // Layout description. The size of the builtins object includes
7299 // room for two pointers per runtime routine written in javascript
7300 // (function and code object).
7301 static const int kJSBuiltinsCount = Builtins::id_count;
7302 static const int kJSBuiltinsOffset = GlobalObject::kHeaderSize;
7303 static const int kSize =
7304 GlobalObject::kHeaderSize + (kJSBuiltinsCount * kPointerSize);
7306 static int OffsetOfFunctionWithId(Builtins::JavaScript id) {
7307 return kJSBuiltinsOffset + id * kPointerSize;
7311 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7315 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
7316 class JSValue: public JSObject {
7318 // [value]: the object being wrapped.
7319 DECL_ACCESSORS(value, Object)
7321 DECLARE_CAST(JSValue)
7323 // Dispatched behavior.
7324 DECLARE_PRINTER(JSValue)
7325 DECLARE_VERIFIER(JSValue)
7327 // Layout description.
7328 static const int kValueOffset = JSObject::kHeaderSize;
7329 static const int kSize = kValueOffset + kPointerSize;
7332 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
7338 // Representation for JS date objects.
7339 class JSDate: public JSObject {
7341 // If one component is NaN, all of them are, indicating a NaN time value.
7342 // [value]: the time value.
7343 DECL_ACCESSORS(value, Object)
7344 // [year]: caches year. Either undefined, smi, or NaN.
7345 DECL_ACCESSORS(year, Object)
7346 // [month]: caches month. Either undefined, smi, or NaN.
7347 DECL_ACCESSORS(month, Object)
7348 // [day]: caches day. Either undefined, smi, or NaN.
7349 DECL_ACCESSORS(day, Object)
7350 // [weekday]: caches day of week. Either undefined, smi, or NaN.
7351 DECL_ACCESSORS(weekday, Object)
7352 // [hour]: caches hours. Either undefined, smi, or NaN.
7353 DECL_ACCESSORS(hour, Object)
7354 // [min]: caches minutes. Either undefined, smi, or NaN.
7355 DECL_ACCESSORS(min, Object)
7356 // [sec]: caches seconds. Either undefined, smi, or NaN.
7357 DECL_ACCESSORS(sec, Object)
7358 // [cache stamp]: sample of the date cache stamp at the
7359 // moment when chached fields were cached.
7360 DECL_ACCESSORS(cache_stamp, Object)
7362 DECLARE_CAST(JSDate)
7364 // Returns the date field with the specified index.
7365 // See FieldIndex for the list of date fields.
7366 static Object* GetField(Object* date, Smi* index);
7368 void SetValue(Object* value, bool is_value_nan);
7371 // Dispatched behavior.
7372 DECLARE_PRINTER(JSDate)
7373 DECLARE_VERIFIER(JSDate)
7375 // The order is important. It must be kept in sync with date macros
7386 kFirstUncachedField,
7387 kMillisecond = kFirstUncachedField,
7391 kYearUTC = kFirstUTCField,
7404 // Layout description.
7405 static const int kValueOffset = JSObject::kHeaderSize;
7406 static const int kYearOffset = kValueOffset + kPointerSize;
7407 static const int kMonthOffset = kYearOffset + kPointerSize;
7408 static const int kDayOffset = kMonthOffset + kPointerSize;
7409 static const int kWeekdayOffset = kDayOffset + kPointerSize;
7410 static const int kHourOffset = kWeekdayOffset + kPointerSize;
7411 static const int kMinOffset = kHourOffset + kPointerSize;
7412 static const int kSecOffset = kMinOffset + kPointerSize;
7413 static const int kCacheStampOffset = kSecOffset + kPointerSize;
7414 static const int kSize = kCacheStampOffset + kPointerSize;
7417 inline Object* DoGetField(FieldIndex index);
7419 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
7421 // Computes and caches the cacheable fields of the date.
7422 inline void SetCachedFields(int64_t local_time_ms, DateCache* date_cache);
7425 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
7429 // Representation of message objects used for error reporting through
7430 // the API. The messages are formatted in JavaScript so this object is
7431 // a real JavaScript object. The information used for formatting the
7432 // error messages are not directly accessible from JavaScript to
7433 // prevent leaking information to user code called during error
7435 class JSMessageObject: public JSObject {
7437 // [type]: the type of error message.
7438 inline int type() const;
7439 inline void set_type(int value);
7441 // [arguments]: the arguments for formatting the error message.
7442 DECL_ACCESSORS(argument, Object)
7444 // [script]: the script from which the error message originated.
7445 DECL_ACCESSORS(script, Object)
7447 // [stack_frames]: an array of stack frames for this error object.
7448 DECL_ACCESSORS(stack_frames, Object)
7450 // [start_position]: the start position in the script for the error message.
7451 inline int start_position() const;
7452 inline void set_start_position(int value);
7454 // [end_position]: the end position in the script for the error message.
7455 inline int end_position() const;
7456 inline void set_end_position(int value);
7458 DECLARE_CAST(JSMessageObject)
7460 // Dispatched behavior.
7461 DECLARE_PRINTER(JSMessageObject)
7462 DECLARE_VERIFIER(JSMessageObject)
7464 // Layout description.
7465 static const int kTypeOffset = JSObject::kHeaderSize;
7466 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
7467 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
7468 static const int kStackFramesOffset = kScriptOffset + kPointerSize;
7469 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
7470 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
7471 static const int kSize = kEndPositionOffset + kPointerSize;
7473 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
7474 kStackFramesOffset + kPointerSize,
7475 kSize> BodyDescriptor;
7479 // Regular expressions
7480 // The regular expression holds a single reference to a FixedArray in
7481 // the kDataOffset field.
7482 // The FixedArray contains the following data:
7483 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
7484 // - reference to the original source string
7485 // - reference to the original flag string
7486 // If it is an atom regexp
7487 // - a reference to a literal string to search for
7488 // If it is an irregexp regexp:
7489 // - a reference to code for Latin1 inputs (bytecode or compiled), or a smi
7490 // used for tracking the last usage (used for code flushing).
7491 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
7492 // used for tracking the last usage (used for code flushing)..
7493 // - max number of registers used by irregexp implementations.
7494 // - number of capture registers (output values) of the regexp.
7495 class JSRegExp: public JSObject {
7498 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
7499 // ATOM: A simple string to match against using an indexOf operation.
7500 // IRREGEXP: Compiled with Irregexp.
7501 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
7502 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
7509 UNICODE_ESCAPES = 16
7514 explicit Flags(uint32_t value) : value_(value) { }
7515 bool is_global() { return (value_ & GLOBAL) != 0; }
7516 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
7517 bool is_multiline() { return (value_ & MULTILINE) != 0; }
7518 bool is_sticky() { return (value_ & STICKY) != 0; }
7519 bool is_unicode() { return (value_ & UNICODE_ESCAPES) != 0; }
7520 uint32_t value() { return value_; }
7525 DECL_ACCESSORS(data, Object)
7527 inline Type TypeTag();
7528 inline int CaptureCount();
7529 inline Flags GetFlags();
7530 inline String* Pattern();
7531 inline Object* DataAt(int index);
7532 // Set implementation data after the object has been prepared.
7533 inline void SetDataAt(int index, Object* value);
7535 static int code_index(bool is_latin1) {
7537 return kIrregexpLatin1CodeIndex;
7539 return kIrregexpUC16CodeIndex;
7543 static int saved_code_index(bool is_latin1) {
7545 return kIrregexpLatin1CodeSavedIndex;
7547 return kIrregexpUC16CodeSavedIndex;
7551 DECLARE_CAST(JSRegExp)
7553 // Dispatched behavior.
7554 DECLARE_VERIFIER(JSRegExp)
7556 static const int kDataOffset = JSObject::kHeaderSize;
7557 static const int kSize = kDataOffset + kPointerSize;
7559 // Indices in the data array.
7560 static const int kTagIndex = 0;
7561 static const int kSourceIndex = kTagIndex + 1;
7562 static const int kFlagsIndex = kSourceIndex + 1;
7563 static const int kDataIndex = kFlagsIndex + 1;
7564 // The data fields are used in different ways depending on the
7565 // value of the tag.
7566 // Atom regexps (literal strings).
7567 static const int kAtomPatternIndex = kDataIndex;
7569 static const int kAtomDataSize = kAtomPatternIndex + 1;
7571 // Irregexp compiled code or bytecode for Latin1. If compilation
7572 // fails, this fields hold an exception object that should be
7573 // thrown if the regexp is used again.
7574 static const int kIrregexpLatin1CodeIndex = kDataIndex;
7575 // Irregexp compiled code or bytecode for UC16. If compilation
7576 // fails, this fields hold an exception object that should be
7577 // thrown if the regexp is used again.
7578 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
7580 // Saved instance of Irregexp compiled code or bytecode for Latin1 that
7581 // is a potential candidate for flushing.
7582 static const int kIrregexpLatin1CodeSavedIndex = kDataIndex + 2;
7583 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
7584 // a potential candidate for flushing.
7585 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
7587 // Maximal number of registers used by either Latin1 or UC16.
7588 // Only used to check that there is enough stack space
7589 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
7590 // Number of captures in the compiled regexp.
7591 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
7593 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
7595 // Offsets directly into the data fixed array.
7596 static const int kDataTagOffset =
7597 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
7598 static const int kDataOneByteCodeOffset =
7599 FixedArray::kHeaderSize + kIrregexpLatin1CodeIndex * kPointerSize;
7600 static const int kDataUC16CodeOffset =
7601 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
7602 static const int kIrregexpCaptureCountOffset =
7603 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
7605 // In-object fields.
7606 static const int kSourceFieldIndex = 0;
7607 static const int kGlobalFieldIndex = 1;
7608 static const int kIgnoreCaseFieldIndex = 2;
7609 static const int kMultilineFieldIndex = 3;
7610 static const int kLastIndexFieldIndex = 4;
7611 static const int kInObjectFieldCount = 5;
7613 // The uninitialized value for a regexp code object.
7614 static const int kUninitializedValue = -1;
7616 // The compilation error value for the regexp code object. The real error
7617 // object is in the saved code field.
7618 static const int kCompilationErrorValue = -2;
7620 // When we store the sweep generation at which we moved the code from the
7621 // code index to the saved code index we mask it of to be in the [0:255]
7623 static const int kCodeAgeMask = 0xff;
7627 class CompilationCacheShape : public BaseShape<HashTableKey*> {
7629 static inline bool IsMatch(HashTableKey* key, Object* value) {
7630 return key->IsMatch(value);
7633 static inline uint32_t Hash(HashTableKey* key) {
7637 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7638 return key->HashForObject(object);
7641 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7643 static const int kPrefixSize = 0;
7644 static const int kEntrySize = 2;
7648 // This cache is used in two different variants. For regexp caching, it simply
7649 // maps identifying info of the regexp to the cached regexp object. Scripts and
7650 // eval code only gets cached after a second probe for the code object. To do
7651 // so, on first "put" only a hash identifying the source is entered into the
7652 // cache, mapping it to a lifetime count of the hash. On each call to Age all
7653 // such lifetimes get reduced, and removed once they reach zero. If a second put
7654 // is called while such a hash is live in the cache, the hash gets replaced by
7655 // an actual cache entry. Age also removes stale live entries from the cache.
7656 // Such entries are identified by SharedFunctionInfos pointing to either the
7657 // recompilation stub, or to "old" code. This avoids memory leaks due to
7658 // premature caching of scripts and eval strings that are never needed later.
7659 class CompilationCacheTable: public HashTable<CompilationCacheTable,
7660 CompilationCacheShape,
7663 // Find cached value for a string key, otherwise return null.
7664 Handle<Object> Lookup(
7665 Handle<String> src, Handle<Context> context, LanguageMode language_mode);
7666 Handle<Object> LookupEval(
7667 Handle<String> src, Handle<SharedFunctionInfo> shared,
7668 LanguageMode language_mode, int scope_position);
7669 Handle<Object> LookupRegExp(Handle<String> source, JSRegExp::Flags flags);
7670 static Handle<CompilationCacheTable> Put(
7671 Handle<CompilationCacheTable> cache, Handle<String> src,
7672 Handle<Context> context, LanguageMode language_mode,
7673 Handle<Object> value);
7674 static Handle<CompilationCacheTable> PutEval(
7675 Handle<CompilationCacheTable> cache, Handle<String> src,
7676 Handle<SharedFunctionInfo> context, Handle<SharedFunctionInfo> value,
7677 int scope_position);
7678 static Handle<CompilationCacheTable> PutRegExp(
7679 Handle<CompilationCacheTable> cache, Handle<String> src,
7680 JSRegExp::Flags flags, Handle<FixedArray> value);
7681 void Remove(Object* value);
7683 static const int kHashGenerations = 10;
7685 DECLARE_CAST(CompilationCacheTable)
7688 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
7692 class CodeCache: public Struct {
7694 DECL_ACCESSORS(default_cache, FixedArray)
7695 DECL_ACCESSORS(normal_type_cache, Object)
7697 // Add the code object to the cache.
7699 Handle<CodeCache> cache, Handle<Name> name, Handle<Code> code);
7701 // Lookup code object in the cache. Returns code object if found and undefined
7703 Object* Lookup(Name* name, Code::Flags flags);
7705 // Get the internal index of a code object in the cache. Returns -1 if the
7706 // code object is not in that cache. This index can be used to later call
7707 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
7709 int GetIndex(Object* name, Code* code);
7711 // Remove an object from the cache with the provided internal index.
7712 void RemoveByIndex(Object* name, Code* code, int index);
7714 DECLARE_CAST(CodeCache)
7716 // Dispatched behavior.
7717 DECLARE_PRINTER(CodeCache)
7718 DECLARE_VERIFIER(CodeCache)
7720 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
7721 static const int kNormalTypeCacheOffset =
7722 kDefaultCacheOffset + kPointerSize;
7723 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
7726 static void UpdateDefaultCache(
7727 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7728 static void UpdateNormalTypeCache(
7729 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7730 Object* LookupDefaultCache(Name* name, Code::Flags flags);
7731 Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
7733 // Code cache layout of the default cache. Elements are alternating name and
7734 // code objects for non normal load/store/call IC's.
7735 static const int kCodeCacheEntrySize = 2;
7736 static const int kCodeCacheEntryNameOffset = 0;
7737 static const int kCodeCacheEntryCodeOffset = 1;
7739 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
7743 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
7745 static inline bool IsMatch(HashTableKey* key, Object* value) {
7746 return key->IsMatch(value);
7749 static inline uint32_t Hash(HashTableKey* key) {
7753 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7754 return key->HashForObject(object);
7757 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7759 static const int kPrefixSize = 0;
7760 static const int kEntrySize = 2;
7764 class CodeCacheHashTable: public HashTable<CodeCacheHashTable,
7765 CodeCacheHashTableShape,
7768 Object* Lookup(Name* name, Code::Flags flags);
7769 static Handle<CodeCacheHashTable> Put(
7770 Handle<CodeCacheHashTable> table,
7774 int GetIndex(Name* name, Code::Flags flags);
7775 void RemoveByIndex(int index);
7777 DECLARE_CAST(CodeCacheHashTable)
7779 // Initial size of the fixed array backing the hash table.
7780 static const int kInitialSize = 64;
7783 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
7787 class PolymorphicCodeCache: public Struct {
7789 DECL_ACCESSORS(cache, Object)
7791 static void Update(Handle<PolymorphicCodeCache> cache,
7792 MapHandleList* maps,
7797 // Returns an undefined value if the entry is not found.
7798 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
7800 DECLARE_CAST(PolymorphicCodeCache)
7802 // Dispatched behavior.
7803 DECLARE_PRINTER(PolymorphicCodeCache)
7804 DECLARE_VERIFIER(PolymorphicCodeCache)
7806 static const int kCacheOffset = HeapObject::kHeaderSize;
7807 static const int kSize = kCacheOffset + kPointerSize;
7810 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
7814 class PolymorphicCodeCacheHashTable
7815 : public HashTable<PolymorphicCodeCacheHashTable,
7816 CodeCacheHashTableShape,
7819 Object* Lookup(MapHandleList* maps, int code_kind);
7821 static Handle<PolymorphicCodeCacheHashTable> Put(
7822 Handle<PolymorphicCodeCacheHashTable> hash_table,
7823 MapHandleList* maps,
7827 DECLARE_CAST(PolymorphicCodeCacheHashTable)
7829 static const int kInitialSize = 64;
7831 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
7835 class TypeFeedbackInfo: public Struct {
7837 inline int ic_total_count();
7838 inline void set_ic_total_count(int count);
7840 inline int ic_with_type_info_count();
7841 inline void change_ic_with_type_info_count(int delta);
7843 inline int ic_generic_count();
7844 inline void change_ic_generic_count(int delta);
7846 inline void initialize_storage();
7848 inline void change_own_type_change_checksum();
7849 inline int own_type_change_checksum();
7851 inline void set_inlined_type_change_checksum(int checksum);
7852 inline bool matches_inlined_type_change_checksum(int checksum);
7854 DECLARE_CAST(TypeFeedbackInfo)
7856 // Dispatched behavior.
7857 DECLARE_PRINTER(TypeFeedbackInfo)
7858 DECLARE_VERIFIER(TypeFeedbackInfo)
7860 static const int kStorage1Offset = HeapObject::kHeaderSize;
7861 static const int kStorage2Offset = kStorage1Offset + kPointerSize;
7862 static const int kStorage3Offset = kStorage2Offset + kPointerSize;
7863 static const int kSize = kStorage3Offset + kPointerSize;
7866 static const int kTypeChangeChecksumBits = 7;
7868 class ICTotalCountField: public BitField<int, 0,
7869 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7870 class OwnTypeChangeChecksum: public BitField<int,
7871 kSmiValueSize - kTypeChangeChecksumBits,
7872 kTypeChangeChecksumBits> {}; // NOLINT
7873 class ICsWithTypeInfoCountField: public BitField<int, 0,
7874 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7875 class InlinedTypeChangeChecksum: public BitField<int,
7876 kSmiValueSize - kTypeChangeChecksumBits,
7877 kTypeChangeChecksumBits> {}; // NOLINT
7879 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
7883 enum AllocationSiteMode {
7884 DONT_TRACK_ALLOCATION_SITE,
7885 TRACK_ALLOCATION_SITE,
7886 LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
7890 class AllocationSite: public Struct {
7892 static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
7893 static const double kPretenureRatio;
7894 static const int kPretenureMinimumCreated = 100;
7896 // Values for pretenure decision field.
7897 enum PretenureDecision {
7903 kLastPretenureDecisionValue = kZombie
7906 const char* PretenureDecisionName(PretenureDecision decision);
7908 DECL_ACCESSORS(transition_info, Object)
7909 // nested_site threads a list of sites that represent nested literals
7910 // walked in a particular order. So [[1, 2], 1, 2] will have one
7911 // nested_site, but [[1, 2], 3, [4]] will have a list of two.
7912 DECL_ACCESSORS(nested_site, Object)
7913 DECL_ACCESSORS(pretenure_data, Smi)
7914 DECL_ACCESSORS(pretenure_create_count, Smi)
7915 DECL_ACCESSORS(dependent_code, DependentCode)
7916 DECL_ACCESSORS(weak_next, Object)
7918 inline void Initialize();
7920 // This method is expensive, it should only be called for reporting.
7921 bool IsNestedSite();
7923 // transition_info bitfields, for constructed array transition info.
7924 class ElementsKindBits: public BitField<ElementsKind, 0, 15> {};
7925 class UnusedBits: public BitField<int, 15, 14> {};
7926 class DoNotInlineBit: public BitField<bool, 29, 1> {};
7928 // Bitfields for pretenure_data
7929 class MementoFoundCountBits: public BitField<int, 0, 26> {};
7930 class PretenureDecisionBits: public BitField<PretenureDecision, 26, 3> {};
7931 class DeoptDependentCodeBit: public BitField<bool, 29, 1> {};
7932 STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
7934 // Increments the mementos found counter and returns true when the first
7935 // memento was found for a given allocation site.
7936 inline bool IncrementMementoFoundCount();
7938 inline void IncrementMementoCreateCount();
7940 PretenureFlag GetPretenureMode();
7942 void ResetPretenureDecision();
7944 PretenureDecision pretenure_decision() {
7945 int value = pretenure_data()->value();
7946 return PretenureDecisionBits::decode(value);
7949 void set_pretenure_decision(PretenureDecision decision) {
7950 int value = pretenure_data()->value();
7952 Smi::FromInt(PretenureDecisionBits::update(value, decision)),
7953 SKIP_WRITE_BARRIER);
7956 bool deopt_dependent_code() {
7957 int value = pretenure_data()->value();
7958 return DeoptDependentCodeBit::decode(value);
7961 void set_deopt_dependent_code(bool deopt) {
7962 int value = pretenure_data()->value();
7964 Smi::FromInt(DeoptDependentCodeBit::update(value, deopt)),
7965 SKIP_WRITE_BARRIER);
7968 int memento_found_count() {
7969 int value = pretenure_data()->value();
7970 return MementoFoundCountBits::decode(value);
7973 inline void set_memento_found_count(int count);
7975 int memento_create_count() {
7976 return pretenure_create_count()->value();
7979 void set_memento_create_count(int count) {
7980 set_pretenure_create_count(Smi::FromInt(count), SKIP_WRITE_BARRIER);
7983 // The pretenuring decision is made during gc, and the zombie state allows
7984 // us to recognize when an allocation site is just being kept alive because
7985 // a later traversal of new space may discover AllocationMementos that point
7986 // to this AllocationSite.
7988 return pretenure_decision() == kZombie;
7991 bool IsMaybeTenure() {
7992 return pretenure_decision() == kMaybeTenure;
7995 inline void MarkZombie();
7997 inline bool MakePretenureDecision(PretenureDecision current_decision,
7999 bool maximum_size_scavenge);
8001 inline bool DigestPretenuringFeedback(bool maximum_size_scavenge);
8003 ElementsKind GetElementsKind() {
8004 DCHECK(!SitePointsToLiteral());
8005 int value = Smi::cast(transition_info())->value();
8006 return ElementsKindBits::decode(value);
8009 void SetElementsKind(ElementsKind kind) {
8010 int value = Smi::cast(transition_info())->value();
8011 set_transition_info(Smi::FromInt(ElementsKindBits::update(value, kind)),
8012 SKIP_WRITE_BARRIER);
8015 bool CanInlineCall() {
8016 int value = Smi::cast(transition_info())->value();
8017 return DoNotInlineBit::decode(value) == 0;
8020 void SetDoNotInlineCall() {
8021 int value = Smi::cast(transition_info())->value();
8022 set_transition_info(Smi::FromInt(DoNotInlineBit::update(value, true)),
8023 SKIP_WRITE_BARRIER);
8026 bool SitePointsToLiteral() {
8027 // If transition_info is a smi, then it represents an ElementsKind
8028 // for a constructed array. Otherwise, it must be a boilerplate
8029 // for an object or array literal.
8030 return transition_info()->IsJSArray() || transition_info()->IsJSObject();
8033 static void DigestTransitionFeedback(Handle<AllocationSite> site,
8034 ElementsKind to_kind);
8036 DECLARE_PRINTER(AllocationSite)
8037 DECLARE_VERIFIER(AllocationSite)
8039 DECLARE_CAST(AllocationSite)
8040 static inline AllocationSiteMode GetMode(
8041 ElementsKind boilerplate_elements_kind);
8042 static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
8043 static inline bool CanTrack(InstanceType type);
8045 static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
8046 static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
8047 static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
8048 static const int kPretenureCreateCountOffset =
8049 kPretenureDataOffset + kPointerSize;
8050 static const int kDependentCodeOffset =
8051 kPretenureCreateCountOffset + kPointerSize;
8052 static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
8053 static const int kSize = kWeakNextOffset + kPointerSize;
8055 // During mark compact we need to take special care for the dependent code
8057 static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
8058 static const int kPointerFieldsEndOffset = kWeakNextOffset;
8060 // For other visitors, use the fixed body descriptor below.
8061 typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
8062 kDependentCodeOffset + kPointerSize,
8063 kSize> BodyDescriptor;
8066 bool PretenuringDecisionMade() {
8067 return pretenure_decision() != kUndecided;
8070 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
8074 class AllocationMemento: public Struct {
8076 static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
8077 static const int kSize = kAllocationSiteOffset + kPointerSize;
8079 DECL_ACCESSORS(allocation_site, Object)
8082 return allocation_site()->IsAllocationSite() &&
8083 !AllocationSite::cast(allocation_site())->IsZombie();
8085 AllocationSite* GetAllocationSite() {
8087 return AllocationSite::cast(allocation_site());
8090 DECLARE_PRINTER(AllocationMemento)
8091 DECLARE_VERIFIER(AllocationMemento)
8093 DECLARE_CAST(AllocationMemento)
8096 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
8100 // Representation of a slow alias as part of a sloppy arguments objects.
8101 // For fast aliases (if HasSloppyArgumentsElements()):
8102 // - the parameter map contains an index into the context
8103 // - all attributes of the element have default values
8104 // For slow aliases (if HasDictionaryArgumentsElements()):
8105 // - the parameter map contains no fast alias mapping (i.e. the hole)
8106 // - this struct (in the slow backing store) contains an index into the context
8107 // - all attributes are available as part if the property details
8108 class AliasedArgumentsEntry: public Struct {
8110 inline int aliased_context_slot() const;
8111 inline void set_aliased_context_slot(int count);
8113 DECLARE_CAST(AliasedArgumentsEntry)
8115 // Dispatched behavior.
8116 DECLARE_PRINTER(AliasedArgumentsEntry)
8117 DECLARE_VERIFIER(AliasedArgumentsEntry)
8119 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
8120 static const int kSize = kAliasedContextSlot + kPointerSize;
8123 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
8127 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
8128 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
8131 class StringHasher {
8133 explicit inline StringHasher(int length, uint32_t seed);
8135 template <typename schar>
8136 static inline uint32_t HashSequentialString(const schar* chars,
8140 // Reads all the data, even for long strings and computes the utf16 length.
8141 static uint32_t ComputeUtf8Hash(Vector<const char> chars,
8143 int* utf16_length_out);
8145 // Calculated hash value for a string consisting of 1 to
8146 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
8147 // value is represented decimal value.
8148 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
8150 // No string is allowed to have a hash of zero. That value is reserved
8151 // for internal properties. If the hash calculation yields zero then we
8153 static const int kZeroHash = 27;
8155 // Reusable parts of the hashing algorithm.
8156 INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
8157 INLINE(static uint32_t GetHashCore(uint32_t running_hash));
8158 INLINE(static uint32_t ComputeRunningHash(uint32_t running_hash,
8159 const uc16* chars, int length));
8160 INLINE(static uint32_t ComputeRunningHashOneByte(uint32_t running_hash,
8165 // Returns the value to store in the hash field of a string with
8166 // the given length and contents.
8167 uint32_t GetHashField();
8168 // Returns true if the hash of this string can be computed without
8169 // looking at the contents.
8170 inline bool has_trivial_hash();
8171 // Adds a block of characters to the hash.
8172 template<typename Char>
8173 inline void AddCharacters(const Char* chars, int len);
8176 // Add a character to the hash.
8177 inline void AddCharacter(uint16_t c);
8178 // Update index. Returns true if string is still an index.
8179 inline bool UpdateIndex(uint16_t c);
8182 uint32_t raw_running_hash_;
8183 uint32_t array_index_;
8184 bool is_array_index_;
8185 bool is_first_char_;
8186 DISALLOW_COPY_AND_ASSIGN(StringHasher);
8190 class IteratingStringHasher : public StringHasher {
8192 static inline uint32_t Hash(String* string, uint32_t seed);
8193 inline void VisitOneByteString(const uint8_t* chars, int length);
8194 inline void VisitTwoByteString(const uint16_t* chars, int length);
8197 inline IteratingStringHasher(int len, uint32_t seed)
8198 : StringHasher(len, seed) {}
8199 void VisitConsString(ConsString* cons_string);
8200 DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher);
8204 // The characteristics of a string are stored in its map. Retrieving these
8205 // few bits of information is moderately expensive, involving two memory
8206 // loads where the second is dependent on the first. To improve efficiency
8207 // the shape of the string is given its own class so that it can be retrieved
8208 // once and used for several string operations. A StringShape is small enough
8209 // to be passed by value and is immutable, but be aware that flattening a
8210 // string can potentially alter its shape. Also be aware that a GC caused by
8211 // something else can alter the shape of a string due to ConsString
8212 // shortcutting. Keeping these restrictions in mind has proven to be error-
8213 // prone and so we no longer put StringShapes in variables unless there is a
8214 // concrete performance benefit at that particular point in the code.
8215 class StringShape BASE_EMBEDDED {
8217 inline explicit StringShape(const String* s);
8218 inline explicit StringShape(Map* s);
8219 inline explicit StringShape(InstanceType t);
8220 inline bool IsSequential();
8221 inline bool IsExternal();
8222 inline bool IsCons();
8223 inline bool IsSliced();
8224 inline bool IsIndirect();
8225 inline bool IsExternalOneByte();
8226 inline bool IsExternalTwoByte();
8227 inline bool IsSequentialOneByte();
8228 inline bool IsSequentialTwoByte();
8229 inline bool IsInternalized();
8230 inline StringRepresentationTag representation_tag();
8231 inline uint32_t encoding_tag();
8232 inline uint32_t full_representation_tag();
8233 inline uint32_t size_tag();
8235 inline uint32_t type() { return type_; }
8236 inline void invalidate() { valid_ = false; }
8237 inline bool valid() { return valid_; }
8239 inline void invalidate() { }
8245 inline void set_valid() { valid_ = true; }
8248 inline void set_valid() { }
8253 // The Name abstract class captures anything that can be used as a property
8254 // name, i.e., strings and symbols. All names store a hash value.
8255 class Name: public HeapObject {
8257 // Get and set the hash field of the name.
8258 inline uint32_t hash_field();
8259 inline void set_hash_field(uint32_t value);
8261 // Tells whether the hash code has been computed.
8262 inline bool HasHashCode();
8264 // Returns a hash value used for the property table
8265 inline uint32_t Hash();
8267 // Equality operations.
8268 inline bool Equals(Name* other);
8269 inline static bool Equals(Handle<Name> one, Handle<Name> two);
8272 inline bool AsArrayIndex(uint32_t* index);
8274 // If the name is private, it can only name own properties.
8275 inline bool IsPrivate();
8277 // If the name is a non-flat string, this method returns a flat version of the
8278 // string. Otherwise it'll just return the input.
8279 static inline Handle<Name> Flatten(Handle<Name> name,
8280 PretenureFlag pretenure = NOT_TENURED);
8284 DECLARE_PRINTER(Name)
8286 void NameShortPrint();
8287 int NameShortPrint(Vector<char> str);
8290 // Layout description.
8291 static const int kHashFieldSlot = HeapObject::kHeaderSize;
8292 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
8293 static const int kHashFieldOffset = kHashFieldSlot;
8295 static const int kHashFieldOffset = kHashFieldSlot + kIntSize;
8297 static const int kSize = kHashFieldSlot + kPointerSize;
8299 // Mask constant for checking if a name has a computed hash code
8300 // and if it is a string that is an array index. The least significant bit
8301 // indicates whether a hash code has been computed. If the hash code has
8302 // been computed the 2nd bit tells whether the string can be used as an
8304 static const int kHashNotComputedMask = 1;
8305 static const int kIsNotArrayIndexMask = 1 << 1;
8306 static const int kNofHashBitFields = 2;
8308 // Shift constant retrieving hash code from hash field.
8309 static const int kHashShift = kNofHashBitFields;
8311 // Only these bits are relevant in the hash, since the top two are shifted
8313 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8315 // Array index strings this short can keep their index in the hash field.
8316 static const int kMaxCachedArrayIndexLength = 7;
8318 // For strings which are array indexes the hash value has the string length
8319 // mixed into the hash, mainly to avoid a hash value of zero which would be
8320 // the case for the string '0'. 24 bits are used for the array index value.
8321 static const int kArrayIndexValueBits = 24;
8322 static const int kArrayIndexLengthBits =
8323 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8325 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8327 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8328 kArrayIndexValueBits> {}; // NOLINT
8329 class ArrayIndexLengthBits : public BitField<unsigned int,
8330 kNofHashBitFields + kArrayIndexValueBits,
8331 kArrayIndexLengthBits> {}; // NOLINT
8333 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8334 // could use a mask to test if the length of string is less than or equal to
8335 // kMaxCachedArrayIndexLength.
8336 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8338 static const unsigned int kContainsCachedArrayIndexMask =
8339 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8340 << ArrayIndexLengthBits::kShift) |
8341 kIsNotArrayIndexMask;
8343 // Value of empty hash field indicating that the hash is not computed.
8344 static const int kEmptyHashField =
8345 kIsNotArrayIndexMask | kHashNotComputedMask;
8348 static inline bool IsHashFieldComputed(uint32_t field);
8351 DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8356 class Symbol: public Name {
8358 // [name]: The print name of a symbol, or undefined if none.
8359 DECL_ACCESSORS(name, Object)
8361 DECL_ACCESSORS(flags, Smi)
8363 // [is_private]: Whether this is a private symbol. Private symbols can only
8364 // be used to designate own properties of objects.
8365 DECL_BOOLEAN_ACCESSORS(is_private)
8367 DECLARE_CAST(Symbol)
8369 // Dispatched behavior.
8370 DECLARE_PRINTER(Symbol)
8371 DECLARE_VERIFIER(Symbol)
8373 // Layout description.
8374 static const int kNameOffset = Name::kSize;
8375 static const int kFlagsOffset = kNameOffset + kPointerSize;
8376 static const int kSize = kFlagsOffset + kPointerSize;
8378 typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
8380 void SymbolShortPrint(std::ostream& os);
8383 static const int kPrivateBit = 0;
8385 const char* PrivateSymbolToName() const;
8388 friend class Name; // For PrivateSymbolToName.
8391 DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
8397 // The String abstract class captures JavaScript string values:
8400 // 4.3.16 String Value
8401 // A string value is a member of the type String and is a finite
8402 // ordered sequence of zero or more 16-bit unsigned integer values.
8404 // All string values have a length field.
8405 class String: public Name {
8407 enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
8409 // Array index strings this short can keep their index in the hash field.
8410 static const int kMaxCachedArrayIndexLength = 7;
8412 // For strings which are array indexes the hash value has the string length
8413 // mixed into the hash, mainly to avoid a hash value of zero which would be
8414 // the case for the string '0'. 24 bits are used for the array index value.
8415 static const int kArrayIndexValueBits = 24;
8416 static const int kArrayIndexLengthBits =
8417 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8419 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8421 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8422 kArrayIndexValueBits> {}; // NOLINT
8423 class ArrayIndexLengthBits : public BitField<unsigned int,
8424 kNofHashBitFields + kArrayIndexValueBits,
8425 kArrayIndexLengthBits> {}; // NOLINT
8427 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8428 // could use a mask to test if the length of string is less than or equal to
8429 // kMaxCachedArrayIndexLength.
8430 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8432 static const unsigned int kContainsCachedArrayIndexMask =
8433 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8434 << ArrayIndexLengthBits::kShift) |
8435 kIsNotArrayIndexMask;
8437 class SubStringRange {
8439 explicit SubStringRange(String* string, int first = 0, int length = -1)
8442 length_(length == -1 ? string->length() : length) {}
8444 inline iterator begin();
8445 inline iterator end();
8453 // Representation of the flat content of a String.
8454 // A non-flat string doesn't have flat content.
8455 // A flat string has content that's encoded as a sequence of either
8456 // one-byte chars or two-byte UC16.
8457 // Returned by String::GetFlatContent().
8460 // Returns true if the string is flat and this structure contains content.
8461 bool IsFlat() { return state_ != NON_FLAT; }
8462 // Returns true if the structure contains one-byte content.
8463 bool IsOneByte() { return state_ == ONE_BYTE; }
8464 // Returns true if the structure contains two-byte content.
8465 bool IsTwoByte() { return state_ == TWO_BYTE; }
8467 // Return the one byte content of the string. Only use if IsOneByte()
8469 Vector<const uint8_t> ToOneByteVector() {
8470 DCHECK_EQ(ONE_BYTE, state_);
8471 return Vector<const uint8_t>(onebyte_start, length_);
8473 // Return the two-byte content of the string. Only use if IsTwoByte()
8475 Vector<const uc16> ToUC16Vector() {
8476 DCHECK_EQ(TWO_BYTE, state_);
8477 return Vector<const uc16>(twobyte_start, length_);
8481 DCHECK(i < length_);
8482 DCHECK(state_ != NON_FLAT);
8483 if (state_ == ONE_BYTE) return onebyte_start[i];
8484 return twobyte_start[i];
8487 bool UsesSameString(const FlatContent& other) const {
8488 return onebyte_start == other.onebyte_start;
8492 enum State { NON_FLAT, ONE_BYTE, TWO_BYTE };
8494 // Constructors only used by String::GetFlatContent().
8495 explicit FlatContent(const uint8_t* start, int length)
8496 : onebyte_start(start), length_(length), state_(ONE_BYTE) {}
8497 explicit FlatContent(const uc16* start, int length)
8498 : twobyte_start(start), length_(length), state_(TWO_BYTE) { }
8499 FlatContent() : onebyte_start(NULL), length_(0), state_(NON_FLAT) { }
8502 const uint8_t* onebyte_start;
8503 const uc16* twobyte_start;
8508 friend class String;
8509 friend class IterableSubString;
8512 template <typename Char>
8513 INLINE(Vector<const Char> GetCharVector());
8515 // Get and set the length of the string.
8516 inline int length() const;
8517 inline void set_length(int value);
8519 // Get and set the length of the string using acquire loads and release
8521 inline int synchronized_length() const;
8522 inline void synchronized_set_length(int value);
8524 // Returns whether this string has only one-byte chars, i.e. all of them can
8525 // be one-byte encoded. This might be the case even if the string is
8526 // two-byte. Such strings may appear when the embedder prefers
8527 // two-byte external representations even for one-byte data.
8528 inline bool IsOneByteRepresentation() const;
8529 inline bool IsTwoByteRepresentation() const;
8531 // Cons and slices have an encoding flag that may not represent the actual
8532 // encoding of the underlying string. This is taken into account here.
8533 // Requires: this->IsFlat()
8534 inline bool IsOneByteRepresentationUnderneath();
8535 inline bool IsTwoByteRepresentationUnderneath();
8537 // NOTE: this should be considered only a hint. False negatives are
8539 inline bool HasOnlyOneByteChars();
8541 // Get and set individual two byte chars in the string.
8542 inline void Set(int index, uint16_t value);
8543 // Get individual two byte char in the string. Repeated calls
8544 // to this method are not efficient unless the string is flat.
8545 INLINE(uint16_t Get(int index));
8547 // Flattens the string. Checks first inline to see if it is
8548 // necessary. Does nothing if the string is not a cons string.
8549 // Flattening allocates a sequential string with the same data as
8550 // the given string and mutates the cons string to a degenerate
8551 // form, where the first component is the new sequential string and
8552 // the second component is the empty string. If allocation fails,
8553 // this function returns a failure. If flattening succeeds, this
8554 // function returns the sequential string that is now the first
8555 // component of the cons string.
8557 // Degenerate cons strings are handled specially by the garbage
8558 // collector (see IsShortcutCandidate).
8560 static inline Handle<String> Flatten(Handle<String> string,
8561 PretenureFlag pretenure = NOT_TENURED);
8563 // Tries to return the content of a flat string as a structure holding either
8564 // a flat vector of char or of uc16.
8565 // If the string isn't flat, and therefore doesn't have flat content, the
8566 // returned structure will report so, and can't provide a vector of either
8568 FlatContent GetFlatContent();
8570 // Returns the parent of a sliced string or first part of a flat cons string.
8571 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
8572 inline String* GetUnderlying();
8574 // String equality operations.
8575 inline bool Equals(String* other);
8576 inline static bool Equals(Handle<String> one, Handle<String> two);
8577 bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
8578 bool IsOneByteEqualTo(Vector<const uint8_t> str);
8579 bool IsTwoByteEqualTo(Vector<const uc16> str);
8581 // Return a UTF8 representation of the string. The string is null
8582 // terminated but may optionally contain nulls. Length is returned
8583 // in length_output if length_output is not a null pointer The string
8584 // should be nearly flat, otherwise the performance of this method may
8585 // be very slow (quadratic in the length). Setting robustness_flag to
8586 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8587 // handles unexpected data without causing assert failures and it does not
8588 // do any heap allocations. This is useful when printing stack traces.
8589 base::SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
8590 RobustnessFlag robustness_flag,
8591 int offset, int length,
8592 int* length_output = 0);
8593 base::SmartArrayPointer<char> ToCString(
8594 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
8595 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
8596 int* length_output = 0);
8598 // Return a 16 bit Unicode representation of the string.
8599 // The string should be nearly flat, otherwise the performance of
8600 // of this method may be very bad. Setting robustness_flag to
8601 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8602 // handles unexpected data without causing assert failures and it does not
8603 // do any heap allocations. This is useful when printing stack traces.
8604 base::SmartArrayPointer<uc16> ToWideCString(
8605 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
8607 bool ComputeArrayIndex(uint32_t* index);
8610 bool MakeExternal(v8::String::ExternalStringResource* resource);
8611 bool MakeExternal(v8::String::ExternalOneByteStringResource* resource);
8614 inline bool AsArrayIndex(uint32_t* index);
8616 DECLARE_CAST(String)
8618 void PrintOn(FILE* out);
8620 // For use during stack traces. Performs rudimentary sanity check.
8623 // Dispatched behavior.
8624 void StringShortPrint(StringStream* accumulator);
8625 void PrintUC16(std::ostream& os, int start = 0, int end = -1); // NOLINT
8626 #if defined(DEBUG) || defined(OBJECT_PRINT)
8627 char* ToAsciiArray();
8629 DECLARE_PRINTER(String)
8630 DECLARE_VERIFIER(String)
8632 inline bool IsFlat();
8634 // Layout description.
8635 static const int kLengthOffset = Name::kSize;
8636 static const int kSize = kLengthOffset + kPointerSize;
8638 // Maximum number of characters to consider when trying to convert a string
8639 // value into an array index.
8640 static const int kMaxArrayIndexSize = 10;
8641 STATIC_ASSERT(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
8644 static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
8645 static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
8646 static const int kMaxUtf16CodeUnit = 0xffff;
8647 static const uint32_t kMaxUtf16CodeUnitU = kMaxUtf16CodeUnit;
8649 // Value of hash field containing computed hash equal to zero.
8650 static const int kEmptyStringHash = kIsNotArrayIndexMask;
8652 // Maximal string length.
8653 static const int kMaxLength = (1 << 28) - 16;
8655 // Max length for computing hash. For strings longer than this limit the
8656 // string length is used as the hash value.
8657 static const int kMaxHashCalcLength = 16383;
8659 // Limit for truncation in short printing.
8660 static const int kMaxShortPrintLength = 1024;
8662 // Support for regular expressions.
8663 const uc16* GetTwoByteData(unsigned start);
8665 // Helper function for flattening strings.
8666 template <typename sinkchar>
8667 static void WriteToFlat(String* source,
8672 // The return value may point to the first aligned word containing the first
8673 // non-one-byte character, rather than directly to the non-one-byte character.
8674 // If the return value is >= the passed length, the entire string was
8676 static inline int NonAsciiStart(const char* chars, int length) {
8677 const char* start = chars;
8678 const char* limit = chars + length;
8680 if (length >= kIntptrSize) {
8681 // Check unaligned bytes.
8682 while (!IsAligned(reinterpret_cast<intptr_t>(chars), sizeof(uintptr_t))) {
8683 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8684 return static_cast<int>(chars - start);
8688 // Check aligned words.
8689 DCHECK(unibrow::Utf8::kMaxOneByteChar == 0x7F);
8690 const uintptr_t non_one_byte_mask = kUintptrAllBitsSet / 0xFF * 0x80;
8691 while (chars + sizeof(uintptr_t) <= limit) {
8692 if (*reinterpret_cast<const uintptr_t*>(chars) & non_one_byte_mask) {
8693 return static_cast<int>(chars - start);
8695 chars += sizeof(uintptr_t);
8698 // Check remaining unaligned bytes.
8699 while (chars < limit) {
8700 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8701 return static_cast<int>(chars - start);
8706 return static_cast<int>(chars - start);
8709 static inline bool IsAscii(const char* chars, int length) {
8710 return NonAsciiStart(chars, length) >= length;
8713 static inline bool IsAscii(const uint8_t* chars, int length) {
8715 NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
8718 static inline int NonOneByteStart(const uc16* chars, int length) {
8719 const uc16* limit = chars + length;
8720 const uc16* start = chars;
8721 while (chars < limit) {
8722 if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
8725 return static_cast<int>(chars - start);
8728 static inline bool IsOneByte(const uc16* chars, int length) {
8729 return NonOneByteStart(chars, length) >= length;
8732 template<class Visitor>
8733 static inline ConsString* VisitFlat(Visitor* visitor,
8737 static Handle<FixedArray> CalculateLineEnds(Handle<String> string,
8738 bool include_ending_line);
8740 // Use the hash field to forward to the canonical internalized string
8741 // when deserializing an internalized string.
8742 inline void SetForwardedInternalizedString(String* string);
8743 inline String* GetForwardedInternalizedString();
8747 friend class StringTableInsertionKey;
8749 static Handle<String> SlowFlatten(Handle<ConsString> cons,
8750 PretenureFlag tenure);
8752 // Slow case of String::Equals. This implementation works on any strings
8753 // but it is most efficient on strings that are almost flat.
8754 bool SlowEquals(String* other);
8756 static bool SlowEquals(Handle<String> one, Handle<String> two);
8758 // Slow case of AsArrayIndex.
8759 bool SlowAsArrayIndex(uint32_t* index);
8761 // Compute and set the hash code.
8762 uint32_t ComputeAndSetHash();
8764 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
8768 // The SeqString abstract class captures sequential string values.
8769 class SeqString: public String {
8771 DECLARE_CAST(SeqString)
8773 // Layout description.
8774 static const int kHeaderSize = String::kSize;
8776 // Truncate the string in-place if possible and return the result.
8777 // In case of new_length == 0, the empty string is returned without
8778 // truncating the original string.
8779 MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
8782 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
8786 // The OneByteString class captures sequential one-byte string objects.
8787 // Each character in the OneByteString is an one-byte character.
8788 class SeqOneByteString: public SeqString {
8790 static const bool kHasOneByteEncoding = true;
8792 // Dispatched behavior.
8793 inline uint16_t SeqOneByteStringGet(int index);
8794 inline void SeqOneByteStringSet(int index, uint16_t value);
8796 // Get the address of the characters in this string.
8797 inline Address GetCharsAddress();
8799 inline uint8_t* GetChars();
8801 DECLARE_CAST(SeqOneByteString)
8803 // Garbage collection support. This method is called by the
8804 // garbage collector to compute the actual size of an OneByteString
8806 inline int SeqOneByteStringSize(InstanceType instance_type);
8808 // Computes the size for an OneByteString instance of a given length.
8809 static int SizeFor(int length) {
8810 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
8813 // Maximal memory usage for a single sequential one-byte string.
8814 static const int kMaxSize = 512 * MB - 1;
8815 STATIC_ASSERT((kMaxSize - kHeaderSize) >= String::kMaxLength);
8818 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
8822 // The TwoByteString class captures sequential unicode string objects.
8823 // Each character in the TwoByteString is a two-byte uint16_t.
8824 class SeqTwoByteString: public SeqString {
8826 static const bool kHasOneByteEncoding = false;
8828 // Dispatched behavior.
8829 inline uint16_t SeqTwoByteStringGet(int index);
8830 inline void SeqTwoByteStringSet(int index, uint16_t value);
8832 // Get the address of the characters in this string.
8833 inline Address GetCharsAddress();
8835 inline uc16* GetChars();
8838 const uint16_t* SeqTwoByteStringGetData(unsigned start);
8840 DECLARE_CAST(SeqTwoByteString)
8842 // Garbage collection support. This method is called by the
8843 // garbage collector to compute the actual size of a TwoByteString
8845 inline int SeqTwoByteStringSize(InstanceType instance_type);
8847 // Computes the size for a TwoByteString instance of a given length.
8848 static int SizeFor(int length) {
8849 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
8852 // Maximal memory usage for a single sequential two-byte string.
8853 static const int kMaxSize = 512 * MB - 1;
8854 STATIC_ASSERT(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
8855 String::kMaxLength);
8858 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
8862 // The ConsString class describes string values built by using the
8863 // addition operator on strings. A ConsString is a pair where the
8864 // first and second components are pointers to other string values.
8865 // One or both components of a ConsString can be pointers to other
8866 // ConsStrings, creating a binary tree of ConsStrings where the leaves
8867 // are non-ConsString string values. The string value represented by
8868 // a ConsString can be obtained by concatenating the leaf string
8869 // values in a left-to-right depth-first traversal of the tree.
8870 class ConsString: public String {
8872 // First string of the cons cell.
8873 inline String* first();
8874 // Doesn't check that the result is a string, even in debug mode. This is
8875 // useful during GC where the mark bits confuse the checks.
8876 inline Object* unchecked_first();
8877 inline void set_first(String* first,
8878 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8880 // Second string of the cons cell.
8881 inline String* second();
8882 // Doesn't check that the result is a string, even in debug mode. This is
8883 // useful during GC where the mark bits confuse the checks.
8884 inline Object* unchecked_second();
8885 inline void set_second(String* second,
8886 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8888 // Dispatched behavior.
8889 uint16_t ConsStringGet(int index);
8891 DECLARE_CAST(ConsString)
8893 // Layout description.
8894 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
8895 static const int kSecondOffset = kFirstOffset + kPointerSize;
8896 static const int kSize = kSecondOffset + kPointerSize;
8898 // Minimum length for a cons string.
8899 static const int kMinLength = 13;
8901 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
8904 DECLARE_VERIFIER(ConsString)
8907 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
8911 // The Sliced String class describes strings that are substrings of another
8912 // sequential string. The motivation is to save time and memory when creating
8913 // a substring. A Sliced String is described as a pointer to the parent,
8914 // the offset from the start of the parent string and the length. Using
8915 // a Sliced String therefore requires unpacking of the parent string and
8916 // adding the offset to the start address. A substring of a Sliced String
8917 // are not nested since the double indirection is simplified when creating
8918 // such a substring.
8919 // Currently missing features are:
8920 // - handling externalized parent strings
8921 // - external strings as parent
8922 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
8923 class SlicedString: public String {
8925 inline String* parent();
8926 inline void set_parent(String* parent,
8927 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8928 inline int offset() const;
8929 inline void set_offset(int offset);
8931 // Dispatched behavior.
8932 uint16_t SlicedStringGet(int index);
8934 DECLARE_CAST(SlicedString)
8936 // Layout description.
8937 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
8938 static const int kOffsetOffset = kParentOffset + kPointerSize;
8939 static const int kSize = kOffsetOffset + kPointerSize;
8941 // Minimum length for a sliced string.
8942 static const int kMinLength = 13;
8944 typedef FixedBodyDescriptor<kParentOffset,
8945 kOffsetOffset + kPointerSize, kSize>
8948 DECLARE_VERIFIER(SlicedString)
8951 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
8955 // The ExternalString class describes string values that are backed by
8956 // a string resource that lies outside the V8 heap. ExternalStrings
8957 // consist of the length field common to all strings, a pointer to the
8958 // external resource. It is important to ensure (externally) that the
8959 // resource is not deallocated while the ExternalString is live in the
8962 // The API expects that all ExternalStrings are created through the
8963 // API. Therefore, ExternalStrings should not be used internally.
8964 class ExternalString: public String {
8966 DECLARE_CAST(ExternalString)
8968 // Layout description.
8969 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
8970 static const int kShortSize = kResourceOffset + kPointerSize;
8971 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
8972 static const int kSize = kResourceDataOffset + kPointerSize;
8974 static const int kMaxShortLength =
8975 (kShortSize - SeqString::kHeaderSize) / kCharSize;
8977 // Return whether external string is short (data pointer is not cached).
8978 inline bool is_short();
8980 STATIC_ASSERT(kResourceOffset == Internals::kStringResourceOffset);
8983 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
8987 // The ExternalOneByteString class is an external string backed by an
8989 class ExternalOneByteString : public ExternalString {
8991 static const bool kHasOneByteEncoding = true;
8993 typedef v8::String::ExternalOneByteStringResource Resource;
8995 // The underlying resource.
8996 inline const Resource* resource();
8997 inline void set_resource(const Resource* buffer);
8999 // Update the pointer cache to the external character array.
9000 // The cached pointer is always valid, as the external character array does =
9001 // not move during lifetime. Deserialization is the only exception, after
9002 // which the pointer cache has to be refreshed.
9003 inline void update_data_cache();
9005 inline const uint8_t* GetChars();
9007 // Dispatched behavior.
9008 inline uint16_t ExternalOneByteStringGet(int index);
9010 DECLARE_CAST(ExternalOneByteString)
9012 // Garbage collection support.
9013 inline void ExternalOneByteStringIterateBody(ObjectVisitor* v);
9015 template <typename StaticVisitor>
9016 inline void ExternalOneByteStringIterateBody();
9019 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalOneByteString);
9023 // The ExternalTwoByteString class is an external string backed by a UTF-16
9025 class ExternalTwoByteString: public ExternalString {
9027 static const bool kHasOneByteEncoding = false;
9029 typedef v8::String::ExternalStringResource Resource;
9031 // The underlying string resource.
9032 inline const Resource* resource();
9033 inline void set_resource(const Resource* buffer);
9035 // Update the pointer cache to the external character array.
9036 // The cached pointer is always valid, as the external character array does =
9037 // not move during lifetime. Deserialization is the only exception, after
9038 // which the pointer cache has to be refreshed.
9039 inline void update_data_cache();
9041 inline const uint16_t* GetChars();
9043 // Dispatched behavior.
9044 inline uint16_t ExternalTwoByteStringGet(int index);
9047 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
9049 DECLARE_CAST(ExternalTwoByteString)
9051 // Garbage collection support.
9052 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
9054 template<typename StaticVisitor>
9055 inline void ExternalTwoByteStringIterateBody();
9058 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
9062 // Utility superclass for stack-allocated objects that must be updated
9063 // on gc. It provides two ways for the gc to update instances, either
9064 // iterating or updating after gc.
9065 class Relocatable BASE_EMBEDDED {
9067 explicit inline Relocatable(Isolate* isolate);
9068 inline virtual ~Relocatable();
9069 virtual void IterateInstance(ObjectVisitor* v) { }
9070 virtual void PostGarbageCollection() { }
9072 static void PostGarbageCollectionProcessing(Isolate* isolate);
9073 static int ArchiveSpacePerThread();
9074 static char* ArchiveState(Isolate* isolate, char* to);
9075 static char* RestoreState(Isolate* isolate, char* from);
9076 static void Iterate(Isolate* isolate, ObjectVisitor* v);
9077 static void Iterate(ObjectVisitor* v, Relocatable* top);
9078 static char* Iterate(ObjectVisitor* v, char* t);
9086 // A flat string reader provides random access to the contents of a
9087 // string independent of the character width of the string. The handle
9088 // must be valid as long as the reader is being used.
9089 class FlatStringReader : public Relocatable {
9091 FlatStringReader(Isolate* isolate, Handle<String> str);
9092 FlatStringReader(Isolate* isolate, Vector<const char> input);
9093 void PostGarbageCollection();
9094 inline uc32 Get(int index);
9095 template <typename Char>
9096 inline Char Get(int index);
9097 int length() { return length_; }
9106 // This maintains an off-stack representation of the stack frames required
9107 // to traverse a ConsString, allowing an entirely iterative and restartable
9108 // traversal of the entire string
9109 class ConsStringIterator {
9111 inline ConsStringIterator() {}
9112 inline explicit ConsStringIterator(ConsString* cons_string, int offset = 0) {
9113 Reset(cons_string, offset);
9115 inline void Reset(ConsString* cons_string, int offset = 0) {
9117 // Next will always return NULL.
9118 if (cons_string == NULL) return;
9119 Initialize(cons_string, offset);
9121 // Returns NULL when complete.
9122 inline String* Next(int* offset_out) {
9124 if (depth_ == 0) return NULL;
9125 return Continue(offset_out);
9129 static const int kStackSize = 32;
9130 // Use a mask instead of doing modulo operations for stack wrapping.
9131 static const int kDepthMask = kStackSize-1;
9132 STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
9133 static inline int OffsetForDepth(int depth);
9135 inline void PushLeft(ConsString* string);
9136 inline void PushRight(ConsString* string);
9137 inline void AdjustMaximumDepth();
9139 inline bool StackBlown() { return maximum_depth_ - depth_ == kStackSize; }
9140 void Initialize(ConsString* cons_string, int offset);
9141 String* Continue(int* offset_out);
9142 String* NextLeaf(bool* blew_stack);
9143 String* Search(int* offset_out);
9145 // Stack must always contain only frames for which right traversal
9146 // has not yet been performed.
9147 ConsString* frames_[kStackSize];
9152 DISALLOW_COPY_AND_ASSIGN(ConsStringIterator);
9156 class StringCharacterStream {
9158 inline StringCharacterStream(String* string,
9160 inline uint16_t GetNext();
9161 inline bool HasMore();
9162 inline void Reset(String* string, int offset = 0);
9163 inline void VisitOneByteString(const uint8_t* chars, int length);
9164 inline void VisitTwoByteString(const uint16_t* chars, int length);
9167 ConsStringIterator iter_;
9170 const uint8_t* buffer8_;
9171 const uint16_t* buffer16_;
9173 const uint8_t* end_;
9174 DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
9178 template <typename T>
9179 class VectorIterator {
9181 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
9182 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
9183 T GetNext() { return data_[index_++]; }
9184 bool has_more() { return index_ < data_.length(); }
9186 Vector<const T> data_;
9191 // The Oddball describes objects null, undefined, true, and false.
9192 class Oddball: public HeapObject {
9194 // [to_string]: Cached to_string computed at startup.
9195 DECL_ACCESSORS(to_string, String)
9197 // [to_number]: Cached to_number computed at startup.
9198 DECL_ACCESSORS(to_number, Object)
9200 inline byte kind() const;
9201 inline void set_kind(byte kind);
9203 DECLARE_CAST(Oddball)
9205 // Dispatched behavior.
9206 DECLARE_VERIFIER(Oddball)
9208 // Initialize the fields.
9209 static void Initialize(Isolate* isolate,
9210 Handle<Oddball> oddball,
9211 const char* to_string,
9212 Handle<Object> to_number,
9215 // Layout description.
9216 static const int kToStringOffset = HeapObject::kHeaderSize;
9217 static const int kToNumberOffset = kToStringOffset + kPointerSize;
9218 static const int kKindOffset = kToNumberOffset + kPointerSize;
9219 static const int kSize = kKindOffset + kPointerSize;
9221 static const byte kFalse = 0;
9222 static const byte kTrue = 1;
9223 static const byte kNotBooleanMask = ~1;
9224 static const byte kTheHole = 2;
9225 static const byte kNull = 3;
9226 static const byte kArgumentMarker = 4;
9227 static const byte kUndefined = 5;
9228 static const byte kUninitialized = 6;
9229 static const byte kOther = 7;
9230 static const byte kException = 8;
9232 typedef FixedBodyDescriptor<kToStringOffset,
9233 kToNumberOffset + kPointerSize,
9234 kSize> BodyDescriptor;
9236 STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset);
9237 STATIC_ASSERT(kNull == Internals::kNullOddballKind);
9238 STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind);
9241 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
9245 class Cell: public HeapObject {
9247 // [value]: value of the cell.
9248 DECL_ACCESSORS(value, Object)
9252 static inline Cell* FromValueAddress(Address value) {
9253 Object* result = FromAddress(value - kValueOffset);
9254 return static_cast<Cell*>(result);
9257 inline Address ValueAddress() {
9258 return address() + kValueOffset;
9261 // Dispatched behavior.
9262 DECLARE_PRINTER(Cell)
9263 DECLARE_VERIFIER(Cell)
9265 // Layout description.
9266 static const int kValueOffset = HeapObject::kHeaderSize;
9267 static const int kSize = kValueOffset + kPointerSize;
9269 typedef FixedBodyDescriptor<kValueOffset,
9270 kValueOffset + kPointerSize,
9271 kSize> BodyDescriptor;
9274 DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9278 class PropertyCell : public HeapObject {
9280 // [property_details]: details of the global property.
9281 DECL_ACCESSORS(property_details_raw, Object)
9282 // [value]: value of the global property.
9283 DECL_ACCESSORS(value, Object)
9284 // [dependent_code]: dependent code that depends on the type of the global
9286 DECL_ACCESSORS(dependent_code, DependentCode)
9288 PropertyDetails property_details() {
9289 return PropertyDetails(Smi::cast(property_details_raw()));
9292 void set_property_details(PropertyDetails details) {
9293 set_property_details_raw(details.AsSmi());
9296 PropertyCellConstantType GetConstantType();
9298 // Computes the new type of the cell's contents for the given value, but
9299 // without actually modifying the details.
9300 static PropertyCellType UpdatedType(Handle<PropertyCell> cell,
9301 Handle<Object> value,
9302 PropertyDetails details);
9303 static void UpdateCell(Handle<GlobalDictionary> dictionary, int entry,
9304 Handle<Object> value, PropertyDetails details);
9306 static Handle<PropertyCell> InvalidateEntry(
9307 Handle<GlobalDictionary> dictionary, int entry);
9309 static void SetValueWithInvalidation(Handle<PropertyCell> cell,
9310 Handle<Object> new_value);
9312 DECLARE_CAST(PropertyCell)
9314 // Dispatched behavior.
9315 DECLARE_PRINTER(PropertyCell)
9316 DECLARE_VERIFIER(PropertyCell)
9318 // Layout description.
9319 static const int kDetailsOffset = HeapObject::kHeaderSize;
9320 static const int kValueOffset = kDetailsOffset + kPointerSize;
9321 static const int kDependentCodeOffset = kValueOffset + kPointerSize;
9322 static const int kSize = kDependentCodeOffset + kPointerSize;
9324 static const int kPointerFieldsBeginOffset = kValueOffset;
9325 static const int kPointerFieldsEndOffset = kSize;
9327 typedef FixedBodyDescriptor<kValueOffset,
9329 kSize> BodyDescriptor;
9332 DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9336 class WeakCell : public HeapObject {
9338 inline Object* value() const;
9340 // This should not be called by anyone except GC.
9341 inline void clear();
9343 // This should not be called by anyone except allocator.
9344 inline void initialize(HeapObject* value);
9346 inline bool cleared() const;
9348 DECL_ACCESSORS(next, Object)
9350 inline void clear_next(Heap* heap);
9352 inline bool next_cleared();
9354 DECLARE_CAST(WeakCell)
9356 DECLARE_PRINTER(WeakCell)
9357 DECLARE_VERIFIER(WeakCell)
9359 // Layout description.
9360 static const int kValueOffset = HeapObject::kHeaderSize;
9361 static const int kNextOffset = kValueOffset + kPointerSize;
9362 static const int kSize = kNextOffset + kPointerSize;
9364 typedef FixedBodyDescriptor<kValueOffset, kSize, kSize> BodyDescriptor;
9367 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakCell);
9371 // The JSProxy describes EcmaScript Harmony proxies
9372 class JSProxy: public JSReceiver {
9374 // [handler]: The handler property.
9375 DECL_ACCESSORS(handler, Object)
9377 // [hash]: The hash code property (undefined if not initialized yet).
9378 DECL_ACCESSORS(hash, Object)
9380 DECLARE_CAST(JSProxy)
9382 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithHandler(
9383 Handle<JSProxy> proxy,
9384 Handle<Object> receiver,
9387 // If the handler defines an accessor property with a setter, invoke it.
9388 // If it defines an accessor property without a setter, or a data property
9389 // that is read-only, throw. In all these cases set '*done' to true,
9390 // otherwise set it to false.
9392 static MaybeHandle<Object> SetPropertyViaPrototypesWithHandler(
9393 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9394 Handle<Object> value, LanguageMode language_mode, bool* done);
9396 MUST_USE_RESULT static Maybe<PropertyAttributes>
9397 GetPropertyAttributesWithHandler(Handle<JSProxy> proxy,
9398 Handle<Object> receiver,
9400 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithHandler(
9401 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9402 Handle<Object> value, LanguageMode language_mode);
9404 // Turn the proxy into an (empty) JSObject.
9405 static void Fix(Handle<JSProxy> proxy);
9407 // Initializes the body after the handler slot.
9408 inline void InitializeBody(int object_size, Object* value);
9410 // Invoke a trap by name. If the trap does not exist on this's handler,
9411 // but derived_trap is non-NULL, invoke that instead. May cause GC.
9412 MUST_USE_RESULT static MaybeHandle<Object> CallTrap(
9413 Handle<JSProxy> proxy,
9415 Handle<Object> derived_trap,
9417 Handle<Object> args[]);
9419 // Dispatched behavior.
9420 DECLARE_PRINTER(JSProxy)
9421 DECLARE_VERIFIER(JSProxy)
9423 // Layout description. We add padding so that a proxy has the same
9424 // size as a virgin JSObject. This is essential for becoming a JSObject
9426 static const int kHandlerOffset = HeapObject::kHeaderSize;
9427 static const int kHashOffset = kHandlerOffset + kPointerSize;
9428 static const int kPaddingOffset = kHashOffset + kPointerSize;
9429 static const int kSize = JSObject::kHeaderSize;
9430 static const int kHeaderSize = kPaddingOffset;
9431 static const int kPaddingSize = kSize - kPaddingOffset;
9433 STATIC_ASSERT(kPaddingSize >= 0);
9435 typedef FixedBodyDescriptor<kHandlerOffset,
9437 kSize> BodyDescriptor;
9440 friend class JSReceiver;
9442 MUST_USE_RESULT static Maybe<bool> HasPropertyWithHandler(
9443 Handle<JSProxy> proxy, Handle<Name> name);
9445 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithHandler(
9446 Handle<JSProxy> proxy, Handle<Name> name, LanguageMode language_mode);
9448 MUST_USE_RESULT Object* GetIdentityHash();
9450 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
9452 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
9456 class JSFunctionProxy: public JSProxy {
9458 // [call_trap]: The call trap.
9459 DECL_ACCESSORS(call_trap, Object)
9461 // [construct_trap]: The construct trap.
9462 DECL_ACCESSORS(construct_trap, Object)
9464 DECLARE_CAST(JSFunctionProxy)
9466 // Dispatched behavior.
9467 DECLARE_PRINTER(JSFunctionProxy)
9468 DECLARE_VERIFIER(JSFunctionProxy)
9470 // Layout description.
9471 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
9472 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
9473 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
9474 static const int kSize = JSFunction::kSize;
9475 static const int kPaddingSize = kSize - kPaddingOffset;
9477 STATIC_ASSERT(kPaddingSize >= 0);
9479 typedef FixedBodyDescriptor<kHandlerOffset,
9480 kConstructTrapOffset + kPointerSize,
9481 kSize> BodyDescriptor;
9484 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
9488 class JSCollection : public JSObject {
9490 // [table]: the backing hash table
9491 DECL_ACCESSORS(table, Object)
9493 static const int kTableOffset = JSObject::kHeaderSize;
9494 static const int kSize = kTableOffset + kPointerSize;
9497 DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollection);
9501 // The JSSet describes EcmaScript Harmony sets
9502 class JSSet : public JSCollection {
9506 // Dispatched behavior.
9507 DECLARE_PRINTER(JSSet)
9508 DECLARE_VERIFIER(JSSet)
9511 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
9515 // The JSMap describes EcmaScript Harmony maps
9516 class JSMap : public JSCollection {
9520 // Dispatched behavior.
9521 DECLARE_PRINTER(JSMap)
9522 DECLARE_VERIFIER(JSMap)
9525 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
9529 // OrderedHashTableIterator is an iterator that iterates over the keys and
9530 // values of an OrderedHashTable.
9532 // The iterator has a reference to the underlying OrderedHashTable data,
9533 // [table], as well as the current [index] the iterator is at.
9535 // When the OrderedHashTable is rehashed it adds a reference from the old table
9536 // to the new table as well as storing enough data about the changes so that the
9537 // iterator [index] can be adjusted accordingly.
9539 // When the [Next] result from the iterator is requested, the iterator checks if
9540 // there is a newer table that it needs to transition to.
9541 template<class Derived, class TableType>
9542 class OrderedHashTableIterator: public JSObject {
9544 // [table]: the backing hash table mapping keys to values.
9545 DECL_ACCESSORS(table, Object)
9547 // [index]: The index into the data table.
9548 DECL_ACCESSORS(index, Object)
9550 // [kind]: The kind of iteration this is. One of the [Kind] enum values.
9551 DECL_ACCESSORS(kind, Object)
9554 void OrderedHashTableIteratorPrint(std::ostream& os); // NOLINT
9557 static const int kTableOffset = JSObject::kHeaderSize;
9558 static const int kIndexOffset = kTableOffset + kPointerSize;
9559 static const int kKindOffset = kIndexOffset + kPointerSize;
9560 static const int kSize = kKindOffset + kPointerSize;
9568 // Whether the iterator has more elements. This needs to be called before
9569 // calling |CurrentKey| and/or |CurrentValue|.
9572 // Move the index forward one.
9574 set_index(Smi::FromInt(Smi::cast(index())->value() + 1));
9577 // Populates the array with the next key and value and then moves the iterator
9579 // This returns the |kind| or 0 if the iterator is already at the end.
9580 Smi* Next(JSArray* value_array);
9582 // Returns the current key of the iterator. This should only be called when
9583 // |HasMore| returns true.
9584 inline Object* CurrentKey();
9587 // Transitions the iterator to the non obsolete backing store. This is a NOP
9588 // if the [table] is not obsolete.
9591 DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
9595 class JSSetIterator: public OrderedHashTableIterator<JSSetIterator,
9598 // Dispatched behavior.
9599 DECLARE_PRINTER(JSSetIterator)
9600 DECLARE_VERIFIER(JSSetIterator)
9602 DECLARE_CAST(JSSetIterator)
9604 // Called by |Next| to populate the array. This allows the subclasses to
9605 // populate the array differently.
9606 inline void PopulateValueArray(FixedArray* array);
9609 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSetIterator);
9613 class JSMapIterator: public OrderedHashTableIterator<JSMapIterator,
9616 // Dispatched behavior.
9617 DECLARE_PRINTER(JSMapIterator)
9618 DECLARE_VERIFIER(JSMapIterator)
9620 DECLARE_CAST(JSMapIterator)
9622 // Called by |Next| to populate the array. This allows the subclasses to
9623 // populate the array differently.
9624 inline void PopulateValueArray(FixedArray* array);
9627 // Returns the current value of the iterator. This should only be called when
9628 // |HasMore| returns true.
9629 inline Object* CurrentValue();
9631 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMapIterator);
9635 // Base class for both JSWeakMap and JSWeakSet
9636 class JSWeakCollection: public JSObject {
9638 // [table]: the backing hash table mapping keys to values.
9639 DECL_ACCESSORS(table, Object)
9641 // [next]: linked list of encountered weak maps during GC.
9642 DECL_ACCESSORS(next, Object)
9644 static const int kTableOffset = JSObject::kHeaderSize;
9645 static const int kNextOffset = kTableOffset + kPointerSize;
9646 static const int kSize = kNextOffset + kPointerSize;
9649 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
9653 // The JSWeakMap describes EcmaScript Harmony weak maps
9654 class JSWeakMap: public JSWeakCollection {
9656 DECLARE_CAST(JSWeakMap)
9658 // Dispatched behavior.
9659 DECLARE_PRINTER(JSWeakMap)
9660 DECLARE_VERIFIER(JSWeakMap)
9663 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
9667 // The JSWeakSet describes EcmaScript Harmony weak sets
9668 class JSWeakSet: public JSWeakCollection {
9670 DECLARE_CAST(JSWeakSet)
9672 // Dispatched behavior.
9673 DECLARE_PRINTER(JSWeakSet)
9674 DECLARE_VERIFIER(JSWeakSet)
9677 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
9681 // Whether a JSArrayBuffer is a SharedArrayBuffer or not.
9682 enum class SharedFlag { kNotShared, kShared };
9685 class JSArrayBuffer: public JSObject {
9687 // [backing_store]: backing memory for this array
9688 DECL_ACCESSORS(backing_store, void)
9690 // [byte_length]: length in bytes
9691 DECL_ACCESSORS(byte_length, Object)
9693 inline uint32_t bit_field() const;
9694 inline void set_bit_field(uint32_t bits);
9696 inline bool is_external();
9697 inline void set_is_external(bool value);
9699 inline bool is_neuterable();
9700 inline void set_is_neuterable(bool value);
9702 inline bool was_neutered();
9703 inline void set_was_neutered(bool value);
9705 inline bool is_shared();
9706 inline void set_is_shared(bool value);
9708 DECLARE_CAST(JSArrayBuffer)
9712 // Dispatched behavior.
9713 DECLARE_PRINTER(JSArrayBuffer)
9714 DECLARE_VERIFIER(JSArrayBuffer)
9716 static const int kBackingStoreOffset = JSObject::kHeaderSize;
9717 static const int kByteLengthOffset = kBackingStoreOffset + kPointerSize;
9718 static const int kBitFieldSlot = kByteLengthOffset + kPointerSize;
9719 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
9720 static const int kBitFieldOffset = kBitFieldSlot;
9722 static const int kBitFieldOffset = kBitFieldSlot + kIntSize;
9724 static const int kSize = kBitFieldSlot + kPointerSize;
9726 static const int kSizeWithInternalFields =
9727 kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
9729 class IsExternal : public BitField<bool, 1, 1> {};
9730 class IsNeuterable : public BitField<bool, 2, 1> {};
9731 class WasNeutered : public BitField<bool, 3, 1> {};
9732 class IsShared : public BitField<bool, 4, 1> {};
9735 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
9739 class JSArrayBufferView: public JSObject {
9741 // [buffer]: ArrayBuffer that this typed array views.
9742 DECL_ACCESSORS(buffer, Object)
9744 // [byte_offset]: offset of typed array in bytes.
9745 DECL_ACCESSORS(byte_offset, Object)
9747 // [byte_length]: length of typed array in bytes.
9748 DECL_ACCESSORS(byte_length, Object)
9750 DECLARE_CAST(JSArrayBufferView)
9752 DECLARE_VERIFIER(JSArrayBufferView)
9754 inline bool WasNeutered() const;
9756 static const int kBufferOffset = JSObject::kHeaderSize;
9757 static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
9758 static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
9759 static const int kViewSize = kByteLengthOffset + kPointerSize;
9763 DECL_ACCESSORS(raw_byte_offset, Object)
9764 DECL_ACCESSORS(raw_byte_length, Object)
9767 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
9771 class JSTypedArray: public JSArrayBufferView {
9773 // [length]: length of typed array in elements.
9774 DECL_ACCESSORS(length, Object)
9775 inline uint32_t length_value() const;
9777 DECLARE_CAST(JSTypedArray)
9779 ExternalArrayType type();
9780 size_t element_size();
9782 Handle<JSArrayBuffer> GetBuffer();
9784 // Dispatched behavior.
9785 DECLARE_PRINTER(JSTypedArray)
9786 DECLARE_VERIFIER(JSTypedArray)
9788 static const int kLengthOffset = kViewSize + kPointerSize;
9789 static const int kSize = kLengthOffset + kPointerSize;
9791 static const int kSizeWithInternalFields =
9792 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9795 static Handle<JSArrayBuffer> MaterializeArrayBuffer(
9796 Handle<JSTypedArray> typed_array);
9798 DECL_ACCESSORS(raw_length, Object)
9801 DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
9805 class JSDataView: public JSArrayBufferView {
9807 DECLARE_CAST(JSDataView)
9809 // Dispatched behavior.
9810 DECLARE_PRINTER(JSDataView)
9811 DECLARE_VERIFIER(JSDataView)
9813 static const int kSize = kViewSize;
9815 static const int kSizeWithInternalFields =
9816 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9819 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
9823 // Foreign describes objects pointing from JavaScript to C structures.
9824 class Foreign: public HeapObject {
9826 // [address]: field containing the address.
9827 inline Address foreign_address();
9828 inline void set_foreign_address(Address value);
9830 DECLARE_CAST(Foreign)
9832 // Dispatched behavior.
9833 inline void ForeignIterateBody(ObjectVisitor* v);
9835 template<typename StaticVisitor>
9836 inline void ForeignIterateBody();
9838 // Dispatched behavior.
9839 DECLARE_PRINTER(Foreign)
9840 DECLARE_VERIFIER(Foreign)
9842 // Layout description.
9844 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
9845 static const int kSize = kForeignAddressOffset + kPointerSize;
9847 STATIC_ASSERT(kForeignAddressOffset == Internals::kForeignAddressOffset);
9850 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
9854 // The JSArray describes JavaScript Arrays
9855 // Such an array can be in one of two modes:
9856 // - fast, backing storage is a FixedArray and length <= elements.length();
9857 // Please note: push and pop can be used to grow and shrink the array.
9858 // - slow, backing storage is a HashTable with numbers as keys.
9859 class JSArray: public JSObject {
9861 // [length]: The length property.
9862 DECL_ACCESSORS(length, Object)
9864 // Overload the length setter to skip write barrier when the length
9865 // is set to a smi. This matches the set function on FixedArray.
9866 inline void set_length(Smi* length);
9868 static bool HasReadOnlyLength(Handle<JSArray> array);
9869 static bool WouldChangeReadOnlyLength(Handle<JSArray> array, uint32_t index);
9870 static MaybeHandle<Object> ReadOnlyLengthError(Handle<JSArray> array);
9872 // Initialize the array with the given capacity. The function may
9873 // fail due to out-of-memory situations, but only if the requested
9874 // capacity is non-zero.
9875 static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
9877 // If the JSArray has fast elements, and new_length would result in
9878 // normalization, returns true.
9879 bool SetLengthWouldNormalize(uint32_t new_length);
9880 static inline bool SetLengthWouldNormalize(Heap* heap, uint32_t new_length);
9882 // Initializes the array to a certain length.
9883 inline bool AllowsSetLength();
9885 static void SetLength(Handle<JSArray> array, uint32_t length);
9886 // Same as above but will also queue splice records if |array| is observed.
9887 static MaybeHandle<Object> ObservableSetLength(Handle<JSArray> array,
9890 // Set the content of the array to the content of storage.
9891 static inline void SetContent(Handle<JSArray> array,
9892 Handle<FixedArrayBase> storage);
9894 DECLARE_CAST(JSArray)
9896 // Dispatched behavior.
9897 DECLARE_PRINTER(JSArray)
9898 DECLARE_VERIFIER(JSArray)
9900 // Number of element slots to pre-allocate for an empty array.
9901 static const int kPreallocatedArrayElements = 4;
9903 // Layout description.
9904 static const int kLengthOffset = JSObject::kHeaderSize;
9905 static const int kSize = kLengthOffset + kPointerSize;
9908 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
9912 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
9913 Handle<Map> initial_map);
9916 // JSRegExpResult is just a JSArray with a specific initial map.
9917 // This initial map adds in-object properties for "index" and "input"
9918 // properties, as assigned by RegExp.prototype.exec, which allows
9919 // faster creation of RegExp exec results.
9920 // This class just holds constants used when creating the result.
9921 // After creation the result must be treated as a JSArray in all regards.
9922 class JSRegExpResult: public JSArray {
9924 // Offsets of object fields.
9925 static const int kIndexOffset = JSArray::kSize;
9926 static const int kInputOffset = kIndexOffset + kPointerSize;
9927 static const int kSize = kInputOffset + kPointerSize;
9928 // Indices of in-object properties.
9929 static const int kIndexIndex = 0;
9930 static const int kInputIndex = 1;
9932 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
9936 class AccessorInfo: public Struct {
9938 DECL_ACCESSORS(name, Object)
9939 DECL_ACCESSORS(flag, Smi)
9940 DECL_ACCESSORS(expected_receiver_type, Object)
9942 inline bool all_can_read();
9943 inline void set_all_can_read(bool value);
9945 inline bool all_can_write();
9946 inline void set_all_can_write(bool value);
9948 inline bool is_special_data_property();
9949 inline void set_is_special_data_property(bool value);
9951 inline PropertyAttributes property_attributes();
9952 inline void set_property_attributes(PropertyAttributes attributes);
9954 // Checks whether the given receiver is compatible with this accessor.
9955 static bool IsCompatibleReceiverMap(Isolate* isolate,
9956 Handle<AccessorInfo> info,
9958 inline bool IsCompatibleReceiver(Object* receiver);
9960 DECLARE_CAST(AccessorInfo)
9962 // Dispatched behavior.
9963 DECLARE_VERIFIER(AccessorInfo)
9965 // Append all descriptors to the array that are not already there.
9966 // Return number added.
9967 static int AppendUnique(Handle<Object> descriptors,
9968 Handle<FixedArray> array,
9969 int valid_descriptors);
9971 static const int kNameOffset = HeapObject::kHeaderSize;
9972 static const int kFlagOffset = kNameOffset + kPointerSize;
9973 static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
9974 static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
9977 inline bool HasExpectedReceiverType() {
9978 return expected_receiver_type()->IsFunctionTemplateInfo();
9980 // Bit positions in flag.
9981 static const int kAllCanReadBit = 0;
9982 static const int kAllCanWriteBit = 1;
9983 static const int kSpecialDataProperty = 2;
9984 class AttributesField : public BitField<PropertyAttributes, 3, 3> {};
9986 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
9990 // An accessor must have a getter, but can have no setter.
9992 // When setting a property, V8 searches accessors in prototypes.
9993 // If an accessor was found and it does not have a setter,
9994 // the request is ignored.
9996 // If the accessor in the prototype has the READ_ONLY property attribute, then
9997 // a new value is added to the derived object when the property is set.
9998 // This shadows the accessor in the prototype.
9999 class ExecutableAccessorInfo: public AccessorInfo {
10001 DECL_ACCESSORS(getter, Object)
10002 DECL_ACCESSORS(setter, Object)
10003 DECL_ACCESSORS(data, Object)
10005 DECLARE_CAST(ExecutableAccessorInfo)
10007 // Dispatched behavior.
10008 DECLARE_PRINTER(ExecutableAccessorInfo)
10009 DECLARE_VERIFIER(ExecutableAccessorInfo)
10011 static const int kGetterOffset = AccessorInfo::kSize;
10012 static const int kSetterOffset = kGetterOffset + kPointerSize;
10013 static const int kDataOffset = kSetterOffset + kPointerSize;
10014 static const int kSize = kDataOffset + kPointerSize;
10016 static void ClearSetter(Handle<ExecutableAccessorInfo> info);
10019 DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
10023 // Support for JavaScript accessors: A pair of a getter and a setter. Each
10024 // accessor can either be
10025 // * a pointer to a JavaScript function or proxy: a real accessor
10026 // * undefined: considered an accessor by the spec, too, strangely enough
10027 // * the hole: an accessor which has not been set
10028 // * a pointer to a map: a transition used to ensure map sharing
10029 class AccessorPair: public Struct {
10031 DECL_ACCESSORS(getter, Object)
10032 DECL_ACCESSORS(setter, Object)
10034 DECLARE_CAST(AccessorPair)
10036 static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
10038 Object* get(AccessorComponent component) {
10039 return component == ACCESSOR_GETTER ? getter() : setter();
10042 void set(AccessorComponent component, Object* value) {
10043 if (component == ACCESSOR_GETTER) {
10050 // Note: Returns undefined instead in case of a hole.
10051 Object* GetComponent(AccessorComponent component);
10053 // Set both components, skipping arguments which are a JavaScript null.
10054 void SetComponents(Object* getter, Object* setter) {
10055 if (!getter->IsNull()) set_getter(getter);
10056 if (!setter->IsNull()) set_setter(setter);
10059 bool Equals(AccessorPair* pair) {
10060 return (this == pair) || pair->Equals(getter(), setter());
10063 bool Equals(Object* getter_value, Object* setter_value) {
10064 return (getter() == getter_value) && (setter() == setter_value);
10067 bool ContainsAccessor() {
10068 return IsJSAccessor(getter()) || IsJSAccessor(setter());
10071 // Dispatched behavior.
10072 DECLARE_PRINTER(AccessorPair)
10073 DECLARE_VERIFIER(AccessorPair)
10075 static const int kGetterOffset = HeapObject::kHeaderSize;
10076 static const int kSetterOffset = kGetterOffset + kPointerSize;
10077 static const int kSize = kSetterOffset + kPointerSize;
10080 // Strangely enough, in addition to functions and harmony proxies, the spec
10081 // requires us to consider undefined as a kind of accessor, too:
10083 // Object.defineProperty(obj, "foo", {get: undefined});
10084 // assertTrue("foo" in obj);
10085 bool IsJSAccessor(Object* obj) {
10086 return obj->IsSpecFunction() || obj->IsUndefined();
10089 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
10093 class AccessCheckInfo: public Struct {
10095 DECL_ACCESSORS(named_callback, Object)
10096 DECL_ACCESSORS(indexed_callback, Object)
10097 DECL_ACCESSORS(data, Object)
10099 DECLARE_CAST(AccessCheckInfo)
10101 // Dispatched behavior.
10102 DECLARE_PRINTER(AccessCheckInfo)
10103 DECLARE_VERIFIER(AccessCheckInfo)
10105 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
10106 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
10107 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
10108 static const int kSize = kDataOffset + kPointerSize;
10111 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
10115 class InterceptorInfo: public Struct {
10117 DECL_ACCESSORS(getter, Object)
10118 DECL_ACCESSORS(setter, Object)
10119 DECL_ACCESSORS(query, Object)
10120 DECL_ACCESSORS(deleter, Object)
10121 DECL_ACCESSORS(enumerator, Object)
10122 DECL_ACCESSORS(data, Object)
10123 DECL_BOOLEAN_ACCESSORS(can_intercept_symbols)
10124 DECL_BOOLEAN_ACCESSORS(all_can_read)
10125 DECL_BOOLEAN_ACCESSORS(non_masking)
10127 inline int flags() const;
10128 inline void set_flags(int flags);
10130 DECLARE_CAST(InterceptorInfo)
10132 // Dispatched behavior.
10133 DECLARE_PRINTER(InterceptorInfo)
10134 DECLARE_VERIFIER(InterceptorInfo)
10136 static const int kGetterOffset = HeapObject::kHeaderSize;
10137 static const int kSetterOffset = kGetterOffset + kPointerSize;
10138 static const int kQueryOffset = kSetterOffset + kPointerSize;
10139 static const int kDeleterOffset = kQueryOffset + kPointerSize;
10140 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
10141 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
10142 static const int kFlagsOffset = kDataOffset + kPointerSize;
10143 static const int kSize = kFlagsOffset + kPointerSize;
10145 static const int kCanInterceptSymbolsBit = 0;
10146 static const int kAllCanReadBit = 1;
10147 static const int kNonMasking = 2;
10150 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
10154 class CallHandlerInfo: public Struct {
10156 DECL_ACCESSORS(callback, Object)
10157 DECL_ACCESSORS(data, Object)
10159 DECLARE_CAST(CallHandlerInfo)
10161 // Dispatched behavior.
10162 DECLARE_PRINTER(CallHandlerInfo)
10163 DECLARE_VERIFIER(CallHandlerInfo)
10165 static const int kCallbackOffset = HeapObject::kHeaderSize;
10166 static const int kDataOffset = kCallbackOffset + kPointerSize;
10167 static const int kSize = kDataOffset + kPointerSize;
10170 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
10174 class TemplateInfo: public Struct {
10176 DECL_ACCESSORS(tag, Object)
10177 inline int number_of_properties() const;
10178 inline void set_number_of_properties(int value);
10179 DECL_ACCESSORS(property_list, Object)
10180 DECL_ACCESSORS(property_accessors, Object)
10182 DECLARE_VERIFIER(TemplateInfo)
10184 static const int kTagOffset = HeapObject::kHeaderSize;
10185 static const int kNumberOfProperties = kTagOffset + kPointerSize;
10186 static const int kPropertyListOffset = kNumberOfProperties + kPointerSize;
10187 static const int kPropertyAccessorsOffset =
10188 kPropertyListOffset + kPointerSize;
10189 static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
10192 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
10196 class FunctionTemplateInfo: public TemplateInfo {
10198 DECL_ACCESSORS(serial_number, Object)
10199 DECL_ACCESSORS(call_code, Object)
10200 DECL_ACCESSORS(prototype_template, Object)
10201 DECL_ACCESSORS(parent_template, Object)
10202 DECL_ACCESSORS(named_property_handler, Object)
10203 DECL_ACCESSORS(indexed_property_handler, Object)
10204 DECL_ACCESSORS(instance_template, Object)
10205 DECL_ACCESSORS(class_name, Object)
10206 DECL_ACCESSORS(signature, Object)
10207 DECL_ACCESSORS(instance_call_handler, Object)
10208 DECL_ACCESSORS(access_check_info, Object)
10209 DECL_ACCESSORS(flag, Smi)
10211 inline int length() const;
10212 inline void set_length(int value);
10214 // Following properties use flag bits.
10215 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
10216 DECL_BOOLEAN_ACCESSORS(undetectable)
10217 // If the bit is set, object instances created by this function
10218 // requires access check.
10219 DECL_BOOLEAN_ACCESSORS(needs_access_check)
10220 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
10221 DECL_BOOLEAN_ACCESSORS(remove_prototype)
10222 DECL_BOOLEAN_ACCESSORS(do_not_cache)
10223 DECL_BOOLEAN_ACCESSORS(instantiated)
10224 DECL_BOOLEAN_ACCESSORS(accept_any_receiver)
10226 DECLARE_CAST(FunctionTemplateInfo)
10228 // Dispatched behavior.
10229 DECLARE_PRINTER(FunctionTemplateInfo)
10230 DECLARE_VERIFIER(FunctionTemplateInfo)
10232 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
10233 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
10234 static const int kPrototypeTemplateOffset =
10235 kCallCodeOffset + kPointerSize;
10236 static const int kParentTemplateOffset =
10237 kPrototypeTemplateOffset + kPointerSize;
10238 static const int kNamedPropertyHandlerOffset =
10239 kParentTemplateOffset + kPointerSize;
10240 static const int kIndexedPropertyHandlerOffset =
10241 kNamedPropertyHandlerOffset + kPointerSize;
10242 static const int kInstanceTemplateOffset =
10243 kIndexedPropertyHandlerOffset + kPointerSize;
10244 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
10245 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
10246 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
10247 static const int kAccessCheckInfoOffset =
10248 kInstanceCallHandlerOffset + kPointerSize;
10249 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
10250 static const int kLengthOffset = kFlagOffset + kPointerSize;
10251 static const int kSize = kLengthOffset + kPointerSize;
10253 // Returns true if |object| is an instance of this function template.
10254 bool IsTemplateFor(Object* object);
10255 bool IsTemplateFor(Map* map);
10257 // Returns the holder JSObject if the function can legally be called with this
10258 // receiver. Returns Heap::null_value() if the call is illegal.
10259 Object* GetCompatibleReceiver(Isolate* isolate, Object* receiver);
10262 // Bit position in the flag, from least significant bit position.
10263 static const int kHiddenPrototypeBit = 0;
10264 static const int kUndetectableBit = 1;
10265 static const int kNeedsAccessCheckBit = 2;
10266 static const int kReadOnlyPrototypeBit = 3;
10267 static const int kRemovePrototypeBit = 4;
10268 static const int kDoNotCacheBit = 5;
10269 static const int kInstantiatedBit = 6;
10270 static const int kAcceptAnyReceiver = 7;
10272 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
10276 class ObjectTemplateInfo: public TemplateInfo {
10278 DECL_ACCESSORS(constructor, Object)
10279 DECL_ACCESSORS(internal_field_count, Object)
10281 DECLARE_CAST(ObjectTemplateInfo)
10283 // Dispatched behavior.
10284 DECLARE_PRINTER(ObjectTemplateInfo)
10285 DECLARE_VERIFIER(ObjectTemplateInfo)
10287 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10288 static const int kInternalFieldCountOffset =
10289 kConstructorOffset + kPointerSize;
10290 static const int kSize = kInternalFieldCountOffset + kPointerSize;
10294 class TypeSwitchInfo: public Struct {
10296 DECL_ACCESSORS(types, Object)
10298 DECLARE_CAST(TypeSwitchInfo)
10300 // Dispatched behavior.
10301 DECLARE_PRINTER(TypeSwitchInfo)
10302 DECLARE_VERIFIER(TypeSwitchInfo)
10304 static const int kTypesOffset = Struct::kHeaderSize;
10305 static const int kSize = kTypesOffset + kPointerSize;
10309 // The DebugInfo class holds additional information for a function being
10311 class DebugInfo: public Struct {
10313 // The shared function info for the source being debugged.
10314 DECL_ACCESSORS(shared, SharedFunctionInfo)
10315 // Code object for the patched code. This code object is the code object
10316 // currently active for the function.
10317 DECL_ACCESSORS(code, Code)
10318 // Fixed array holding status information for each active break point.
10319 DECL_ACCESSORS(break_points, FixedArray)
10321 // Check if there is a break point at a code position.
10322 bool HasBreakPoint(int code_position);
10323 // Get the break point info object for a code position.
10324 Object* GetBreakPointInfo(int code_position);
10325 // Clear a break point.
10326 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
10328 Handle<Object> break_point_object);
10329 // Set a break point.
10330 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
10331 int source_position, int statement_position,
10332 Handle<Object> break_point_object);
10333 // Get the break point objects for a code position.
10334 Handle<Object> GetBreakPointObjects(int code_position);
10335 // Find the break point info holding this break point object.
10336 static Handle<Object> FindBreakPointInfo(Handle<DebugInfo> debug_info,
10337 Handle<Object> break_point_object);
10338 // Get the number of break points for this function.
10339 int GetBreakPointCount();
10341 DECLARE_CAST(DebugInfo)
10343 // Dispatched behavior.
10344 DECLARE_PRINTER(DebugInfo)
10345 DECLARE_VERIFIER(DebugInfo)
10347 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
10348 static const int kCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
10349 static const int kBreakPointsStateIndex = kCodeIndex + kPointerSize;
10350 static const int kSize = kBreakPointsStateIndex + kPointerSize;
10352 static const int kEstimatedNofBreakPointsInFunction = 16;
10355 static const int kNoBreakPointInfo = -1;
10357 // Lookup the index in the break_points array for a code position.
10358 int GetBreakPointInfoIndex(int code_position);
10360 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
10364 // The BreakPointInfo class holds information for break points set in a
10365 // function. The DebugInfo object holds a BreakPointInfo object for each code
10366 // position with one or more break points.
10367 class BreakPointInfo: public Struct {
10369 // The position in the code for the break point.
10370 DECL_ACCESSORS(code_position, Smi)
10371 // The position in the source for the break position.
10372 DECL_ACCESSORS(source_position, Smi)
10373 // The position in the source for the last statement before this break
10375 DECL_ACCESSORS(statement_position, Smi)
10376 // List of related JavaScript break points.
10377 DECL_ACCESSORS(break_point_objects, Object)
10379 // Removes a break point.
10380 static void ClearBreakPoint(Handle<BreakPointInfo> info,
10381 Handle<Object> break_point_object);
10382 // Set a break point.
10383 static void SetBreakPoint(Handle<BreakPointInfo> info,
10384 Handle<Object> break_point_object);
10385 // Check if break point info has this break point object.
10386 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
10387 Handle<Object> break_point_object);
10388 // Get the number of break points for this code position.
10389 int GetBreakPointCount();
10391 DECLARE_CAST(BreakPointInfo)
10393 // Dispatched behavior.
10394 DECLARE_PRINTER(BreakPointInfo)
10395 DECLARE_VERIFIER(BreakPointInfo)
10397 static const int kCodePositionIndex = Struct::kHeaderSize;
10398 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
10399 static const int kStatementPositionIndex =
10400 kSourcePositionIndex + kPointerSize;
10401 static const int kBreakPointObjectsIndex =
10402 kStatementPositionIndex + kPointerSize;
10403 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
10406 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
10410 #undef DECL_BOOLEAN_ACCESSORS
10411 #undef DECL_ACCESSORS
10412 #undef DECLARE_CAST
10413 #undef DECLARE_VERIFIER
10415 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
10416 V(kStringTable, "string_table", "(Internalized strings)") \
10417 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
10418 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
10419 V(kSmiRootList, "smi_root_list", "(Smi roots)") \
10420 V(kInternalizedString, "internalized_string", "(Internal string)") \
10421 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
10422 V(kTop, "top", "(Isolate)") \
10423 V(kRelocatable, "relocatable", "(Relocatable)") \
10424 V(kDebug, "debug", "(Debugger)") \
10425 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
10426 V(kHandleScope, "handlescope", "(Handle scope)") \
10427 V(kBuiltins, "builtins", "(Builtins)") \
10428 V(kGlobalHandles, "globalhandles", "(Global handles)") \
10429 V(kEternalHandles, "eternalhandles", "(Eternal handles)") \
10430 V(kThreadManager, "threadmanager", "(Thread manager)") \
10431 V(kStrongRoots, "strong roots", "(Strong roots)") \
10432 V(kExtensions, "Extensions", "(Extensions)")
10434 class VisitorSynchronization : public AllStatic {
10436 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
10438 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
10441 #undef DECLARE_ENUM
10443 static const char* const kTags[kNumberOfSyncTags];
10444 static const char* const kTagNames[kNumberOfSyncTags];
10447 // Abstract base class for visiting, and optionally modifying, the
10448 // pointers contained in Objects. Used in GC and serialization/deserialization.
10449 class ObjectVisitor BASE_EMBEDDED {
10451 virtual ~ObjectVisitor() {}
10453 // Visits a contiguous arrays of pointers in the half-open range
10454 // [start, end). Any or all of the values may be modified on return.
10455 virtual void VisitPointers(Object** start, Object** end) = 0;
10457 // Handy shorthand for visiting a single pointer.
10458 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
10460 // Visit weak next_code_link in Code object.
10461 virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
10463 // To allow lazy clearing of inline caches the visitor has
10464 // a rich interface for iterating over Code objects..
10466 // Visits a code target in the instruction stream.
10467 virtual void VisitCodeTarget(RelocInfo* rinfo);
10469 // Visits a code entry in a JS function.
10470 virtual void VisitCodeEntry(Address entry_address);
10472 // Visits a global property cell reference in the instruction stream.
10473 virtual void VisitCell(RelocInfo* rinfo);
10475 // Visits a runtime entry in the instruction stream.
10476 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
10478 // Visits the resource of an one-byte or two-byte string.
10479 virtual void VisitExternalOneByteString(
10480 v8::String::ExternalOneByteStringResource** resource) {}
10481 virtual void VisitExternalTwoByteString(
10482 v8::String::ExternalStringResource** resource) {}
10484 // Visits a debug call target in the instruction stream.
10485 virtual void VisitDebugTarget(RelocInfo* rinfo);
10487 // Visits the byte sequence in a function's prologue that contains information
10488 // about the code's age.
10489 virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
10491 // Visit pointer embedded into a code object.
10492 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
10494 // Visits an external reference embedded into a code object.
10495 virtual void VisitExternalReference(RelocInfo* rinfo);
10497 // Visits an external reference.
10498 virtual void VisitExternalReference(Address* p) {}
10500 // Visits an (encoded) internal reference.
10501 virtual void VisitInternalReference(RelocInfo* rinfo) {}
10503 // Visits a handle that has an embedder-assigned class ID.
10504 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
10506 // Intended for serialization/deserialization checking: insert, or
10507 // check for the presence of, a tag at this position in the stream.
10508 // Also used for marking up GC roots in heap snapshots.
10509 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
10513 class StructBodyDescriptor : public
10514 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
10516 static inline int SizeOf(Map* map, HeapObject* object) {
10517 return map->instance_size();
10522 // BooleanBit is a helper class for setting and getting a bit in an
10524 class BooleanBit : public AllStatic {
10526 static inline bool get(Smi* smi, int bit_position) {
10527 return get(smi->value(), bit_position);
10530 static inline bool get(int value, int bit_position) {
10531 return (value & (1 << bit_position)) != 0;
10534 static inline Smi* set(Smi* smi, int bit_position, bool v) {
10535 return Smi::FromInt(set(smi->value(), bit_position, v));
10538 static inline int set(int value, int bit_position, bool v) {
10540 value |= (1 << bit_position);
10542 value &= ~(1 << bit_position);
10548 } } // namespace v8::internal
10550 #endif // V8_OBJECTS_H_