1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
10 #include "src/allocation.h"
11 #include "src/assert-scope.h"
12 #include "src/bailout-reason.h"
13 #include "src/base/bits.h"
14 #include "src/base/smart-pointers.h"
15 #include "src/builtins.h"
16 #include "src/checks.h"
17 #include "src/elements-kind.h"
18 #include "src/field-index.h"
19 #include "src/flags.h"
21 #include "src/property-details.h"
22 #include "src/unicode-inl.h"
23 #include "src/unicode-decoder.h"
26 #if V8_TARGET_ARCH_ARM
27 #include "src/arm/constants-arm.h" // NOLINT
28 #elif V8_TARGET_ARCH_ARM64
29 #include "src/arm64/constants-arm64.h" // NOLINT
30 #elif V8_TARGET_ARCH_MIPS
31 #include "src/mips/constants-mips.h" // NOLINT
32 #elif V8_TARGET_ARCH_MIPS64
33 #include "src/mips64/constants-mips64.h" // NOLINT
34 #elif V8_TARGET_ARCH_PPC
35 #include "src/ppc/constants-ppc.h" // NOLINT
40 // Most object types in the V8 JavaScript are described in this file.
42 // Inheritance hierarchy:
44 // - Smi (immediate small integer)
45 // - HeapObject (superclass for everything allocated in the heap)
46 // - JSReceiver (suitable for property access)
50 // - JSArrayBufferView
63 // - JSGeneratorObject
82 // - CompilationCacheTable
83 // - CodeCacheHashTable
89 // - TypeFeedbackVector
92 // - ScriptContextTable
103 // - ExternalOneByteString
104 // - ExternalTwoByteString
105 // - InternalizedString
106 // - SeqInternalizedString
107 // - SeqOneByteInternalizedString
108 // - SeqTwoByteInternalizedString
109 // - ConsInternalizedString
110 // - ExternalInternalizedString
111 // - ExternalOneByteInternalizedString
112 // - ExternalTwoByteInternalizedString
129 // - SharedFunctionInfo
133 // - ExecutableAccessorInfo
139 // - FunctionTemplateInfo
140 // - ObjectTemplateInfo
149 // Formats of Object*:
150 // Smi: [31 bit signed int] 0
151 // HeapObject: [32 bit direct pointer] (4 byte aligned) | 01
156 enum KeyedAccessStoreMode {
158 STORE_TRANSITION_SMI_TO_OBJECT,
159 STORE_TRANSITION_SMI_TO_DOUBLE,
160 STORE_TRANSITION_DOUBLE_TO_OBJECT,
161 STORE_TRANSITION_HOLEY_SMI_TO_OBJECT,
162 STORE_TRANSITION_HOLEY_SMI_TO_DOUBLE,
163 STORE_TRANSITION_HOLEY_DOUBLE_TO_OBJECT,
164 STORE_AND_GROW_NO_TRANSITION,
165 STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT,
166 STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE,
167 STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT,
168 STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_OBJECT,
169 STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_DOUBLE,
170 STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT,
171 STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS,
172 STORE_NO_TRANSITION_HANDLE_COW
176 enum TypeofMode { INSIDE_TYPEOF, NOT_INSIDE_TYPEOF };
185 enum ExternalArrayType {
186 kExternalInt8Array = 1,
189 kExternalUint16Array,
191 kExternalUint32Array,
192 kExternalFloat32Array,
193 kExternalFloat64Array,
194 kExternalUint8ClampedArray,
198 static const int kGrowICDelta = STORE_AND_GROW_NO_TRANSITION -
200 STATIC_ASSERT(STANDARD_STORE == 0);
201 STATIC_ASSERT(kGrowICDelta ==
202 STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT -
203 STORE_TRANSITION_SMI_TO_OBJECT);
204 STATIC_ASSERT(kGrowICDelta ==
205 STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE -
206 STORE_TRANSITION_SMI_TO_DOUBLE);
207 STATIC_ASSERT(kGrowICDelta ==
208 STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT -
209 STORE_TRANSITION_DOUBLE_TO_OBJECT);
212 static inline KeyedAccessStoreMode GetGrowStoreMode(
213 KeyedAccessStoreMode store_mode) {
214 if (store_mode < STORE_AND_GROW_NO_TRANSITION) {
215 store_mode = static_cast<KeyedAccessStoreMode>(
216 static_cast<int>(store_mode) + kGrowICDelta);
222 static inline bool IsTransitionStoreMode(KeyedAccessStoreMode store_mode) {
223 return store_mode > STANDARD_STORE &&
224 store_mode <= STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT &&
225 store_mode != STORE_AND_GROW_NO_TRANSITION;
229 static inline KeyedAccessStoreMode GetNonTransitioningStoreMode(
230 KeyedAccessStoreMode store_mode) {
231 if (store_mode >= STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS) {
234 if (store_mode >= STORE_AND_GROW_NO_TRANSITION) {
235 return STORE_AND_GROW_NO_TRANSITION;
237 return STANDARD_STORE;
241 static inline bool IsGrowStoreMode(KeyedAccessStoreMode store_mode) {
242 return store_mode >= STORE_AND_GROW_NO_TRANSITION &&
243 store_mode <= STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT;
247 enum IcCheckType { ELEMENT, PROPERTY };
250 // SKIP_WRITE_BARRIER skips the write barrier.
251 // UPDATE_WEAK_WRITE_BARRIER skips the marking part of the write barrier and
252 // only performs the generational part.
253 // UPDATE_WRITE_BARRIER is doing the full barrier, marking and generational.
254 enum WriteBarrierMode {
256 UPDATE_WEAK_WRITE_BARRIER,
261 // Indicates whether a value can be loaded as a constant.
262 enum StoreMode { ALLOW_IN_DESCRIPTOR, FORCE_FIELD };
265 // PropertyNormalizationMode is used to specify whether to keep
266 // inobject properties when normalizing properties of a JSObject.
267 enum PropertyNormalizationMode {
268 CLEAR_INOBJECT_PROPERTIES,
269 KEEP_INOBJECT_PROPERTIES
273 // Indicates how aggressively the prototype should be optimized. FAST_PROTOTYPE
274 // will give the fastest result by tailoring the map to the prototype, but that
275 // will cause polymorphism with other objects. REGULAR_PROTOTYPE is to be used
276 // (at least for now) when dynamically modifying the prototype chain of an
277 // object using __proto__ or Object.setPrototypeOf.
278 enum PrototypeOptimizationMode { REGULAR_PROTOTYPE, FAST_PROTOTYPE };
281 // Indicates whether transitions can be added to a source map or not.
282 enum TransitionFlag {
288 // Indicates whether the transition is simple: the target map of the transition
289 // either extends the current map with a new property, or it modifies the
290 // property that was added last to the current map.
291 enum SimpleTransitionFlag {
292 SIMPLE_PROPERTY_TRANSITION,
298 // Indicates whether we are only interested in the descriptors of a particular
299 // map, or in all descriptors in the descriptor array.
300 enum DescriptorFlag {
305 // The GC maintains a bit of information, the MarkingParity, which toggles
306 // from odd to even and back every time marking is completed. Incremental
307 // marking can visit an object twice during a marking phase, so algorithms that
308 // that piggy-back on marking can use the parity to ensure that they only
309 // perform an operation on an object once per marking phase: they record the
310 // MarkingParity when they visit an object, and only re-visit the object when it
311 // is marked again and the MarkingParity changes.
318 // ICs store extra state in a Code object. The default extra state is
320 typedef int ExtraICState;
321 static const ExtraICState kNoExtraICState = 0;
323 // Instance size sentinel for objects of variable size.
324 const int kVariableSizeSentinel = 0;
326 // We may store the unsigned bit field as signed Smi value and do not
328 const int kStubMajorKeyBits = 7;
329 const int kStubMinorKeyBits = kSmiValueSize - kStubMajorKeyBits - 1;
331 // All Maps have a field instance_type containing a InstanceType.
332 // It describes the type of the instances.
334 // As an example, a JavaScript object is a heap object and its map
335 // instance_type is JS_OBJECT_TYPE.
337 // The names of the string instance types are intended to systematically
338 // mirror their encoding in the instance_type field of the map. The default
339 // encoding is considered TWO_BYTE. It is not mentioned in the name. ONE_BYTE
340 // encoding is mentioned explicitly in the name. Likewise, the default
341 // representation is considered sequential. It is not mentioned in the
342 // name. The other representations (e.g. CONS, EXTERNAL) are explicitly
343 // mentioned. Finally, the string is either a STRING_TYPE (if it is a normal
344 // string) or a INTERNALIZED_STRING_TYPE (if it is a internalized string).
346 // NOTE: The following things are some that depend on the string types having
347 // instance_types that are less than those of all other types:
348 // HeapObject::Size, HeapObject::IterateBody, the typeof operator, and
351 // NOTE: Everything following JS_VALUE_TYPE is considered a
352 // JSObject for GC purposes. The first four entries here have typeof
353 // 'object', whereas JS_FUNCTION_TYPE has typeof 'function'.
354 #define INSTANCE_TYPE_LIST(V) \
356 V(ONE_BYTE_STRING_TYPE) \
357 V(CONS_STRING_TYPE) \
358 V(CONS_ONE_BYTE_STRING_TYPE) \
359 V(SLICED_STRING_TYPE) \
360 V(SLICED_ONE_BYTE_STRING_TYPE) \
361 V(EXTERNAL_STRING_TYPE) \
362 V(EXTERNAL_ONE_BYTE_STRING_TYPE) \
363 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
364 V(SHORT_EXTERNAL_STRING_TYPE) \
365 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE) \
366 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
368 V(INTERNALIZED_STRING_TYPE) \
369 V(ONE_BYTE_INTERNALIZED_STRING_TYPE) \
370 V(EXTERNAL_INTERNALIZED_STRING_TYPE) \
371 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
372 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
373 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE) \
374 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
375 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
378 V(SIMD128_VALUE_TYPE) \
384 V(PROPERTY_CELL_TYPE) \
386 V(HEAP_NUMBER_TYPE) \
387 V(MUTABLE_HEAP_NUMBER_TYPE) \
390 V(BYTECODE_ARRAY_TYPE) \
393 V(FIXED_INT8_ARRAY_TYPE) \
394 V(FIXED_UINT8_ARRAY_TYPE) \
395 V(FIXED_INT16_ARRAY_TYPE) \
396 V(FIXED_UINT16_ARRAY_TYPE) \
397 V(FIXED_INT32_ARRAY_TYPE) \
398 V(FIXED_UINT32_ARRAY_TYPE) \
399 V(FIXED_FLOAT32_ARRAY_TYPE) \
400 V(FIXED_FLOAT64_ARRAY_TYPE) \
401 V(FIXED_UINT8_CLAMPED_ARRAY_TYPE) \
405 V(DECLARED_ACCESSOR_DESCRIPTOR_TYPE) \
406 V(DECLARED_ACCESSOR_INFO_TYPE) \
407 V(EXECUTABLE_ACCESSOR_INFO_TYPE) \
408 V(ACCESSOR_PAIR_TYPE) \
409 V(ACCESS_CHECK_INFO_TYPE) \
410 V(INTERCEPTOR_INFO_TYPE) \
411 V(CALL_HANDLER_INFO_TYPE) \
412 V(FUNCTION_TEMPLATE_INFO_TYPE) \
413 V(OBJECT_TEMPLATE_INFO_TYPE) \
414 V(SIGNATURE_INFO_TYPE) \
415 V(TYPE_SWITCH_INFO_TYPE) \
416 V(ALLOCATION_MEMENTO_TYPE) \
417 V(ALLOCATION_SITE_TYPE) \
420 V(POLYMORPHIC_CODE_CACHE_TYPE) \
421 V(TYPE_FEEDBACK_INFO_TYPE) \
422 V(ALIASED_ARGUMENTS_ENTRY_TYPE) \
424 V(PROTOTYPE_INFO_TYPE) \
426 V(FIXED_ARRAY_TYPE) \
427 V(FIXED_DOUBLE_ARRAY_TYPE) \
428 V(SHARED_FUNCTION_INFO_TYPE) \
431 V(JS_MESSAGE_OBJECT_TYPE) \
436 V(JS_CONTEXT_EXTENSION_OBJECT_TYPE) \
437 V(JS_GENERATOR_OBJECT_TYPE) \
439 V(JS_GLOBAL_OBJECT_TYPE) \
440 V(JS_BUILTINS_OBJECT_TYPE) \
441 V(JS_GLOBAL_PROXY_TYPE) \
443 V(JS_ARRAY_BUFFER_TYPE) \
444 V(JS_TYPED_ARRAY_TYPE) \
445 V(JS_DATA_VIEW_TYPE) \
449 V(JS_SET_ITERATOR_TYPE) \
450 V(JS_MAP_ITERATOR_TYPE) \
451 V(JS_WEAK_MAP_TYPE) \
452 V(JS_WEAK_SET_TYPE) \
455 V(JS_FUNCTION_TYPE) \
456 V(JS_FUNCTION_PROXY_TYPE) \
458 V(BREAK_POINT_INFO_TYPE)
461 // Since string types are not consecutive, this macro is used to
462 // iterate over them.
463 #define STRING_TYPE_LIST(V) \
464 V(STRING_TYPE, kVariableSizeSentinel, string, String) \
465 V(ONE_BYTE_STRING_TYPE, kVariableSizeSentinel, one_byte_string, \
467 V(CONS_STRING_TYPE, ConsString::kSize, cons_string, ConsString) \
468 V(CONS_ONE_BYTE_STRING_TYPE, ConsString::kSize, cons_one_byte_string, \
470 V(SLICED_STRING_TYPE, SlicedString::kSize, sliced_string, SlicedString) \
471 V(SLICED_ONE_BYTE_STRING_TYPE, SlicedString::kSize, sliced_one_byte_string, \
472 SlicedOneByteString) \
473 V(EXTERNAL_STRING_TYPE, ExternalTwoByteString::kSize, external_string, \
475 V(EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kSize, \
476 external_one_byte_string, ExternalOneByteString) \
477 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, ExternalTwoByteString::kSize, \
478 external_string_with_one_byte_data, ExternalStringWithOneByteData) \
479 V(SHORT_EXTERNAL_STRING_TYPE, ExternalTwoByteString::kShortSize, \
480 short_external_string, ShortExternalString) \
481 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kShortSize, \
482 short_external_one_byte_string, ShortExternalOneByteString) \
483 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, \
484 ExternalTwoByteString::kShortSize, \
485 short_external_string_with_one_byte_data, \
486 ShortExternalStringWithOneByteData) \
488 V(INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, internalized_string, \
489 InternalizedString) \
490 V(ONE_BYTE_INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, \
491 one_byte_internalized_string, OneByteInternalizedString) \
492 V(EXTERNAL_INTERNALIZED_STRING_TYPE, ExternalTwoByteString::kSize, \
493 external_internalized_string, ExternalInternalizedString) \
494 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, ExternalOneByteString::kSize, \
495 external_one_byte_internalized_string, ExternalOneByteInternalizedString) \
496 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
497 ExternalTwoByteString::kSize, \
498 external_internalized_string_with_one_byte_data, \
499 ExternalInternalizedStringWithOneByteData) \
500 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE, \
501 ExternalTwoByteString::kShortSize, short_external_internalized_string, \
502 ShortExternalInternalizedString) \
503 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, \
504 ExternalOneByteString::kShortSize, \
505 short_external_one_byte_internalized_string, \
506 ShortExternalOneByteInternalizedString) \
507 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
508 ExternalTwoByteString::kShortSize, \
509 short_external_internalized_string_with_one_byte_data, \
510 ShortExternalInternalizedStringWithOneByteData)
512 // A struct is a simple object a set of object-valued fields. Including an
513 // object type in this causes the compiler to generate most of the boilerplate
514 // code for the class including allocation and garbage collection routines,
515 // casts and predicates. All you need to define is the class, methods and
516 // object verification routines. Easy, no?
518 // Note that for subtle reasons related to the ordering or numerical values of
519 // type tags, elements in this list have to be added to the INSTANCE_TYPE_LIST
521 #define STRUCT_LIST(V) \
523 V(EXECUTABLE_ACCESSOR_INFO, ExecutableAccessorInfo, \
524 executable_accessor_info) \
525 V(ACCESSOR_PAIR, AccessorPair, accessor_pair) \
526 V(ACCESS_CHECK_INFO, AccessCheckInfo, access_check_info) \
527 V(INTERCEPTOR_INFO, InterceptorInfo, interceptor_info) \
528 V(CALL_HANDLER_INFO, CallHandlerInfo, call_handler_info) \
529 V(FUNCTION_TEMPLATE_INFO, FunctionTemplateInfo, function_template_info) \
530 V(OBJECT_TEMPLATE_INFO, ObjectTemplateInfo, object_template_info) \
531 V(TYPE_SWITCH_INFO, TypeSwitchInfo, type_switch_info) \
532 V(SCRIPT, Script, script) \
533 V(ALLOCATION_SITE, AllocationSite, allocation_site) \
534 V(ALLOCATION_MEMENTO, AllocationMemento, allocation_memento) \
535 V(CODE_CACHE, CodeCache, code_cache) \
536 V(POLYMORPHIC_CODE_CACHE, PolymorphicCodeCache, polymorphic_code_cache) \
537 V(TYPE_FEEDBACK_INFO, TypeFeedbackInfo, type_feedback_info) \
538 V(ALIASED_ARGUMENTS_ENTRY, AliasedArgumentsEntry, aliased_arguments_entry) \
539 V(DEBUG_INFO, DebugInfo, debug_info) \
540 V(BREAK_POINT_INFO, BreakPointInfo, break_point_info) \
541 V(PROTOTYPE_INFO, PrototypeInfo, prototype_info)
543 // We use the full 8 bits of the instance_type field to encode heap object
544 // instance types. The high-order bit (bit 7) is set if the object is not a
545 // string, and cleared if it is a string.
546 const uint32_t kIsNotStringMask = 0x80;
547 const uint32_t kStringTag = 0x0;
548 const uint32_t kNotStringTag = 0x80;
550 // Bit 6 indicates that the object is an internalized string (if set) or not.
551 // Bit 7 has to be clear as well.
552 const uint32_t kIsNotInternalizedMask = 0x40;
553 const uint32_t kNotInternalizedTag = 0x40;
554 const uint32_t kInternalizedTag = 0x0;
556 // If bit 7 is clear then bit 2 indicates whether the string consists of
557 // two-byte characters or one-byte characters.
558 const uint32_t kStringEncodingMask = 0x4;
559 const uint32_t kTwoByteStringTag = 0x0;
560 const uint32_t kOneByteStringTag = 0x4;
562 // If bit 7 is clear, the low-order 2 bits indicate the representation
564 const uint32_t kStringRepresentationMask = 0x03;
565 enum StringRepresentationTag {
567 kConsStringTag = 0x1,
568 kExternalStringTag = 0x2,
569 kSlicedStringTag = 0x3
571 const uint32_t kIsIndirectStringMask = 0x1;
572 const uint32_t kIsIndirectStringTag = 0x1;
573 STATIC_ASSERT((kSeqStringTag & kIsIndirectStringMask) == 0); // NOLINT
574 STATIC_ASSERT((kExternalStringTag & kIsIndirectStringMask) == 0); // NOLINT
575 STATIC_ASSERT((kConsStringTag &
576 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
577 STATIC_ASSERT((kSlicedStringTag &
578 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
580 // Use this mask to distinguish between cons and slice only after making
581 // sure that the string is one of the two (an indirect string).
582 const uint32_t kSlicedNotConsMask = kSlicedStringTag & ~kConsStringTag;
583 STATIC_ASSERT(IS_POWER_OF_TWO(kSlicedNotConsMask));
585 // If bit 7 is clear, then bit 3 indicates whether this two-byte
586 // string actually contains one byte data.
587 const uint32_t kOneByteDataHintMask = 0x08;
588 const uint32_t kOneByteDataHintTag = 0x08;
590 // If bit 7 is clear and string representation indicates an external string,
591 // then bit 4 indicates whether the data pointer is cached.
592 const uint32_t kShortExternalStringMask = 0x10;
593 const uint32_t kShortExternalStringTag = 0x10;
596 // A ConsString with an empty string as the right side is a candidate
597 // for being shortcut by the garbage collector. We don't allocate any
598 // non-flat internalized strings, so we do not shortcut them thereby
599 // avoiding turning internalized strings into strings. The bit-masks
600 // below contain the internalized bit as additional safety.
601 // See heap.cc, mark-compact.cc and objects-visiting.cc.
602 const uint32_t kShortcutTypeMask =
604 kIsNotInternalizedMask |
605 kStringRepresentationMask;
606 const uint32_t kShortcutTypeTag = kConsStringTag | kNotInternalizedTag;
608 static inline bool IsShortcutCandidate(int type) {
609 return ((type & kShortcutTypeMask) == kShortcutTypeTag);
615 INTERNALIZED_STRING_TYPE = kTwoByteStringTag | kSeqStringTag |
616 kInternalizedTag, // FIRST_PRIMITIVE_TYPE
617 ONE_BYTE_INTERNALIZED_STRING_TYPE =
618 kOneByteStringTag | kSeqStringTag | kInternalizedTag,
619 EXTERNAL_INTERNALIZED_STRING_TYPE =
620 kTwoByteStringTag | kExternalStringTag | kInternalizedTag,
621 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
622 kOneByteStringTag | kExternalStringTag | kInternalizedTag,
623 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
624 EXTERNAL_INTERNALIZED_STRING_TYPE | kOneByteDataHintTag |
626 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE = EXTERNAL_INTERNALIZED_STRING_TYPE |
627 kShortExternalStringTag |
629 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
630 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kShortExternalStringTag |
632 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
633 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
634 kShortExternalStringTag | kInternalizedTag,
635 STRING_TYPE = INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
636 ONE_BYTE_STRING_TYPE =
637 ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
638 CONS_STRING_TYPE = kTwoByteStringTag | kConsStringTag | kNotInternalizedTag,
639 CONS_ONE_BYTE_STRING_TYPE =
640 kOneByteStringTag | kConsStringTag | kNotInternalizedTag,
642 kTwoByteStringTag | kSlicedStringTag | kNotInternalizedTag,
643 SLICED_ONE_BYTE_STRING_TYPE =
644 kOneByteStringTag | kSlicedStringTag | kNotInternalizedTag,
645 EXTERNAL_STRING_TYPE =
646 EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
647 EXTERNAL_ONE_BYTE_STRING_TYPE =
648 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
649 EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
650 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
652 SHORT_EXTERNAL_STRING_TYPE =
653 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
654 SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE =
655 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
656 SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
657 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
661 SYMBOL_TYPE = kNotStringTag, // FIRST_NONSTRING_TYPE, LAST_NAME_TYPE
663 // Other primitives (cannot contain non-map-word pointers to heap objects).
666 ODDBALL_TYPE, // LAST_PRIMITIVE_TYPE
668 // Objects allocated in their own spaces (never in new space).
672 // "Data", objects that cannot contain non-map-word pointers to heap
674 MUTABLE_HEAP_NUMBER_TYPE,
679 FIXED_INT8_ARRAY_TYPE, // FIRST_FIXED_TYPED_ARRAY_TYPE
680 FIXED_UINT8_ARRAY_TYPE,
681 FIXED_INT16_ARRAY_TYPE,
682 FIXED_UINT16_ARRAY_TYPE,
683 FIXED_INT32_ARRAY_TYPE,
684 FIXED_UINT32_ARRAY_TYPE,
685 FIXED_FLOAT32_ARRAY_TYPE,
686 FIXED_FLOAT64_ARRAY_TYPE,
687 FIXED_UINT8_CLAMPED_ARRAY_TYPE, // LAST_FIXED_TYPED_ARRAY_TYPE
688 FIXED_DOUBLE_ARRAY_TYPE,
689 FILLER_TYPE, // LAST_DATA_TYPE
692 DECLARED_ACCESSOR_DESCRIPTOR_TYPE,
693 DECLARED_ACCESSOR_INFO_TYPE,
694 EXECUTABLE_ACCESSOR_INFO_TYPE,
696 ACCESS_CHECK_INFO_TYPE,
697 INTERCEPTOR_INFO_TYPE,
698 CALL_HANDLER_INFO_TYPE,
699 FUNCTION_TEMPLATE_INFO_TYPE,
700 OBJECT_TEMPLATE_INFO_TYPE,
702 TYPE_SWITCH_INFO_TYPE,
703 ALLOCATION_SITE_TYPE,
704 ALLOCATION_MEMENTO_TYPE,
707 POLYMORPHIC_CODE_CACHE_TYPE,
708 TYPE_FEEDBACK_INFO_TYPE,
709 ALIASED_ARGUMENTS_ENTRY_TYPE,
712 BREAK_POINT_INFO_TYPE,
714 SHARED_FUNCTION_INFO_TYPE,
720 // All the following types are subtypes of JSReceiver, which corresponds to
721 // objects in the JS sense. The first and the last type in this range are
722 // the two forms of function. This organization enables using the same
723 // compares for checking the JS_RECEIVER/SPEC_OBJECT range and the
724 // NONCALLABLE_JS_OBJECT range.
725 JS_FUNCTION_PROXY_TYPE, // FIRST_JS_RECEIVER_TYPE, FIRST_JS_PROXY_TYPE
726 JS_PROXY_TYPE, // LAST_JS_PROXY_TYPE
727 JS_VALUE_TYPE, // FIRST_JS_OBJECT_TYPE
728 JS_MESSAGE_OBJECT_TYPE,
731 JS_CONTEXT_EXTENSION_OBJECT_TYPE,
732 JS_GENERATOR_OBJECT_TYPE,
734 JS_GLOBAL_OBJECT_TYPE,
735 JS_BUILTINS_OBJECT_TYPE,
736 JS_GLOBAL_PROXY_TYPE,
738 JS_ARRAY_BUFFER_TYPE,
743 JS_SET_ITERATOR_TYPE,
744 JS_MAP_ITERATOR_TYPE,
748 JS_FUNCTION_TYPE, // LAST_JS_OBJECT_TYPE, LAST_JS_RECEIVER_TYPE
752 LAST_TYPE = JS_FUNCTION_TYPE,
753 FIRST_NAME_TYPE = FIRST_TYPE,
754 LAST_NAME_TYPE = SYMBOL_TYPE,
755 FIRST_UNIQUE_NAME_TYPE = INTERNALIZED_STRING_TYPE,
756 LAST_UNIQUE_NAME_TYPE = SYMBOL_TYPE,
757 FIRST_NONSTRING_TYPE = SYMBOL_TYPE,
758 FIRST_PRIMITIVE_TYPE = FIRST_NAME_TYPE,
759 LAST_PRIMITIVE_TYPE = ODDBALL_TYPE,
760 // Boundaries for testing for a fixed typed array.
761 FIRST_FIXED_TYPED_ARRAY_TYPE = FIXED_INT8_ARRAY_TYPE,
762 LAST_FIXED_TYPED_ARRAY_TYPE = FIXED_UINT8_CLAMPED_ARRAY_TYPE,
763 // Boundary for promotion to old space.
764 LAST_DATA_TYPE = FILLER_TYPE,
765 // Boundary for objects represented as JSReceiver (i.e. JSObject or JSProxy).
766 // Note that there is no range for JSObject or JSProxy, since their subtypes
767 // are not continuous in this enum! The enum ranges instead reflect the
768 // external class names, where proxies are treated as either ordinary objects,
770 FIRST_JS_RECEIVER_TYPE = JS_FUNCTION_PROXY_TYPE,
771 LAST_JS_RECEIVER_TYPE = LAST_TYPE,
772 // Boundaries for testing the types represented as JSObject
773 FIRST_JS_OBJECT_TYPE = JS_VALUE_TYPE,
774 LAST_JS_OBJECT_TYPE = LAST_TYPE,
775 // Boundaries for testing the types represented as JSProxy
776 FIRST_JS_PROXY_TYPE = JS_FUNCTION_PROXY_TYPE,
777 LAST_JS_PROXY_TYPE = JS_PROXY_TYPE,
778 // Boundaries for testing whether the type is a JavaScript object.
779 FIRST_SPEC_OBJECT_TYPE = FIRST_JS_RECEIVER_TYPE,
780 LAST_SPEC_OBJECT_TYPE = LAST_JS_RECEIVER_TYPE,
781 // Boundaries for testing the types for which typeof is "object".
782 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_PROXY_TYPE,
783 LAST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_REGEXP_TYPE,
784 // Note that the types for which typeof is "function" are not continuous.
785 // Define this so that we can put assertions on discrete checks.
786 NUM_OF_CALLABLE_SPEC_OBJECT_TYPES = 2
789 STATIC_ASSERT(JS_OBJECT_TYPE == Internals::kJSObjectType);
790 STATIC_ASSERT(FIRST_NONSTRING_TYPE == Internals::kFirstNonstringType);
791 STATIC_ASSERT(ODDBALL_TYPE == Internals::kOddballType);
792 STATIC_ASSERT(FOREIGN_TYPE == Internals::kForeignType);
795 #define FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(V) \
796 V(FAST_ELEMENTS_SUB_TYPE) \
797 V(DICTIONARY_ELEMENTS_SUB_TYPE) \
798 V(FAST_PROPERTIES_SUB_TYPE) \
799 V(DICTIONARY_PROPERTIES_SUB_TYPE) \
800 V(MAP_CODE_CACHE_SUB_TYPE) \
801 V(SCOPE_INFO_SUB_TYPE) \
802 V(STRING_TABLE_SUB_TYPE) \
803 V(DESCRIPTOR_ARRAY_SUB_TYPE) \
804 V(TRANSITION_ARRAY_SUB_TYPE)
806 enum FixedArraySubInstanceType {
807 #define DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE(name) name,
808 FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE)
809 #undef DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE
810 LAST_FIXED_ARRAY_SUB_TYPE = TRANSITION_ARRAY_SUB_TYPE
823 #define DECL_BOOLEAN_ACCESSORS(name) \
824 inline bool name() const; \
825 inline void set_##name(bool value); \
828 #define DECL_ACCESSORS(name, type) \
829 inline type* name() const; \
830 inline void set_##name(type* value, \
831 WriteBarrierMode mode = UPDATE_WRITE_BARRIER); \
834 #define DECLARE_CAST(type) \
835 INLINE(static type* cast(Object* object)); \
836 INLINE(static const type* cast(const Object* object));
840 class AllocationSite;
841 class AllocationSiteCreationContext;
842 class AllocationSiteUsageContext;
845 class ElementsAccessor;
846 class FixedArrayBase;
847 class FunctionLiteral;
849 class JSBuiltinsObject;
850 class LayoutDescriptor;
851 class LookupIterator;
852 class ObjectHashTable;
855 class SafepointEntry;
856 class SharedFunctionInfo;
858 class TypeFeedbackInfo;
859 class TypeFeedbackVector;
862 // We cannot just say "class HeapType;" if it is created from a template... =8-?
863 template<class> class TypeImpl;
864 struct HeapTypeConfig;
865 typedef TypeImpl<HeapTypeConfig> HeapType;
868 // A template-ized version of the IsXXX functions.
869 template <class C> inline bool Is(Object* obj);
872 #define DECLARE_VERIFIER(Name) void Name##Verify();
874 #define DECLARE_VERIFIER(Name)
878 #define DECLARE_PRINTER(Name) void Name##Print(std::ostream& os); // NOLINT
880 #define DECLARE_PRINTER(Name)
884 #define OBJECT_TYPE_LIST(V) \
889 #define HEAP_OBJECT_TYPE_LIST(V) \
891 V(MutableHeapNumber) \
907 V(ExternalTwoByteString) \
908 V(ExternalOneByteString) \
909 V(SeqTwoByteString) \
910 V(SeqOneByteString) \
911 V(InternalizedString) \
914 V(FixedTypedArrayBase) \
917 V(FixedUint16Array) \
919 V(FixedUint32Array) \
921 V(FixedFloat32Array) \
922 V(FixedFloat64Array) \
923 V(FixedUint8ClampedArray) \
929 V(JSContextExtensionObject) \
930 V(JSGeneratorObject) \
932 V(LayoutDescriptor) \
936 V(TypeFeedbackVector) \
937 V(DeoptimizationInputData) \
938 V(DeoptimizationOutputData) \
942 V(FixedDoubleArray) \
946 V(ScriptContextTable) \
952 V(SharedFunctionInfo) \
961 V(JSArrayBufferView) \
970 V(JSWeakCollection) \
977 V(NormalizedMapCache) \
978 V(CompilationCacheTable) \
979 V(CodeCacheHashTable) \
980 V(PolymorphicCodeCacheHashTable) \
985 V(JSBuiltinsObject) \
987 V(UndetectableObject) \
988 V(AccessCheckNeeded) \
994 V(WeakValueHashTable) \
997 // Object is the abstract superclass for all classes in the
999 // Object does not use any virtual functions to avoid the
1000 // allocation of the C++ vtable.
1001 // Since both Smi and HeapObject are subclasses of Object no
1002 // data members can be present in Object.
1006 bool IsObject() const { return true; }
1008 #define IS_TYPE_FUNCTION_DECL(type_) INLINE(bool Is##type_() const);
1009 OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1010 HEAP_OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1011 #undef IS_TYPE_FUNCTION_DECL
1013 // A non-keyed store is of the form a.x = foo or a["x"] = foo whereas
1014 // a keyed store is of the form a[expression] = foo.
1015 enum StoreFromKeyed {
1016 MAY_BE_STORE_FROM_KEYED,
1017 CERTAINLY_NOT_STORE_FROM_KEYED
1020 INLINE(bool IsFixedArrayBase() const);
1021 INLINE(bool IsExternal() const);
1022 INLINE(bool IsAccessorInfo() const);
1024 INLINE(bool IsStruct() const);
1025 #define DECLARE_STRUCT_PREDICATE(NAME, Name, name) \
1026 INLINE(bool Is##Name() const);
1027 STRUCT_LIST(DECLARE_STRUCT_PREDICATE)
1028 #undef DECLARE_STRUCT_PREDICATE
1030 INLINE(bool IsSpecObject()) const;
1031 INLINE(bool IsSpecFunction()) const;
1032 INLINE(bool IsTemplateInfo()) const;
1033 INLINE(bool IsNameDictionary() const);
1034 INLINE(bool IsGlobalDictionary() const);
1035 INLINE(bool IsSeededNumberDictionary() const);
1036 INLINE(bool IsUnseededNumberDictionary() const);
1037 INLINE(bool IsOrderedHashSet() const);
1038 INLINE(bool IsOrderedHashMap() const);
1039 bool IsCallable() const;
1040 static bool IsPromise(Handle<Object> object);
1043 INLINE(bool IsUndefined() const);
1044 INLINE(bool IsNull() const);
1045 INLINE(bool IsTheHole() const);
1046 INLINE(bool IsException() const);
1047 INLINE(bool IsUninitialized() const);
1048 INLINE(bool IsTrue() const);
1049 INLINE(bool IsFalse() const);
1050 INLINE(bool IsArgumentsMarker() const);
1052 // Filler objects (fillers and free space objects).
1053 INLINE(bool IsFiller() const);
1055 // Extract the number.
1056 inline double Number();
1057 INLINE(bool IsNaN() const);
1058 INLINE(bool IsMinusZero() const);
1059 bool ToInt32(int32_t* value);
1060 bool ToUint32(uint32_t* value);
1062 inline Representation OptimalRepresentation();
1064 inline ElementsKind OptimalElementsKind();
1066 inline bool FitsRepresentation(Representation representation);
1068 // Checks whether two valid primitive encodings of a property name resolve to
1069 // the same logical property. E.g., the smi 1, the string "1" and the double
1070 // 1 all refer to the same property, so this helper will return true.
1071 inline bool KeyEquals(Object* other);
1073 Handle<HeapType> OptimalType(Isolate* isolate, Representation representation);
1075 inline static Handle<Object> NewStorageFor(Isolate* isolate,
1076 Handle<Object> object,
1077 Representation representation);
1079 inline static Handle<Object> WrapForRead(Isolate* isolate,
1080 Handle<Object> object,
1081 Representation representation);
1083 // Returns true if the object is of the correct type to be used as a
1084 // implementation of a JSObject's elements.
1085 inline bool HasValidElements();
1087 inline bool HasSpecificClassOf(String* name);
1089 bool BooleanValue(); // ECMA-262 9.2.
1091 // Convert to a JSObject if needed.
1092 // native_context is used when creating wrapper object.
1093 static inline MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1094 Handle<Object> object);
1095 static MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1096 Handle<Object> object,
1097 Handle<Context> context);
1099 MUST_USE_RESULT static MaybeHandle<Object> GetProperty(
1100 LookupIterator* it, LanguageMode language_mode = SLOPPY);
1102 // Implementation of [[Put]], ECMA-262 5th edition, section 8.12.5.
1103 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1104 Handle<Object> object, Handle<Name> name, Handle<Object> value,
1105 LanguageMode language_mode,
1106 StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
1108 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1109 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1110 StoreFromKeyed store_mode);
1112 MUST_USE_RESULT static MaybeHandle<Object> SetSuperProperty(
1113 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1114 StoreFromKeyed store_mode);
1116 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1117 LookupIterator* it, LanguageMode language_mode);
1118 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1119 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1120 LanguageMode language_mode);
1121 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1122 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1123 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1124 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1125 Handle<Object> value, LanguageMode language_mode);
1126 MUST_USE_RESULT static MaybeHandle<Object> RedefineNonconfigurableProperty(
1127 Isolate* isolate, Handle<Object> name, Handle<Object> value,
1128 LanguageMode language_mode);
1129 MUST_USE_RESULT static MaybeHandle<Object> SetDataProperty(
1130 LookupIterator* it, Handle<Object> value);
1131 MUST_USE_RESULT static MaybeHandle<Object> AddDataProperty(
1132 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1133 LanguageMode language_mode, StoreFromKeyed store_mode);
1134 MUST_USE_RESULT static inline MaybeHandle<Object> GetPropertyOrElement(
1135 Handle<Object> object, Handle<Name> name,
1136 LanguageMode language_mode = SLOPPY);
1137 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1138 Isolate* isolate, Handle<Object> object, const char* key,
1139 LanguageMode language_mode = SLOPPY);
1140 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1141 Handle<Object> object, Handle<Name> name,
1142 LanguageMode language_mode = SLOPPY);
1144 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithAccessor(
1145 LookupIterator* it, LanguageMode language_mode);
1146 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithAccessor(
1147 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1149 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithDefinedGetter(
1150 Handle<Object> receiver,
1151 Handle<JSReceiver> getter);
1152 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithDefinedSetter(
1153 Handle<Object> receiver,
1154 Handle<JSReceiver> setter,
1155 Handle<Object> value);
1157 MUST_USE_RESULT static inline MaybeHandle<Object> GetElement(
1158 Isolate* isolate, Handle<Object> object, uint32_t index,
1159 LanguageMode language_mode = SLOPPY);
1161 MUST_USE_RESULT static inline MaybeHandle<Object> SetElement(
1162 Isolate* isolate, Handle<Object> object, uint32_t index,
1163 Handle<Object> value, LanguageMode language_mode);
1165 static inline Handle<Object> GetPrototypeSkipHiddenPrototypes(
1166 Isolate* isolate, Handle<Object> receiver);
1168 bool HasInPrototypeChain(Isolate* isolate, Object* object);
1170 // Returns the permanent hash code associated with this object. May return
1171 // undefined if not yet created.
1174 // Returns undefined for JSObjects, but returns the hash code for simple
1175 // objects. This avoids a double lookup in the cases where we know we will
1176 // add the hash to the JSObject if it does not already exist.
1177 Object* GetSimpleHash();
1179 // Returns the permanent hash code associated with this object depending on
1180 // the actual object type. May create and store a hash code if needed and none
1182 static Handle<Smi> GetOrCreateHash(Isolate* isolate, Handle<Object> object);
1184 // Checks whether this object has the same value as the given one. This
1185 // function is implemented according to ES5, section 9.12 and can be used
1186 // to implement the Harmony "egal" function.
1187 bool SameValue(Object* other);
1189 // Checks whether this object has the same value as the given one.
1190 // +0 and -0 are treated equal. Everything else is the same as SameValue.
1191 // This function is implemented according to ES6, section 7.2.4 and is used
1192 // by ES6 Map and Set.
1193 bool SameValueZero(Object* other);
1195 // Tries to convert an object to an array length. Returns true and sets the
1196 // output parameter if it succeeds.
1197 inline bool ToArrayLength(uint32_t* index);
1199 // Tries to convert an object to an array index. Returns true and sets the
1200 // output parameter if it succeeds. Equivalent to ToArrayLength, but does not
1201 // allow kMaxUInt32.
1202 inline bool ToArrayIndex(uint32_t* index);
1204 // Returns true if this is a JSValue containing a string and the index is
1205 // < the length of the string. Used to implement [] on strings.
1206 inline bool IsStringObjectWithCharacterAt(uint32_t index);
1208 DECLARE_VERIFIER(Object)
1210 // Verify a pointer is a valid object pointer.
1211 static void VerifyPointer(Object* p);
1214 inline void VerifyApiCallResultType();
1216 // Prints this object without details.
1217 void ShortPrint(FILE* out = stdout);
1219 // Prints this object without details to a message accumulator.
1220 void ShortPrint(StringStream* accumulator);
1222 void ShortPrint(std::ostream& os); // NOLINT
1224 DECLARE_CAST(Object)
1226 // Layout description.
1227 static const int kHeaderSize = 0; // Object does not take up any space.
1230 // For our gdb macros, we should perhaps change these in the future.
1233 // Prints this object with details.
1234 void Print(std::ostream& os); // NOLINT
1236 void Print() { ShortPrint(); }
1237 void Print(std::ostream& os) { ShortPrint(os); } // NOLINT
1241 friend class LookupIterator;
1242 friend class PrototypeIterator;
1244 // Return the map of the root of object's prototype chain.
1245 Map* GetRootMap(Isolate* isolate);
1247 // Helper for SetProperty and SetSuperProperty.
1248 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyInternal(
1249 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1250 StoreFromKeyed store_mode, bool* found);
1252 DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
1256 // In objects.h to be usable without objects-inl.h inclusion.
1257 bool Object::IsSmi() const { return HAS_SMI_TAG(this); }
1258 bool Object::IsHeapObject() const { return Internals::HasHeapObjectTag(this); }
1262 explicit Brief(const Object* const v) : value(v) {}
1263 const Object* value;
1267 std::ostream& operator<<(std::ostream& os, const Brief& v);
1270 // Smi represents integer Numbers that can be stored in 31 bits.
1271 // Smis are immediate which means they are NOT allocated in the heap.
1272 // The this pointer has the following format: [31 bit signed int] 0
1273 // For long smis it has the following format:
1274 // [32 bit signed int] [31 bits zero padding] 0
1275 // Smi stands for small integer.
1276 class Smi: public Object {
1278 // Returns the integer value.
1279 inline int value() const { return Internals::SmiValue(this); }
1281 // Convert a value to a Smi object.
1282 static inline Smi* FromInt(int value) {
1283 DCHECK(Smi::IsValid(value));
1284 return reinterpret_cast<Smi*>(Internals::IntToSmi(value));
1287 static inline Smi* FromIntptr(intptr_t value) {
1288 DCHECK(Smi::IsValid(value));
1289 int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
1290 return reinterpret_cast<Smi*>((value << smi_shift_bits) | kSmiTag);
1293 // Returns whether value can be represented in a Smi.
1294 static inline bool IsValid(intptr_t value) {
1295 bool result = Internals::IsValidSmi(value);
1296 DCHECK_EQ(result, value >= kMinValue && value <= kMaxValue);
1302 // Dispatched behavior.
1303 void SmiPrint(std::ostream& os) const; // NOLINT
1304 DECLARE_VERIFIER(Smi)
1306 static const int kMinValue =
1307 (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1308 static const int kMaxValue = -(kMinValue + 1);
1311 DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1315 // Heap objects typically have a map pointer in their first word. However,
1316 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1317 // encoded in the first word. The class MapWord is an abstraction of the
1318 // value in a heap object's first word.
1319 class MapWord BASE_EMBEDDED {
1321 // Normal state: the map word contains a map pointer.
1323 // Create a map word from a map pointer.
1324 static inline MapWord FromMap(const Map* map);
1326 // View this map word as a map pointer.
1327 inline Map* ToMap();
1330 // Scavenge collection: the map word of live objects in the from space
1331 // contains a forwarding address (a heap object pointer in the to space).
1333 // True if this map word is a forwarding address for a scavenge
1334 // collection. Only valid during a scavenge collection (specifically,
1335 // when all map words are heap object pointers, i.e. not during a full GC).
1336 inline bool IsForwardingAddress();
1338 // Create a map word from a forwarding address.
1339 static inline MapWord FromForwardingAddress(HeapObject* object);
1341 // View this map word as a forwarding address.
1342 inline HeapObject* ToForwardingAddress();
1344 static inline MapWord FromRawValue(uintptr_t value) {
1345 return MapWord(value);
1348 inline uintptr_t ToRawValue() {
1353 // HeapObject calls the private constructor and directly reads the value.
1354 friend class HeapObject;
1356 explicit MapWord(uintptr_t value) : value_(value) {}
1362 // The content of an heap object (except for the map pointer). kTaggedValues
1363 // objects can contain both heap pointers and Smis, kMixedValues can contain
1364 // heap pointers, Smis, and raw values (e.g. doubles or strings), and kRawValues
1365 // objects can contain raw values and Smis.
1366 enum class HeapObjectContents { kTaggedValues, kMixedValues, kRawValues };
1369 // HeapObject is the superclass for all classes describing heap allocated
1371 class HeapObject: public Object {
1373 // [map]: Contains a map which contains the object's reflective
1375 inline Map* map() const;
1376 inline void set_map(Map* value);
1377 // The no-write-barrier version. This is OK if the object is white and in
1378 // new space, or if the value is an immortal immutable object, like the maps
1379 // of primitive (non-JS) objects like strings, heap numbers etc.
1380 inline void set_map_no_write_barrier(Map* value);
1382 // Get the map using acquire load.
1383 inline Map* synchronized_map();
1384 inline MapWord synchronized_map_word() const;
1386 // Set the map using release store
1387 inline void synchronized_set_map(Map* value);
1388 inline void synchronized_set_map_no_write_barrier(Map* value);
1389 inline void synchronized_set_map_word(MapWord map_word);
1391 // During garbage collection, the map word of a heap object does not
1392 // necessarily contain a map pointer.
1393 inline MapWord map_word() const;
1394 inline void set_map_word(MapWord map_word);
1396 // The Heap the object was allocated in. Used also to access Isolate.
1397 inline Heap* GetHeap() const;
1399 // Convenience method to get current isolate.
1400 inline Isolate* GetIsolate() const;
1402 // Converts an address to a HeapObject pointer.
1403 static inline HeapObject* FromAddress(Address address) {
1404 DCHECK_TAG_ALIGNED(address);
1405 return reinterpret_cast<HeapObject*>(address + kHeapObjectTag);
1408 // Returns the address of this HeapObject.
1409 inline Address address() {
1410 return reinterpret_cast<Address>(this) - kHeapObjectTag;
1413 // Iterates over pointers contained in the object (including the Map)
1414 void Iterate(ObjectVisitor* v);
1416 // Iterates over all pointers contained in the object except the
1417 // first map pointer. The object type is given in the first
1418 // parameter. This function does not access the map pointer in the
1419 // object, and so is safe to call while the map pointer is modified.
1420 void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1422 // Returns the heap object's size in bytes
1425 // Indicates what type of values this heap object may contain.
1426 inline HeapObjectContents ContentType();
1428 // Given a heap object's map pointer, returns the heap size in bytes
1429 // Useful when the map pointer field is used for other purposes.
1431 inline int SizeFromMap(Map* map);
1433 // Returns the field at offset in obj, as a read/write Object* reference.
1434 // Does no checking, and is safe to use during GC, while maps are invalid.
1435 // Does not invoke write barrier, so should only be assigned to
1436 // during marking GC.
1437 static inline Object** RawField(HeapObject* obj, int offset);
1439 // Adds the |code| object related to |name| to the code cache of this map. If
1440 // this map is a dictionary map that is shared, the map copied and installed
1442 static void UpdateMapCodeCache(Handle<HeapObject> object,
1446 DECLARE_CAST(HeapObject)
1448 // Return the write barrier mode for this. Callers of this function
1449 // must be able to present a reference to an DisallowHeapAllocation
1450 // object as a sign that they are not going to use this function
1451 // from code that allocates and thus invalidates the returned write
1453 inline WriteBarrierMode GetWriteBarrierMode(
1454 const DisallowHeapAllocation& promise);
1456 // Dispatched behavior.
1457 void HeapObjectShortPrint(std::ostream& os); // NOLINT
1459 void PrintHeader(std::ostream& os, const char* id); // NOLINT
1461 DECLARE_PRINTER(HeapObject)
1462 DECLARE_VERIFIER(HeapObject)
1464 inline void VerifyObjectField(int offset);
1465 inline void VerifySmiField(int offset);
1467 // Verify a pointer is a valid HeapObject pointer that points to object
1468 // areas in the heap.
1469 static void VerifyHeapPointer(Object* p);
1472 inline AllocationAlignment RequiredAlignment();
1474 // Layout description.
1475 // First field in a heap object is map.
1476 static const int kMapOffset = Object::kHeaderSize;
1477 static const int kHeaderSize = kMapOffset + kPointerSize;
1479 STATIC_ASSERT(kMapOffset == Internals::kHeapObjectMapOffset);
1482 // helpers for calling an ObjectVisitor to iterate over pointers in the
1483 // half-open range [start, end) specified as integer offsets
1484 inline void IteratePointers(ObjectVisitor* v, int start, int end);
1485 // as above, for the single element at "offset"
1486 inline void IteratePointer(ObjectVisitor* v, int offset);
1487 // as above, for the next code link of a code object.
1488 inline void IterateNextCodeLink(ObjectVisitor* v, int offset);
1491 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1495 // This class describes a body of an object of a fixed size
1496 // in which all pointer fields are located in the [start_offset, end_offset)
1498 template<int start_offset, int end_offset, int size>
1499 class FixedBodyDescriptor {
1501 static const int kStartOffset = start_offset;
1502 static const int kEndOffset = end_offset;
1503 static const int kSize = size;
1505 static inline void IterateBody(HeapObject* obj, ObjectVisitor* v);
1507 template<typename StaticVisitor>
1508 static inline void IterateBody(HeapObject* obj) {
1509 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1510 HeapObject::RawField(obj, end_offset));
1515 // This class describes a body of an object of a variable size
1516 // in which all pointer fields are located in the [start_offset, object_size)
1518 template<int start_offset>
1519 class FlexibleBodyDescriptor {
1521 static const int kStartOffset = start_offset;
1523 static inline void IterateBody(HeapObject* obj,
1527 template<typename StaticVisitor>
1528 static inline void IterateBody(HeapObject* obj, int object_size) {
1529 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1530 HeapObject::RawField(obj, object_size));
1535 // The HeapNumber class describes heap allocated numbers that cannot be
1536 // represented in a Smi (small integer)
1537 class HeapNumber: public HeapObject {
1539 // [value]: number value.
1540 inline double value() const;
1541 inline void set_value(double value);
1543 DECLARE_CAST(HeapNumber)
1545 // Dispatched behavior.
1546 bool HeapNumberBooleanValue();
1548 void HeapNumberPrint(std::ostream& os); // NOLINT
1549 DECLARE_VERIFIER(HeapNumber)
1551 inline int get_exponent();
1552 inline int get_sign();
1554 // Layout description.
1555 static const int kValueOffset = HeapObject::kHeaderSize;
1556 // IEEE doubles are two 32 bit words. The first is just mantissa, the second
1557 // is a mixture of sign, exponent and mantissa. The offsets of two 32 bit
1558 // words within double numbers are endian dependent and they are set
1560 #if defined(V8_TARGET_LITTLE_ENDIAN)
1561 static const int kMantissaOffset = kValueOffset;
1562 static const int kExponentOffset = kValueOffset + 4;
1563 #elif defined(V8_TARGET_BIG_ENDIAN)
1564 static const int kMantissaOffset = kValueOffset + 4;
1565 static const int kExponentOffset = kValueOffset;
1567 #error Unknown byte ordering
1570 static const int kSize = kValueOffset + kDoubleSize;
1571 static const uint32_t kSignMask = 0x80000000u;
1572 static const uint32_t kExponentMask = 0x7ff00000u;
1573 static const uint32_t kMantissaMask = 0xfffffu;
1574 static const int kMantissaBits = 52;
1575 static const int kExponentBits = 11;
1576 static const int kExponentBias = 1023;
1577 static const int kExponentShift = 20;
1578 static const int kInfinityOrNanExponent =
1579 (kExponentMask >> kExponentShift) - kExponentBias;
1580 static const int kMantissaBitsInTopWord = 20;
1581 static const int kNonMantissaBitsInTopWord = 12;
1584 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
1588 // The Simd128Value class describes heap allocated 128 bit SIMD values.
1589 class Simd128Value : public HeapObject {
1591 DECLARE_CAST(Simd128Value)
1593 DECLARE_PRINTER(Simd128Value)
1594 DECLARE_VERIFIER(Simd128Value)
1596 // Checks that another instance is bit-wise equal.
1597 bool BitwiseEquals(const Simd128Value* other) const;
1598 // Computes a hash from the 128 bit value, viewed as 4 32-bit integers.
1599 uint32_t Hash() const;
1600 // Copies the 16 bytes of SIMD data to the destination address.
1601 void CopyBits(void* destination) const;
1603 // Layout description.
1604 static const int kValueOffset = HeapObject::kHeaderSize;
1605 static const int kSize = kValueOffset + kSimd128Size;
1608 DISALLOW_IMPLICIT_CONSTRUCTORS(Simd128Value);
1612 // V has parameters (TYPE, Type, type, lane count, lane type)
1613 #define SIMD128_TYPES(V) \
1614 V(FLOAT32X4, Float32x4, float32x4, 4, float) \
1615 V(INT32X4, Int32x4, int32x4, 4, int32_t) \
1616 V(BOOL32X4, Bool32x4, bool32x4, 4, bool) \
1617 V(INT16X8, Int16x8, int16x8, 8, int16_t) \
1618 V(BOOL16X8, Bool16x8, bool16x8, 8, bool) \
1619 V(INT8X16, Int8x16, int8x16, 16, int8_t) \
1620 V(BOOL8X16, Bool8x16, bool8x16, 16, bool)
1622 #define SIMD128_VALUE_CLASS(TYPE, Type, type, lane_count, lane_type) \
1623 class Type final : public Simd128Value { \
1625 inline lane_type get_lane(int lane) const; \
1626 inline void set_lane(int lane, lane_type value); \
1628 DECLARE_CAST(Type) \
1630 DECLARE_PRINTER(Type) \
1633 DISALLOW_IMPLICIT_CONSTRUCTORS(Type); \
1635 SIMD128_TYPES(SIMD128_VALUE_CLASS)
1636 #undef SIMD128_VALUE_CLASS
1639 enum EnsureElementsMode {
1640 DONT_ALLOW_DOUBLE_ELEMENTS,
1641 ALLOW_COPIED_DOUBLE_ELEMENTS,
1642 ALLOW_CONVERTED_DOUBLE_ELEMENTS
1646 // Indicator for one component of an AccessorPair.
1647 enum AccessorComponent {
1653 // JSReceiver includes types on which properties can be defined, i.e.,
1654 // JSObject and JSProxy.
1655 class JSReceiver: public HeapObject {
1657 DECLARE_CAST(JSReceiver)
1659 // Implementation of [[HasProperty]], ECMA-262 5th edition, section 8.12.6.
1660 MUST_USE_RESULT static inline Maybe<bool> HasProperty(
1661 Handle<JSReceiver> object, Handle<Name> name);
1662 MUST_USE_RESULT static inline Maybe<bool> HasOwnProperty(Handle<JSReceiver>,
1664 MUST_USE_RESULT static inline Maybe<bool> HasElement(
1665 Handle<JSReceiver> object, uint32_t index);
1666 MUST_USE_RESULT static inline Maybe<bool> HasOwnElement(
1667 Handle<JSReceiver> object, uint32_t index);
1669 // Implementation of [[Delete]], ECMA-262 5th edition, section 8.12.7.
1670 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyOrElement(
1671 Handle<JSReceiver> object, Handle<Name> name,
1672 LanguageMode language_mode = SLOPPY);
1673 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1674 Handle<JSReceiver> object, Handle<Name> name,
1675 LanguageMode language_mode = SLOPPY);
1676 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1677 LookupIterator* it, LanguageMode language_mode);
1678 MUST_USE_RESULT static MaybeHandle<Object> DeleteElement(
1679 Handle<JSReceiver> object, uint32_t index,
1680 LanguageMode language_mode = SLOPPY);
1682 // Tests for the fast common case for property enumeration.
1683 bool IsSimpleEnum();
1685 // Returns the class name ([[Class]] property in the specification).
1686 String* class_name();
1688 // Returns the constructor name (the name (possibly, inferred name) of the
1689 // function that was used to instantiate the object).
1690 String* constructor_name();
1692 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetPropertyAttributes(
1693 Handle<JSReceiver> object, Handle<Name> name);
1694 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1695 GetOwnPropertyAttributes(Handle<JSReceiver> object, Handle<Name> name);
1697 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetElementAttributes(
1698 Handle<JSReceiver> object, uint32_t index);
1699 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1700 GetOwnElementAttributes(Handle<JSReceiver> object, uint32_t index);
1702 MUST_USE_RESULT static Maybe<PropertyAttributes> GetPropertyAttributes(
1703 LookupIterator* it);
1706 static Handle<Object> GetDataProperty(Handle<JSReceiver> object,
1708 static Handle<Object> GetDataProperty(LookupIterator* it);
1711 // Retrieves a permanent object identity hash code. The undefined value might
1712 // be returned in case no hash was created yet.
1713 inline Object* GetIdentityHash();
1715 // Retrieves a permanent object identity hash code. May create and store a
1716 // hash code if needed and none exists.
1717 inline static Handle<Smi> GetOrCreateIdentityHash(
1718 Handle<JSReceiver> object);
1720 enum KeyCollectionType { OWN_ONLY, INCLUDE_PROTOS };
1722 // Computes the enumerable keys for a JSObject. Used for implementing
1723 // "for (n in object) { }".
1724 MUST_USE_RESULT static MaybeHandle<FixedArray> GetKeys(
1725 Handle<JSReceiver> object,
1726 KeyCollectionType type);
1729 DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
1733 // The JSObject describes real heap allocated JavaScript objects with
1735 // Note that the map of JSObject changes during execution to enable inline
1737 class JSObject: public JSReceiver {
1739 // [properties]: Backing storage for properties.
1740 // properties is a FixedArray in the fast case and a Dictionary in the
1742 DECL_ACCESSORS(properties, FixedArray) // Get and set fast properties.
1743 inline void initialize_properties();
1744 inline bool HasFastProperties();
1745 // Gets slow properties for non-global objects.
1746 inline NameDictionary* property_dictionary();
1747 // Gets global object properties.
1748 inline GlobalDictionary* global_dictionary();
1750 // [elements]: The elements (properties with names that are integers).
1752 // Elements can be in two general modes: fast and slow. Each mode
1753 // corrensponds to a set of object representations of elements that
1754 // have something in common.
1756 // In the fast mode elements is a FixedArray and so each element can
1757 // be quickly accessed. This fact is used in the generated code. The
1758 // elements array can have one of three maps in this mode:
1759 // fixed_array_map, sloppy_arguments_elements_map or
1760 // fixed_cow_array_map (for copy-on-write arrays). In the latter case
1761 // the elements array may be shared by a few objects and so before
1762 // writing to any element the array must be copied. Use
1763 // EnsureWritableFastElements in this case.
1765 // In the slow mode the elements is either a NumberDictionary, a
1766 // FixedArray parameter map for a (sloppy) arguments object.
1767 DECL_ACCESSORS(elements, FixedArrayBase)
1768 inline void initialize_elements();
1769 static void ResetElements(Handle<JSObject> object);
1770 static inline void SetMapAndElements(Handle<JSObject> object,
1772 Handle<FixedArrayBase> elements);
1773 inline ElementsKind GetElementsKind();
1774 ElementsAccessor* GetElementsAccessor();
1775 // Returns true if an object has elements of FAST_SMI_ELEMENTS ElementsKind.
1776 inline bool HasFastSmiElements();
1777 // Returns true if an object has elements of FAST_ELEMENTS ElementsKind.
1778 inline bool HasFastObjectElements();
1779 // Returns true if an object has elements of FAST_ELEMENTS or
1780 // FAST_SMI_ONLY_ELEMENTS.
1781 inline bool HasFastSmiOrObjectElements();
1782 // Returns true if an object has any of the fast elements kinds.
1783 inline bool HasFastElements();
1784 // Returns true if an object has elements of FAST_DOUBLE_ELEMENTS
1786 inline bool HasFastDoubleElements();
1787 // Returns true if an object has elements of FAST_HOLEY_*_ELEMENTS
1789 inline bool HasFastHoleyElements();
1790 inline bool HasSloppyArgumentsElements();
1791 inline bool HasDictionaryElements();
1793 inline bool HasFixedTypedArrayElements();
1795 inline bool HasFixedUint8ClampedElements();
1796 inline bool HasFixedArrayElements();
1797 inline bool HasFixedInt8Elements();
1798 inline bool HasFixedUint8Elements();
1799 inline bool HasFixedInt16Elements();
1800 inline bool HasFixedUint16Elements();
1801 inline bool HasFixedInt32Elements();
1802 inline bool HasFixedUint32Elements();
1803 inline bool HasFixedFloat32Elements();
1804 inline bool HasFixedFloat64Elements();
1806 inline bool HasFastArgumentsElements();
1807 inline bool HasSlowArgumentsElements();
1808 inline SeededNumberDictionary* element_dictionary(); // Gets slow elements.
1810 // Requires: HasFastElements().
1811 static Handle<FixedArray> EnsureWritableFastElements(
1812 Handle<JSObject> object);
1814 // Collects elements starting at index 0.
1815 // Undefined values are placed after non-undefined values.
1816 // Returns the number of non-undefined values.
1817 static Handle<Object> PrepareElementsForSort(Handle<JSObject> object,
1819 // As PrepareElementsForSort, but only on objects where elements is
1820 // a dictionary, and it will stay a dictionary. Collates undefined and
1821 // unexisting elements below limit from position zero of the elements.
1822 static Handle<Object> PrepareSlowElementsForSort(Handle<JSObject> object,
1825 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithInterceptor(
1826 LookupIterator* it, Handle<Object> value);
1828 // SetLocalPropertyIgnoreAttributes converts callbacks to fields. We need to
1829 // grant an exemption to ExecutableAccessor callbacks in some cases.
1830 enum ExecutableAccessorInfoHandling { DEFAULT_HANDLING, DONT_FORCE_FIELD };
1832 MUST_USE_RESULT static MaybeHandle<Object> DefineOwnPropertyIgnoreAttributes(
1833 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1834 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1836 MUST_USE_RESULT static MaybeHandle<Object> SetOwnPropertyIgnoreAttributes(
1837 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1838 PropertyAttributes attributes,
1839 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1841 MUST_USE_RESULT static MaybeHandle<Object> SetOwnElementIgnoreAttributes(
1842 Handle<JSObject> object, uint32_t index, Handle<Object> value,
1843 PropertyAttributes attributes,
1844 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1846 // Equivalent to one of the above depending on whether |name| can be converted
1847 // to an array index.
1848 MUST_USE_RESULT static MaybeHandle<Object>
1849 DefinePropertyOrElementIgnoreAttributes(
1850 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1851 PropertyAttributes attributes = NONE,
1852 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1854 // Adds or reconfigures a property to attributes NONE. It will fail when it
1856 MUST_USE_RESULT static Maybe<bool> CreateDataProperty(LookupIterator* it,
1857 Handle<Object> value);
1859 static void AddProperty(Handle<JSObject> object, Handle<Name> name,
1860 Handle<Object> value, PropertyAttributes attributes);
1862 MUST_USE_RESULT static MaybeHandle<Object> AddDataElement(
1863 Handle<JSObject> receiver, uint32_t index, Handle<Object> value,
1864 PropertyAttributes attributes);
1866 // Extend the receiver with a single fast property appeared first in the
1867 // passed map. This also extends the property backing store if necessary.
1868 static void AllocateStorageForMap(Handle<JSObject> object, Handle<Map> map);
1870 // Migrates the given object to a map whose field representations are the
1871 // lowest upper bound of all known representations for that field.
1872 static void MigrateInstance(Handle<JSObject> instance);
1874 // Migrates the given object only if the target map is already available,
1875 // or returns false if such a map is not yet available.
1876 static bool TryMigrateInstance(Handle<JSObject> instance);
1878 // Sets the property value in a normalized object given (key, value, details).
1879 // Handles the special representation of JS global objects.
1880 static void SetNormalizedProperty(Handle<JSObject> object, Handle<Name> name,
1881 Handle<Object> value,
1882 PropertyDetails details);
1883 static void SetDictionaryElement(Handle<JSObject> object, uint32_t index,
1884 Handle<Object> value,
1885 PropertyAttributes attributes);
1886 static void SetDictionaryArgumentsElement(Handle<JSObject> object,
1888 Handle<Object> value,
1889 PropertyAttributes attributes);
1891 static void OptimizeAsPrototype(Handle<JSObject> object,
1892 PrototypeOptimizationMode mode);
1893 static void ReoptimizeIfPrototype(Handle<JSObject> object);
1894 static void LazyRegisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1895 static bool UnregisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1896 static void InvalidatePrototypeChains(Map* map);
1898 // Alternative implementation of WeakFixedArray::NullCallback.
1899 class PrototypeRegistryCompactionCallback {
1901 static void Callback(Object* value, int old_index, int new_index);
1904 // Retrieve interceptors.
1905 InterceptorInfo* GetNamedInterceptor();
1906 InterceptorInfo* GetIndexedInterceptor();
1908 // Used from JSReceiver.
1909 MUST_USE_RESULT static Maybe<PropertyAttributes>
1910 GetPropertyAttributesWithInterceptor(LookupIterator* it);
1911 MUST_USE_RESULT static Maybe<PropertyAttributes>
1912 GetPropertyAttributesWithFailedAccessCheck(LookupIterator* it);
1914 // Retrieves an AccessorPair property from the given object. Might return
1915 // undefined if the property doesn't exist or is of a different kind.
1916 MUST_USE_RESULT static MaybeHandle<Object> GetAccessor(
1917 Handle<JSObject> object,
1919 AccessorComponent component);
1921 // Defines an AccessorPair property on the given object.
1922 // TODO(mstarzinger): Rename to SetAccessor().
1923 static MaybeHandle<Object> DefineAccessor(Handle<JSObject> object,
1925 Handle<Object> getter,
1926 Handle<Object> setter,
1927 PropertyAttributes attributes);
1929 // Defines an AccessorInfo property on the given object.
1930 MUST_USE_RESULT static MaybeHandle<Object> SetAccessor(
1931 Handle<JSObject> object,
1932 Handle<AccessorInfo> info);
1934 // The result must be checked first for exceptions. If there's no exception,
1935 // the output parameter |done| indicates whether the interceptor has a result
1937 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithInterceptor(
1938 LookupIterator* it, bool* done);
1940 // Accessors for hidden properties object.
1942 // Hidden properties are not own properties of the object itself.
1943 // Instead they are stored in an auxiliary structure kept as an own
1944 // property with a special name Heap::hidden_string(). But if the
1945 // receiver is a JSGlobalProxy then the auxiliary object is a property
1946 // of its prototype, and if it's a detached proxy, then you can't have
1947 // hidden properties.
1949 // Sets a hidden property on this object. Returns this object if successful,
1950 // undefined if called on a detached proxy.
1951 static Handle<Object> SetHiddenProperty(Handle<JSObject> object,
1953 Handle<Object> value);
1954 // Gets the value of a hidden property with the given key. Returns the hole
1955 // if the property doesn't exist (or if called on a detached proxy),
1956 // otherwise returns the value set for the key.
1957 Object* GetHiddenProperty(Handle<Name> key);
1958 // Deletes a hidden property. Deleting a non-existing property is
1959 // considered successful.
1960 static void DeleteHiddenProperty(Handle<JSObject> object,
1962 // Returns true if the object has a property with the hidden string as name.
1963 static bool HasHiddenProperties(Handle<JSObject> object);
1965 static void SetIdentityHash(Handle<JSObject> object, Handle<Smi> hash);
1967 static void ValidateElements(Handle<JSObject> object);
1969 // Makes sure that this object can contain HeapObject as elements.
1970 static inline void EnsureCanContainHeapObjectElements(Handle<JSObject> obj);
1972 // Makes sure that this object can contain the specified elements.
1973 static inline void EnsureCanContainElements(
1974 Handle<JSObject> object,
1977 EnsureElementsMode mode);
1978 static inline void EnsureCanContainElements(
1979 Handle<JSObject> object,
1980 Handle<FixedArrayBase> elements,
1982 EnsureElementsMode mode);
1983 static void EnsureCanContainElements(
1984 Handle<JSObject> object,
1985 Arguments* arguments,
1988 EnsureElementsMode mode);
1990 // Would we convert a fast elements array to dictionary mode given
1991 // an access at key?
1992 bool WouldConvertToSlowElements(uint32_t index);
1994 // Computes the new capacity when expanding the elements of a JSObject.
1995 static uint32_t NewElementsCapacity(uint32_t old_capacity) {
1996 // (old_capacity + 50%) + 16
1997 return old_capacity + (old_capacity >> 1) + 16;
2000 // These methods do not perform access checks!
2001 static void UpdateAllocationSite(Handle<JSObject> object,
2002 ElementsKind to_kind);
2004 // Lookup interceptors are used for handling properties controlled by host
2006 inline bool HasNamedInterceptor();
2007 inline bool HasIndexedInterceptor();
2009 // Computes the enumerable keys from interceptors. Used for debug mirrors and
2010 // by JSReceiver::GetKeys.
2011 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForNamedInterceptor(
2012 Handle<JSObject> object,
2013 Handle<JSReceiver> receiver);
2014 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForIndexedInterceptor(
2015 Handle<JSObject> object,
2016 Handle<JSReceiver> receiver);
2018 // Support functions for v8 api (needed for correct interceptor behavior).
2019 MUST_USE_RESULT static Maybe<bool> HasRealNamedProperty(
2020 Handle<JSObject> object, Handle<Name> name);
2021 MUST_USE_RESULT static Maybe<bool> HasRealElementProperty(
2022 Handle<JSObject> object, uint32_t index);
2023 MUST_USE_RESULT static Maybe<bool> HasRealNamedCallbackProperty(
2024 Handle<JSObject> object, Handle<Name> name);
2026 // Get the header size for a JSObject. Used to compute the index of
2027 // internal fields as well as the number of internal fields.
2028 inline int GetHeaderSize();
2030 inline int GetInternalFieldCount();
2031 inline int GetInternalFieldOffset(int index);
2032 inline Object* GetInternalField(int index);
2033 inline void SetInternalField(int index, Object* value);
2034 inline void SetInternalField(int index, Smi* value);
2036 // Returns the number of properties on this object filtering out properties
2037 // with the specified attributes (ignoring interceptors).
2038 int NumberOfOwnProperties(PropertyAttributes filter = NONE);
2039 // Fill in details for properties into storage starting at the specified
2040 // index. Returns the number of properties added.
2041 int GetOwnPropertyNames(FixedArray* storage, int index,
2042 PropertyAttributes filter = NONE);
2044 // Returns the number of properties on this object filtering out properties
2045 // with the specified attributes (ignoring interceptors).
2046 int NumberOfOwnElements(PropertyAttributes filter);
2047 // Returns the number of enumerable elements (ignoring interceptors).
2048 int NumberOfEnumElements();
2049 // Returns the number of elements on this object filtering out elements
2050 // with the specified attributes (ignoring interceptors).
2051 int GetOwnElementKeys(FixedArray* storage, PropertyAttributes filter);
2052 // Count and fill in the enumerable elements into storage.
2053 // (storage->length() == NumberOfEnumElements()).
2054 // If storage is NULL, will count the elements without adding
2055 // them to any storage.
2056 // Returns the number of enumerable elements.
2057 int GetEnumElementKeys(FixedArray* storage);
2059 static Handle<FixedArray> GetEnumPropertyKeys(Handle<JSObject> object,
2062 // Returns a new map with all transitions dropped from the object's current
2063 // map and the ElementsKind set.
2064 static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
2065 ElementsKind to_kind);
2066 static void TransitionElementsKind(Handle<JSObject> object,
2067 ElementsKind to_kind);
2069 // Always use this to migrate an object to a new map.
2070 // |expected_additional_properties| is only used for fast-to-slow transitions
2071 // and ignored otherwise.
2072 static void MigrateToMap(Handle<JSObject> object, Handle<Map> new_map,
2073 int expected_additional_properties = 0);
2075 // Convert the object to use the canonical dictionary
2076 // representation. If the object is expected to have additional properties
2077 // added this number can be indicated to have the backing store allocated to
2078 // an initial capacity for holding these properties.
2079 static void NormalizeProperties(Handle<JSObject> object,
2080 PropertyNormalizationMode mode,
2081 int expected_additional_properties,
2082 const char* reason);
2084 // Convert and update the elements backing store to be a
2085 // SeededNumberDictionary dictionary. Returns the backing after conversion.
2086 static Handle<SeededNumberDictionary> NormalizeElements(
2087 Handle<JSObject> object);
2089 void RequireSlowElements(SeededNumberDictionary* dictionary);
2091 // Transform slow named properties to fast variants.
2092 static void MigrateSlowToFast(Handle<JSObject> object,
2093 int unused_property_fields, const char* reason);
2095 inline bool IsUnboxedDoubleField(FieldIndex index);
2097 // Access fast-case object properties at index.
2098 static Handle<Object> FastPropertyAt(Handle<JSObject> object,
2099 Representation representation,
2101 inline Object* RawFastPropertyAt(FieldIndex index);
2102 inline double RawFastDoublePropertyAt(FieldIndex index);
2104 inline void FastPropertyAtPut(FieldIndex index, Object* value);
2105 inline void RawFastPropertyAtPut(FieldIndex index, Object* value);
2106 inline void RawFastDoublePropertyAtPut(FieldIndex index, double value);
2107 inline void WriteToField(int descriptor, Object* value);
2109 // Access to in object properties.
2110 inline int GetInObjectPropertyOffset(int index);
2111 inline Object* InObjectPropertyAt(int index);
2112 inline Object* InObjectPropertyAtPut(int index,
2114 WriteBarrierMode mode
2115 = UPDATE_WRITE_BARRIER);
2117 // Set the object's prototype (only JSReceiver and null are allowed values).
2118 MUST_USE_RESULT static MaybeHandle<Object> SetPrototype(
2119 Handle<JSObject> object, Handle<Object> value, bool from_javascript);
2121 // Initializes the body after properties slot, properties slot is
2122 // initialized by set_properties. Fill the pre-allocated fields with
2123 // pre_allocated_value and the rest with filler_value.
2124 // Note: this call does not update write barrier, the caller is responsible
2125 // to ensure that |filler_value| can be collected without WB here.
2126 inline void InitializeBody(Map* map,
2127 Object* pre_allocated_value,
2128 Object* filler_value);
2130 // Check whether this object references another object
2131 bool ReferencesObject(Object* obj);
2133 // Disalow further properties to be added to the oject.
2134 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensions(
2135 Handle<JSObject> object);
2137 bool IsExtensible();
2140 MUST_USE_RESULT static MaybeHandle<Object> Seal(Handle<JSObject> object);
2142 // ES5 Object.freeze
2143 MUST_USE_RESULT static MaybeHandle<Object> Freeze(Handle<JSObject> object);
2145 // Called the first time an object is observed with ES7 Object.observe.
2146 static void SetObserved(Handle<JSObject> object);
2149 enum DeepCopyHints { kNoHints = 0, kObjectIsShallow = 1 };
2151 MUST_USE_RESULT static MaybeHandle<JSObject> DeepCopy(
2152 Handle<JSObject> object,
2153 AllocationSiteUsageContext* site_context,
2154 DeepCopyHints hints = kNoHints);
2155 MUST_USE_RESULT static MaybeHandle<JSObject> DeepWalk(
2156 Handle<JSObject> object,
2157 AllocationSiteCreationContext* site_context);
2159 DECLARE_CAST(JSObject)
2161 // Dispatched behavior.
2162 void JSObjectShortPrint(StringStream* accumulator);
2163 DECLARE_PRINTER(JSObject)
2164 DECLARE_VERIFIER(JSObject)
2166 void PrintProperties(std::ostream& os); // NOLINT
2167 void PrintElements(std::ostream& os); // NOLINT
2169 #if defined(DEBUG) || defined(OBJECT_PRINT)
2170 void PrintTransitions(std::ostream& os); // NOLINT
2173 static void PrintElementsTransition(
2174 FILE* file, Handle<JSObject> object,
2175 ElementsKind from_kind, Handle<FixedArrayBase> from_elements,
2176 ElementsKind to_kind, Handle<FixedArrayBase> to_elements);
2178 void PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map);
2181 // Structure for collecting spill information about JSObjects.
2182 class SpillInformation {
2186 int number_of_objects_;
2187 int number_of_objects_with_fast_properties_;
2188 int number_of_objects_with_fast_elements_;
2189 int number_of_fast_used_fields_;
2190 int number_of_fast_unused_fields_;
2191 int number_of_slow_used_properties_;
2192 int number_of_slow_unused_properties_;
2193 int number_of_fast_used_elements_;
2194 int number_of_fast_unused_elements_;
2195 int number_of_slow_used_elements_;
2196 int number_of_slow_unused_elements_;
2199 void IncrementSpillStatistics(SpillInformation* info);
2203 // If a GC was caused while constructing this object, the elements pointer
2204 // may point to a one pointer filler map. The object won't be rooted, but
2205 // our heap verification code could stumble across it.
2206 bool ElementsAreSafeToExamine();
2209 Object* SlowReverseLookup(Object* value);
2211 // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2212 // Also maximal value of JSArray's length property.
2213 static const uint32_t kMaxElementCount = 0xffffffffu;
2215 // Constants for heuristics controlling conversion of fast elements
2216 // to slow elements.
2218 // Maximal gap that can be introduced by adding an element beyond
2219 // the current elements length.
2220 static const uint32_t kMaxGap = 1024;
2222 // Maximal length of fast elements array that won't be checked for
2223 // being dense enough on expansion.
2224 static const int kMaxUncheckedFastElementsLength = 5000;
2226 // Same as above but for old arrays. This limit is more strict. We
2227 // don't want to be wasteful with long lived objects.
2228 static const int kMaxUncheckedOldFastElementsLength = 500;
2230 // Note that Page::kMaxRegularHeapObjectSize puts a limit on
2231 // permissible values (see the DCHECK in heap.cc).
2232 static const int kInitialMaxFastElementArray = 100000;
2234 // This constant applies only to the initial map of "global.Object" and
2235 // not to arbitrary other JSObject maps.
2236 static const int kInitialGlobalObjectUnusedPropertiesCount = 4;
2238 static const int kMaxInstanceSize = 255 * kPointerSize;
2239 // When extending the backing storage for property values, we increase
2240 // its size by more than the 1 entry necessary, so sequentially adding fields
2241 // to the same object requires fewer allocations and copies.
2242 static const int kFieldsAdded = 3;
2244 // Layout description.
2245 static const int kPropertiesOffset = HeapObject::kHeaderSize;
2246 static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2247 static const int kHeaderSize = kElementsOffset + kPointerSize;
2249 STATIC_ASSERT(kHeaderSize == Internals::kJSObjectHeaderSize);
2251 class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2253 static inline int SizeOf(Map* map, HeapObject* object);
2256 Context* GetCreationContext();
2258 // Enqueue change record for Object.observe. May cause GC.
2259 MUST_USE_RESULT static MaybeHandle<Object> EnqueueChangeRecord(
2260 Handle<JSObject> object, const char* type, Handle<Name> name,
2261 Handle<Object> old_value);
2263 // Gets the number of currently used elements.
2264 int GetFastElementsUsage();
2266 // Deletes an existing named property in a normalized object.
2267 static void DeleteNormalizedProperty(Handle<JSObject> object,
2268 Handle<Name> name, int entry);
2270 static bool AllCanRead(LookupIterator* it);
2271 static bool AllCanWrite(LookupIterator* it);
2274 friend class JSReceiver;
2275 friend class Object;
2277 static void MigrateFastToFast(Handle<JSObject> object, Handle<Map> new_map);
2278 static void MigrateFastToSlow(Handle<JSObject> object,
2279 Handle<Map> new_map,
2280 int expected_additional_properties);
2282 // Used from Object::GetProperty().
2283 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithFailedAccessCheck(
2284 LookupIterator* it);
2286 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithFailedAccessCheck(
2287 LookupIterator* it, Handle<Object> value);
2289 // Add a property to a slow-case object.
2290 static void AddSlowProperty(Handle<JSObject> object,
2292 Handle<Object> value,
2293 PropertyAttributes attributes);
2295 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithInterceptor(
2296 LookupIterator* it);
2298 bool ReferencesObjectFromElements(FixedArray* elements,
2302 // Return the hash table backing store or the inline stored identity hash,
2303 // whatever is found.
2304 MUST_USE_RESULT Object* GetHiddenPropertiesHashTable();
2306 // Return the hash table backing store for hidden properties. If there is no
2307 // backing store, allocate one.
2308 static Handle<ObjectHashTable> GetOrCreateHiddenPropertiesHashtable(
2309 Handle<JSObject> object);
2311 // Set the hidden property backing store to either a hash table or
2312 // the inline-stored identity hash.
2313 static Handle<Object> SetHiddenPropertiesHashTable(
2314 Handle<JSObject> object,
2315 Handle<Object> value);
2317 MUST_USE_RESULT Object* GetIdentityHash();
2319 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSObject> object);
2321 static Handle<SeededNumberDictionary> GetNormalizedElementDictionary(
2322 Handle<JSObject> object, Handle<FixedArrayBase> elements);
2324 // Helper for fast versions of preventExtensions, seal, and freeze.
2325 // attrs is one of NONE, SEALED, or FROZEN (depending on the operation).
2326 template <PropertyAttributes attrs>
2327 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensionsWithTransition(
2328 Handle<JSObject> object);
2330 DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
2334 // Common superclass for FixedArrays that allow implementations to share
2335 // common accessors and some code paths.
2336 class FixedArrayBase: public HeapObject {
2338 // [length]: length of the array.
2339 inline int length() const;
2340 inline void set_length(int value);
2342 // Get and set the length using acquire loads and release stores.
2343 inline int synchronized_length() const;
2344 inline void synchronized_set_length(int value);
2346 DECLARE_CAST(FixedArrayBase)
2348 // Layout description.
2349 // Length is smi tagged when it is stored.
2350 static const int kLengthOffset = HeapObject::kHeaderSize;
2351 static const int kHeaderSize = kLengthOffset + kPointerSize;
2355 class FixedDoubleArray;
2356 class IncrementalMarking;
2359 // FixedArray describes fixed-sized arrays with element type Object*.
2360 class FixedArray: public FixedArrayBase {
2362 // Setter and getter for elements.
2363 inline Object* get(int index) const;
2364 void SetValue(uint32_t index, Object* value);
2365 static inline Handle<Object> get(Handle<FixedArray> array, int index);
2366 // Setter that uses write barrier.
2367 inline void set(int index, Object* value);
2368 inline bool is_the_hole(int index);
2370 // Setter that doesn't need write barrier.
2371 inline void set(int index, Smi* value);
2372 // Setter with explicit barrier mode.
2373 inline void set(int index, Object* value, WriteBarrierMode mode);
2375 // Setters for frequently used oddballs located in old space.
2376 inline void set_undefined(int index);
2377 inline void set_null(int index);
2378 inline void set_the_hole(int index);
2380 inline Object** GetFirstElementAddress();
2381 inline bool ContainsOnlySmisOrHoles();
2383 // Gives access to raw memory which stores the array's data.
2384 inline Object** data_start();
2386 inline void FillWithHoles(int from, int to);
2388 // Shrink length and insert filler objects.
2389 void Shrink(int length);
2391 enum KeyFilter { ALL_KEYS, NON_SYMBOL_KEYS };
2393 // Add the elements of a JSArray to this FixedArray.
2394 MUST_USE_RESULT static MaybeHandle<FixedArray> AddKeysFromArrayLike(
2395 Handle<FixedArray> content, Handle<JSObject> array,
2396 KeyFilter filter = ALL_KEYS);
2398 // Computes the union of keys and return the result.
2399 // Used for implementing "for (n in object) { }"
2400 MUST_USE_RESULT static MaybeHandle<FixedArray> UnionOfKeys(
2401 Handle<FixedArray> first,
2402 Handle<FixedArray> second);
2404 // Copy a sub array from the receiver to dest.
2405 void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
2407 // Garbage collection support.
2408 static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
2410 // Code Generation support.
2411 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2413 // Garbage collection support.
2414 inline Object** RawFieldOfElementAt(int index);
2416 DECLARE_CAST(FixedArray)
2418 // Maximal allowed size, in bytes, of a single FixedArray.
2419 // Prevents overflowing size computations, as well as extreme memory
2421 static const int kMaxSize = 128 * MB * kPointerSize;
2422 // Maximally allowed length of a FixedArray.
2423 static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
2425 // Dispatched behavior.
2426 DECLARE_PRINTER(FixedArray)
2427 DECLARE_VERIFIER(FixedArray)
2429 // Checks if two FixedArrays have identical contents.
2430 bool IsEqualTo(FixedArray* other);
2433 // Swap two elements in a pair of arrays. If this array and the
2434 // numbers array are the same object, the elements are only swapped
2436 void SwapPairs(FixedArray* numbers, int i, int j);
2438 // Sort prefix of this array and the numbers array as pairs wrt. the
2439 // numbers. If the numbers array and the this array are the same
2440 // object, the prefix of this array is sorted.
2441 void SortPairs(FixedArray* numbers, uint32_t len);
2443 class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
2445 static inline int SizeOf(Map* map, HeapObject* object);
2449 // Set operation on FixedArray without using write barriers. Can
2450 // only be used for storing old space objects or smis.
2451 static inline void NoWriteBarrierSet(FixedArray* array,
2455 // Set operation on FixedArray without incremental write barrier. Can
2456 // only be used if the object is guaranteed to be white (whiteness witness
2458 static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
2463 STATIC_ASSERT(kHeaderSize == Internals::kFixedArrayHeaderSize);
2465 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
2469 // FixedDoubleArray describes fixed-sized arrays with element type double.
2470 class FixedDoubleArray: public FixedArrayBase {
2472 // Setter and getter for elements.
2473 inline double get_scalar(int index);
2474 inline uint64_t get_representation(int index);
2475 static inline Handle<Object> get(Handle<FixedDoubleArray> array, int index);
2476 // This accessor has to get a Number as |value|.
2477 void SetValue(uint32_t index, Object* value);
2478 inline void set(int index, double value);
2479 inline void set_the_hole(int index);
2481 // Checking for the hole.
2482 inline bool is_the_hole(int index);
2484 // Garbage collection support.
2485 inline static int SizeFor(int length) {
2486 return kHeaderSize + length * kDoubleSize;
2489 // Gives access to raw memory which stores the array's data.
2490 inline double* data_start();
2492 inline void FillWithHoles(int from, int to);
2494 // Code Generation support.
2495 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2497 DECLARE_CAST(FixedDoubleArray)
2499 // Maximal allowed size, in bytes, of a single FixedDoubleArray.
2500 // Prevents overflowing size computations, as well as extreme memory
2502 static const int kMaxSize = 512 * MB;
2503 // Maximally allowed length of a FixedArray.
2504 static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
2506 // Dispatched behavior.
2507 DECLARE_PRINTER(FixedDoubleArray)
2508 DECLARE_VERIFIER(FixedDoubleArray)
2511 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
2515 class WeakFixedArray : public FixedArray {
2517 // If |maybe_array| is not a WeakFixedArray, a fresh one will be allocated.
2518 // This function does not check if the value exists already, callers must
2519 // ensure this themselves if necessary.
2520 static Handle<WeakFixedArray> Add(Handle<Object> maybe_array,
2521 Handle<HeapObject> value,
2522 int* assigned_index = NULL);
2524 // Returns true if an entry was found and removed.
2525 bool Remove(Handle<HeapObject> value);
2527 class NullCallback {
2529 static void Callback(Object* value, int old_index, int new_index) {}
2532 template <class CompactionCallback>
2535 inline Object* Get(int index) const;
2536 inline void Clear(int index);
2537 inline int Length() const;
2539 inline bool IsEmptySlot(int index) const;
2540 static Object* Empty() { return Smi::FromInt(0); }
2542 DECLARE_CAST(WeakFixedArray)
2545 static const int kLastUsedIndexIndex = 0;
2546 static const int kFirstIndex = 1;
2548 static Handle<WeakFixedArray> Allocate(
2549 Isolate* isolate, int size, Handle<WeakFixedArray> initialize_from);
2551 static void Set(Handle<WeakFixedArray> array, int index,
2552 Handle<HeapObject> value);
2553 inline void clear(int index);
2555 inline int last_used_index() const;
2556 inline void set_last_used_index(int index);
2558 // Disallow inherited setters.
2559 void set(int index, Smi* value);
2560 void set(int index, Object* value);
2561 void set(int index, Object* value, WriteBarrierMode mode);
2562 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakFixedArray);
2566 // Generic array grows dynamically with O(1) amortized insertion.
2567 class ArrayList : public FixedArray {
2571 // Use this if GC can delete elements from the array.
2572 kReloadLengthAfterAllocation,
2574 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj,
2575 AddMode mode = kNone);
2576 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj1,
2577 Handle<Object> obj2, AddMode = kNone);
2578 inline int Length();
2579 inline void SetLength(int length);
2580 inline Object* Get(int index);
2581 inline Object** Slot(int index);
2582 inline void Set(int index, Object* obj);
2583 inline void Clear(int index, Object* undefined);
2584 DECLARE_CAST(ArrayList)
2587 static Handle<ArrayList> EnsureSpace(Handle<ArrayList> array, int length);
2588 static const int kLengthIndex = 0;
2589 static const int kFirstIndex = 1;
2590 DISALLOW_IMPLICIT_CONSTRUCTORS(ArrayList);
2594 // DescriptorArrays are fixed arrays used to hold instance descriptors.
2595 // The format of the these objects is:
2596 // [0]: Number of descriptors
2597 // [1]: Either Smi(0) if uninitialized, or a pointer to small fixed array:
2598 // [0]: pointer to fixed array with enum cache
2599 // [1]: either Smi(0) or pointer to fixed array with indices
2601 // [2 + number of descriptors * kDescriptorSize]: start of slack
2602 class DescriptorArray: public FixedArray {
2604 // Returns true for both shared empty_descriptor_array and for smis, which the
2605 // map uses to encode additional bit fields when the descriptor array is not
2607 inline bool IsEmpty();
2609 // Returns the number of descriptors in the array.
2610 inline int number_of_descriptors();
2612 inline int number_of_descriptors_storage();
2614 inline int NumberOfSlackDescriptors();
2616 inline void SetNumberOfDescriptors(int number_of_descriptors);
2617 inline int number_of_entries();
2619 inline bool HasEnumCache();
2621 inline void CopyEnumCacheFrom(DescriptorArray* array);
2623 inline FixedArray* GetEnumCache();
2625 inline bool HasEnumIndicesCache();
2627 inline FixedArray* GetEnumIndicesCache();
2629 inline Object** GetEnumCacheSlot();
2631 void ClearEnumCache();
2633 // Initialize or change the enum cache,
2634 // using the supplied storage for the small "bridge".
2635 void SetEnumCache(FixedArray* bridge_storage,
2636 FixedArray* new_cache,
2637 Object* new_index_cache);
2639 bool CanHoldValue(int descriptor, Object* value);
2641 // Accessors for fetching instance descriptor at descriptor number.
2642 inline Name* GetKey(int descriptor_number);
2643 inline Object** GetKeySlot(int descriptor_number);
2644 inline Object* GetValue(int descriptor_number);
2645 inline void SetValue(int descriptor_number, Object* value);
2646 inline Object** GetValueSlot(int descriptor_number);
2647 static inline int GetValueOffset(int descriptor_number);
2648 inline Object** GetDescriptorStartSlot(int descriptor_number);
2649 inline Object** GetDescriptorEndSlot(int descriptor_number);
2650 inline PropertyDetails GetDetails(int descriptor_number);
2651 inline PropertyType GetType(int descriptor_number);
2652 inline int GetFieldIndex(int descriptor_number);
2653 inline HeapType* GetFieldType(int descriptor_number);
2654 inline Object* GetConstant(int descriptor_number);
2655 inline Object* GetCallbacksObject(int descriptor_number);
2656 inline AccessorDescriptor* GetCallbacks(int descriptor_number);
2658 inline Name* GetSortedKey(int descriptor_number);
2659 inline int GetSortedKeyIndex(int descriptor_number);
2660 inline void SetSortedKey(int pointer, int descriptor_number);
2661 inline void SetRepresentation(int descriptor_number,
2662 Representation representation);
2664 // Accessor for complete descriptor.
2665 inline void Get(int descriptor_number, Descriptor* desc);
2666 inline void Set(int descriptor_number, Descriptor* desc);
2667 void Replace(int descriptor_number, Descriptor* descriptor);
2669 // Append automatically sets the enumeration index. This should only be used
2670 // to add descriptors in bulk at the end, followed by sorting the descriptor
2672 inline void Append(Descriptor* desc);
2674 static Handle<DescriptorArray> CopyUpTo(Handle<DescriptorArray> desc,
2675 int enumeration_index,
2678 static Handle<DescriptorArray> CopyUpToAddAttributes(
2679 Handle<DescriptorArray> desc,
2680 int enumeration_index,
2681 PropertyAttributes attributes,
2684 // Sort the instance descriptors by the hash codes of their keys.
2687 // Search the instance descriptors for given name.
2688 INLINE(int Search(Name* name, int number_of_own_descriptors));
2690 // As the above, but uses DescriptorLookupCache and updates it when
2692 INLINE(int SearchWithCache(Name* name, Map* map));
2694 // Allocates a DescriptorArray, but returns the singleton
2695 // empty descriptor array object if number_of_descriptors is 0.
2696 static Handle<DescriptorArray> Allocate(Isolate* isolate,
2697 int number_of_descriptors,
2700 DECLARE_CAST(DescriptorArray)
2702 // Constant for denoting key was not found.
2703 static const int kNotFound = -1;
2705 static const int kDescriptorLengthIndex = 0;
2706 static const int kEnumCacheIndex = 1;
2707 static const int kFirstIndex = 2;
2709 // The length of the "bridge" to the enum cache.
2710 static const int kEnumCacheBridgeLength = 2;
2711 static const int kEnumCacheBridgeCacheIndex = 0;
2712 static const int kEnumCacheBridgeIndicesCacheIndex = 1;
2714 // Layout description.
2715 static const int kDescriptorLengthOffset = FixedArray::kHeaderSize;
2716 static const int kEnumCacheOffset = kDescriptorLengthOffset + kPointerSize;
2717 static const int kFirstOffset = kEnumCacheOffset + kPointerSize;
2719 // Layout description for the bridge array.
2720 static const int kEnumCacheBridgeCacheOffset = FixedArray::kHeaderSize;
2722 // Layout of descriptor.
2723 static const int kDescriptorKey = 0;
2724 static const int kDescriptorDetails = 1;
2725 static const int kDescriptorValue = 2;
2726 static const int kDescriptorSize = 3;
2728 #if defined(DEBUG) || defined(OBJECT_PRINT)
2729 // For our gdb macros, we should perhaps change these in the future.
2732 // Print all the descriptors.
2733 void PrintDescriptors(std::ostream& os); // NOLINT
2737 // Is the descriptor array sorted and without duplicates?
2738 bool IsSortedNoDuplicates(int valid_descriptors = -1);
2740 // Is the descriptor array consistent with the back pointers in targets?
2741 bool IsConsistentWithBackPointers(Map* current_map);
2743 // Are two DescriptorArrays equal?
2744 bool IsEqualTo(DescriptorArray* other);
2747 // Returns the fixed array length required to hold number_of_descriptors
2749 static int LengthFor(int number_of_descriptors) {
2750 return ToKeyIndex(number_of_descriptors);
2754 // WhitenessWitness is used to prove that a descriptor array is white
2755 // (unmarked), so incremental write barriers can be skipped because the
2756 // marking invariant cannot be broken and slots pointing into evacuation
2757 // candidates will be discovered when the object is scanned. A witness is
2758 // always stack-allocated right after creating an array. By allocating a
2759 // witness, incremental marking is globally disabled. The witness is then
2760 // passed along wherever needed to statically prove that the array is known to
2762 class WhitenessWitness {
2764 inline explicit WhitenessWitness(DescriptorArray* array);
2765 inline ~WhitenessWitness();
2768 IncrementalMarking* marking_;
2771 // An entry in a DescriptorArray, represented as an (array, index) pair.
2774 inline explicit Entry(DescriptorArray* descs, int index) :
2775 descs_(descs), index_(index) { }
2777 inline PropertyType type();
2778 inline Object* GetCallbackObject();
2781 DescriptorArray* descs_;
2785 // Conversion from descriptor number to array indices.
2786 static int ToKeyIndex(int descriptor_number) {
2787 return kFirstIndex +
2788 (descriptor_number * kDescriptorSize) +
2792 static int ToDetailsIndex(int descriptor_number) {
2793 return kFirstIndex +
2794 (descriptor_number * kDescriptorSize) +
2798 static int ToValueIndex(int descriptor_number) {
2799 return kFirstIndex +
2800 (descriptor_number * kDescriptorSize) +
2804 // Transfer a complete descriptor from the src descriptor array to this
2805 // descriptor array.
2806 void CopyFrom(int index, DescriptorArray* src, const WhitenessWitness&);
2808 inline void Set(int descriptor_number,
2810 const WhitenessWitness&);
2812 // Swap first and second descriptor.
2813 inline void SwapSortedKeys(int first, int second);
2815 DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
2819 enum SearchMode { ALL_ENTRIES, VALID_ENTRIES };
2821 template <SearchMode search_mode, typename T>
2822 inline int Search(T* array, Name* name, int valid_entries = 0,
2823 int* out_insertion_index = NULL);
2826 // HashTable is a subclass of FixedArray that implements a hash table
2827 // that uses open addressing and quadratic probing.
2829 // In order for the quadratic probing to work, elements that have not
2830 // yet been used and elements that have been deleted are
2831 // distinguished. Probing continues when deleted elements are
2832 // encountered and stops when unused elements are encountered.
2834 // - Elements with key == undefined have not been used yet.
2835 // - Elements with key == the_hole have been deleted.
2837 // The hash table class is parameterized with a Shape and a Key.
2838 // Shape must be a class with the following interface:
2839 // class ExampleShape {
2841 // // Tells whether key matches other.
2842 // static bool IsMatch(Key key, Object* other);
2843 // // Returns the hash value for key.
2844 // static uint32_t Hash(Key key);
2845 // // Returns the hash value for object.
2846 // static uint32_t HashForObject(Key key, Object* object);
2847 // // Convert key to an object.
2848 // static inline Handle<Object> AsHandle(Isolate* isolate, Key key);
2849 // // The prefix size indicates number of elements in the beginning
2850 // // of the backing storage.
2851 // static const int kPrefixSize = ..;
2852 // // The Element size indicates number of elements per entry.
2853 // static const int kEntrySize = ..;
2855 // The prefix size indicates an amount of memory in the
2856 // beginning of the backing storage that can be used for non-element
2857 // information by subclasses.
2859 template<typename Key>
2862 static const bool UsesSeed = false;
2863 static uint32_t Hash(Key key) { return 0; }
2864 static uint32_t SeededHash(Key key, uint32_t seed) {
2868 static uint32_t HashForObject(Key key, Object* object) { return 0; }
2869 static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
2871 return HashForObject(key, object);
2876 class HashTableBase : public FixedArray {
2878 // Returns the number of elements in the hash table.
2879 inline int NumberOfElements();
2881 // Returns the number of deleted elements in the hash table.
2882 inline int NumberOfDeletedElements();
2884 // Returns the capacity of the hash table.
2885 inline int Capacity();
2887 // ElementAdded should be called whenever an element is added to a
2889 inline void ElementAdded();
2891 // ElementRemoved should be called whenever an element is removed from
2893 inline void ElementRemoved();
2894 inline void ElementsRemoved(int n);
2896 // Computes the required capacity for a table holding the given
2897 // number of elements. May be more than HashTable::kMaxCapacity.
2898 static inline int ComputeCapacity(int at_least_space_for);
2900 // Tells whether k is a real key. The hole and undefined are not allowed
2901 // as keys and can be used to indicate missing or deleted elements.
2902 inline bool IsKey(Object* k);
2904 // Compute the probe offset (quadratic probing).
2905 INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
2906 return (n + n * n) >> 1;
2909 static const int kNumberOfElementsIndex = 0;
2910 static const int kNumberOfDeletedElementsIndex = 1;
2911 static const int kCapacityIndex = 2;
2912 static const int kPrefixStartIndex = 3;
2914 // Constant used for denoting a absent entry.
2915 static const int kNotFound = -1;
2918 // Update the number of elements in the hash table.
2919 inline void SetNumberOfElements(int nof);
2921 // Update the number of deleted elements in the hash table.
2922 inline void SetNumberOfDeletedElements(int nod);
2924 // Returns probe entry.
2925 static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
2926 DCHECK(base::bits::IsPowerOfTwo32(size));
2927 return (hash + GetProbeOffset(number)) & (size - 1);
2930 inline static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
2931 return hash & (size - 1);
2934 inline static uint32_t NextProbe(
2935 uint32_t last, uint32_t number, uint32_t size) {
2936 return (last + number) & (size - 1);
2941 template <typename Derived, typename Shape, typename Key>
2942 class HashTable : public HashTableBase {
2945 inline uint32_t Hash(Key key) {
2946 if (Shape::UsesSeed) {
2947 return Shape::SeededHash(key, GetHeap()->HashSeed());
2949 return Shape::Hash(key);
2953 inline uint32_t HashForObject(Key key, Object* object) {
2954 if (Shape::UsesSeed) {
2955 return Shape::SeededHashForObject(key, GetHeap()->HashSeed(), object);
2957 return Shape::HashForObject(key, object);
2961 // Returns a new HashTable object.
2962 MUST_USE_RESULT static Handle<Derived> New(
2963 Isolate* isolate, int at_least_space_for,
2964 MinimumCapacity capacity_option = USE_DEFAULT_MINIMUM_CAPACITY,
2965 PretenureFlag pretenure = NOT_TENURED);
2967 DECLARE_CAST(HashTable)
2969 // Garbage collection support.
2970 void IteratePrefix(ObjectVisitor* visitor);
2971 void IterateElements(ObjectVisitor* visitor);
2973 // Find entry for key otherwise return kNotFound.
2974 inline int FindEntry(Key key);
2975 inline int FindEntry(Isolate* isolate, Key key, int32_t hash);
2976 int FindEntry(Isolate* isolate, Key key);
2978 // Rehashes the table in-place.
2979 void Rehash(Key key);
2981 // Returns the key at entry.
2982 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
2984 static const int kElementsStartIndex = kPrefixStartIndex + Shape::kPrefixSize;
2985 static const int kEntrySize = Shape::kEntrySize;
2986 static const int kElementsStartOffset =
2987 kHeaderSize + kElementsStartIndex * kPointerSize;
2988 static const int kCapacityOffset =
2989 kHeaderSize + kCapacityIndex * kPointerSize;
2991 // Returns the index for an entry (of the key)
2992 static inline int EntryToIndex(int entry) {
2993 return (entry * kEntrySize) + kElementsStartIndex;
2997 friend class ObjectHashTable;
2999 // Find the entry at which to insert element with the given key that
3000 // has the given hash value.
3001 uint32_t FindInsertionEntry(uint32_t hash);
3003 // Attempt to shrink hash table after removal of key.
3004 MUST_USE_RESULT static Handle<Derived> Shrink(Handle<Derived> table, Key key);
3006 // Ensure enough space for n additional elements.
3007 MUST_USE_RESULT static Handle<Derived> EnsureCapacity(
3008 Handle<Derived> table,
3011 PretenureFlag pretenure = NOT_TENURED);
3013 // Sets the capacity of the hash table.
3014 void SetCapacity(int capacity) {
3015 // To scale a computed hash code to fit within the hash table, we
3016 // use bit-wise AND with a mask, so the capacity must be positive
3018 DCHECK(capacity > 0);
3019 DCHECK(capacity <= kMaxCapacity);
3020 set(kCapacityIndex, Smi::FromInt(capacity));
3023 // Maximal capacity of HashTable. Based on maximal length of underlying
3024 // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
3026 static const int kMaxCapacity =
3027 (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
3030 // Returns _expected_ if one of entries given by the first _probe_ probes is
3031 // equal to _expected_. Otherwise, returns the entry given by the probe
3033 uint32_t EntryForProbe(Key key, Object* k, int probe, uint32_t expected);
3035 void Swap(uint32_t entry1, uint32_t entry2, WriteBarrierMode mode);
3037 // Rehashes this hash-table into the new table.
3038 void Rehash(Handle<Derived> new_table, Key key);
3042 // HashTableKey is an abstract superclass for virtual key behavior.
3043 class HashTableKey {
3045 // Returns whether the other object matches this key.
3046 virtual bool IsMatch(Object* other) = 0;
3047 // Returns the hash value for this key.
3048 virtual uint32_t Hash() = 0;
3049 // Returns the hash value for object.
3050 virtual uint32_t HashForObject(Object* key) = 0;
3051 // Returns the key object for storing into the hash table.
3052 MUST_USE_RESULT virtual Handle<Object> AsHandle(Isolate* isolate) = 0;
3054 virtual ~HashTableKey() {}
3058 class StringTableShape : public BaseShape<HashTableKey*> {
3060 static inline bool IsMatch(HashTableKey* key, Object* value) {
3061 return key->IsMatch(value);
3064 static inline uint32_t Hash(HashTableKey* key) {
3068 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3069 return key->HashForObject(object);
3072 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3074 static const int kPrefixSize = 0;
3075 static const int kEntrySize = 1;
3078 class SeqOneByteString;
3082 // No special elements in the prefix and the element size is 1
3083 // because only the string itself (the key) needs to be stored.
3084 class StringTable: public HashTable<StringTable,
3088 // Find string in the string table. If it is not there yet, it is
3089 // added. The return value is the string found.
3090 static Handle<String> LookupString(Isolate* isolate, Handle<String> key);
3091 static Handle<String> LookupKey(Isolate* isolate, HashTableKey* key);
3092 static String* LookupKeyIfExists(Isolate* isolate, HashTableKey* key);
3094 // Tries to internalize given string and returns string handle on success
3095 // or an empty handle otherwise.
3096 MUST_USE_RESULT static MaybeHandle<String> InternalizeStringIfExists(
3098 Handle<String> string);
3100 // Looks up a string that is equal to the given string and returns
3101 // string handle if it is found, or an empty handle otherwise.
3102 MUST_USE_RESULT static MaybeHandle<String> LookupStringIfExists(
3104 Handle<String> str);
3105 MUST_USE_RESULT static MaybeHandle<String> LookupTwoCharsStringIfExists(
3110 static void EnsureCapacityForDeserialization(Isolate* isolate, int expected);
3112 DECLARE_CAST(StringTable)
3115 template <bool seq_one_byte>
3116 friend class JsonParser;
3118 DISALLOW_IMPLICIT_CONSTRUCTORS(StringTable);
3122 template <typename Derived, typename Shape, typename Key>
3123 class Dictionary: public HashTable<Derived, Shape, Key> {
3124 typedef HashTable<Derived, Shape, Key> DerivedHashTable;
3127 // Returns the value at entry.
3128 Object* ValueAt(int entry) {
3129 return this->get(Derived::EntryToIndex(entry) + 1);
3132 // Set the value for entry.
3133 void ValueAtPut(int entry, Object* value) {
3134 this->set(Derived::EntryToIndex(entry) + 1, value);
3137 // Returns the property details for the property at entry.
3138 PropertyDetails DetailsAt(int entry) {
3139 return Shape::DetailsAt(static_cast<Derived*>(this), entry);
3142 // Set the details for entry.
3143 void DetailsAtPut(int entry, PropertyDetails value) {
3144 Shape::DetailsAtPut(static_cast<Derived*>(this), entry, value);
3147 // Returns true if property at given entry is deleted.
3148 bool IsDeleted(int entry) {
3149 return Shape::IsDeleted(static_cast<Derived*>(this), entry);
3152 // Delete a property from the dictionary.
3153 static Handle<Object> DeleteProperty(Handle<Derived> dictionary, int entry);
3155 // Attempt to shrink the dictionary after deletion of key.
3156 MUST_USE_RESULT static inline Handle<Derived> Shrink(
3157 Handle<Derived> dictionary,
3159 return DerivedHashTable::Shrink(dictionary, key);
3163 // TODO(dcarney): templatize or move to SeededNumberDictionary
3164 void CopyValuesTo(FixedArray* elements);
3166 // Returns the number of elements in the dictionary filtering out properties
3167 // with the specified attributes.
3168 int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3170 // Returns the number of enumerable elements in the dictionary.
3171 int NumberOfEnumElements() {
3172 return NumberOfElementsFilterAttributes(
3173 static_cast<PropertyAttributes>(DONT_ENUM | SYMBOLIC));
3176 // Returns true if the dictionary contains any elements that are non-writable,
3177 // non-configurable, non-enumerable, or have getters/setters.
3178 bool HasComplexElements();
3180 enum SortMode { UNSORTED, SORTED };
3182 // Fill in details for properties into storage.
3183 // Returns the number of properties added.
3184 int CopyKeysTo(FixedArray* storage, int index, PropertyAttributes filter,
3185 SortMode sort_mode);
3187 // Copies enumerable keys to preallocated fixed array.
3188 void CopyEnumKeysTo(FixedArray* storage);
3190 // Accessors for next enumeration index.
3191 void SetNextEnumerationIndex(int index) {
3193 this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
3196 int NextEnumerationIndex() {
3197 return Smi::cast(this->get(kNextEnumerationIndexIndex))->value();
3200 // Creates a new dictionary.
3201 MUST_USE_RESULT static Handle<Derived> New(
3203 int at_least_space_for,
3204 PretenureFlag pretenure = NOT_TENURED);
3206 // Ensure enough space for n additional elements.
3207 static Handle<Derived> EnsureCapacity(Handle<Derived> obj, int n, Key key);
3210 void Print(std::ostream& os); // NOLINT
3212 // Returns the key (slow).
3213 Object* SlowReverseLookup(Object* value);
3215 // Sets the entry to (key, value) pair.
3216 inline void SetEntry(int entry,
3218 Handle<Object> value);
3219 inline void SetEntry(int entry,
3221 Handle<Object> value,
3222 PropertyDetails details);
3224 MUST_USE_RESULT static Handle<Derived> Add(
3225 Handle<Derived> dictionary,
3227 Handle<Object> value,
3228 PropertyDetails details);
3230 // Returns iteration indices array for the |dictionary|.
3231 // Values are direct indices in the |HashTable| array.
3232 static Handle<FixedArray> BuildIterationIndicesArray(
3233 Handle<Derived> dictionary);
3236 // Generic at put operation.
3237 MUST_USE_RESULT static Handle<Derived> AtPut(
3238 Handle<Derived> dictionary,
3240 Handle<Object> value);
3242 // Add entry to dictionary.
3243 static void AddEntry(
3244 Handle<Derived> dictionary,
3246 Handle<Object> value,
3247 PropertyDetails details,
3250 // Generate new enumeration indices to avoid enumeration index overflow.
3251 // Returns iteration indices array for the |dictionary|.
3252 static Handle<FixedArray> GenerateNewEnumerationIndices(
3253 Handle<Derived> dictionary);
3254 static const int kMaxNumberKeyIndex = DerivedHashTable::kPrefixStartIndex;
3255 static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
3259 template <typename Derived, typename Shape>
3260 class NameDictionaryBase : public Dictionary<Derived, Shape, Handle<Name> > {
3261 typedef Dictionary<Derived, Shape, Handle<Name> > DerivedDictionary;
3264 // Find entry for key, otherwise return kNotFound. Optimized version of
3265 // HashTable::FindEntry.
3266 int FindEntry(Handle<Name> key);
3270 template <typename Key>
3271 class BaseDictionaryShape : public BaseShape<Key> {
3273 template <typename Dictionary>
3274 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry) {
3275 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3276 DCHECK(entry >= 0); // Not found is -1, which is not caught by get().
3277 return PropertyDetails(
3278 Smi::cast(dict->get(Dictionary::EntryToIndex(entry) + 2)));
3281 template <typename Dictionary>
3282 static inline void DetailsAtPut(Dictionary* dict, int entry,
3283 PropertyDetails value) {
3284 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3285 dict->set(Dictionary::EntryToIndex(entry) + 2, value.AsSmi());
3288 template <typename Dictionary>
3289 static bool IsDeleted(Dictionary* dict, int entry) {
3293 template <typename Dictionary>
3294 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3295 Handle<Object> value, PropertyDetails details);
3299 class NameDictionaryShape : public BaseDictionaryShape<Handle<Name> > {
3301 static inline bool IsMatch(Handle<Name> key, Object* other);
3302 static inline uint32_t Hash(Handle<Name> key);
3303 static inline uint32_t HashForObject(Handle<Name> key, Object* object);
3304 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Name> key);
3305 static const int kPrefixSize = 2;
3306 static const int kEntrySize = 3;
3307 static const bool kIsEnumerable = true;
3311 class NameDictionary
3312 : public NameDictionaryBase<NameDictionary, NameDictionaryShape> {
3313 typedef NameDictionaryBase<NameDictionary, NameDictionaryShape>
3317 DECLARE_CAST(NameDictionary)
3319 inline static Handle<FixedArray> DoGenerateNewEnumerationIndices(
3320 Handle<NameDictionary> dictionary);
3324 class GlobalDictionaryShape : public NameDictionaryShape {
3326 static const int kEntrySize = 2; // Overrides NameDictionaryShape::kEntrySize
3328 template <typename Dictionary>
3329 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry);
3331 template <typename Dictionary>
3332 static inline void DetailsAtPut(Dictionary* dict, int entry,
3333 PropertyDetails value);
3335 template <typename Dictionary>
3336 static bool IsDeleted(Dictionary* dict, int entry);
3338 template <typename Dictionary>
3339 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3340 Handle<Object> value, PropertyDetails details);
3344 class GlobalDictionary
3345 : public NameDictionaryBase<GlobalDictionary, GlobalDictionaryShape> {
3347 DECLARE_CAST(GlobalDictionary)
3351 class NumberDictionaryShape : public BaseDictionaryShape<uint32_t> {
3353 static inline bool IsMatch(uint32_t key, Object* other);
3354 static inline Handle<Object> AsHandle(Isolate* isolate, uint32_t key);
3355 static const int kEntrySize = 3;
3356 static const bool kIsEnumerable = false;
3360 class SeededNumberDictionaryShape : public NumberDictionaryShape {
3362 static const bool UsesSeed = true;
3363 static const int kPrefixSize = 2;
3365 static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
3366 static inline uint32_t SeededHashForObject(uint32_t key,
3372 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
3374 static const int kPrefixSize = 0;
3376 static inline uint32_t Hash(uint32_t key);
3377 static inline uint32_t HashForObject(uint32_t key, Object* object);
3381 class SeededNumberDictionary
3382 : public Dictionary<SeededNumberDictionary,
3383 SeededNumberDictionaryShape,
3386 DECLARE_CAST(SeededNumberDictionary)
3388 // Type specific at put (default NONE attributes is used when adding).
3389 MUST_USE_RESULT static Handle<SeededNumberDictionary> AtNumberPut(
3390 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3391 Handle<Object> value, bool used_as_prototype);
3392 MUST_USE_RESULT static Handle<SeededNumberDictionary> AddNumberEntry(
3393 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3394 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3396 // Set an existing entry or add a new one if needed.
3397 // Return the updated dictionary.
3398 MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
3399 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3400 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3402 void UpdateMaxNumberKey(uint32_t key, bool used_as_prototype);
3404 // If slow elements are required we will never go back to fast-case
3405 // for the elements kept in this dictionary. We require slow
3406 // elements if an element has been added at an index larger than
3407 // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
3408 // when defining a getter or setter with a number key.
3409 inline bool requires_slow_elements();
3410 inline void set_requires_slow_elements();
3412 // Get the value of the max number key that has been added to this
3413 // dictionary. max_number_key can only be called if
3414 // requires_slow_elements returns false.
3415 inline uint32_t max_number_key();
3418 static const int kRequiresSlowElementsMask = 1;
3419 static const int kRequiresSlowElementsTagSize = 1;
3420 static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
3424 class UnseededNumberDictionary
3425 : public Dictionary<UnseededNumberDictionary,
3426 UnseededNumberDictionaryShape,
3429 DECLARE_CAST(UnseededNumberDictionary)
3431 // Type specific at put (default NONE attributes is used when adding).
3432 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AtNumberPut(
3433 Handle<UnseededNumberDictionary> dictionary,
3435 Handle<Object> value);
3436 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AddNumberEntry(
3437 Handle<UnseededNumberDictionary> dictionary,
3439 Handle<Object> value);
3441 // Set an existing entry or add a new one if needed.
3442 // Return the updated dictionary.
3443 MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
3444 Handle<UnseededNumberDictionary> dictionary,
3446 Handle<Object> value);
3450 class ObjectHashTableShape : public BaseShape<Handle<Object> > {
3452 static inline bool IsMatch(Handle<Object> key, Object* other);
3453 static inline uint32_t Hash(Handle<Object> key);
3454 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3455 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3456 static const int kPrefixSize = 0;
3457 static const int kEntrySize = 2;
3461 // ObjectHashTable maps keys that are arbitrary objects to object values by
3462 // using the identity hash of the key for hashing purposes.
3463 class ObjectHashTable: public HashTable<ObjectHashTable,
3464 ObjectHashTableShape,
3467 ObjectHashTable, ObjectHashTableShape, Handle<Object> > DerivedHashTable;
3469 DECLARE_CAST(ObjectHashTable)
3471 // Attempt to shrink hash table after removal of key.
3472 MUST_USE_RESULT static inline Handle<ObjectHashTable> Shrink(
3473 Handle<ObjectHashTable> table,
3474 Handle<Object> key);
3476 // Looks up the value associated with the given key. The hole value is
3477 // returned in case the key is not present.
3478 Object* Lookup(Handle<Object> key);
3479 Object* Lookup(Handle<Object> key, int32_t hash);
3480 Object* Lookup(Isolate* isolate, Handle<Object> key, int32_t hash);
3482 // Adds (or overwrites) the value associated with the given key.
3483 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3485 Handle<Object> value);
3486 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3487 Handle<Object> key, Handle<Object> value,
3490 // Returns an ObjectHashTable (possibly |table|) where |key| has been removed.
3491 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3494 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3495 Handle<Object> key, bool* was_present,
3499 friend class MarkCompactCollector;
3501 void AddEntry(int entry, Object* key, Object* value);
3502 void RemoveEntry(int entry);
3504 // Returns the index to the value of an entry.
3505 static inline int EntryToValueIndex(int entry) {
3506 return EntryToIndex(entry) + 1;
3511 // OrderedHashTable is a HashTable with Object keys that preserves
3512 // insertion order. There are Map and Set interfaces (OrderedHashMap
3513 // and OrderedHashTable, below). It is meant to be used by JSMap/JSSet.
3515 // Only Object* keys are supported, with Object::SameValueZero() used as the
3516 // equality operator and Object::GetHash() for the hash function.
3518 // Based on the "Deterministic Hash Table" as described by Jason Orendorff at
3519 // https://wiki.mozilla.org/User:Jorend/Deterministic_hash_tables
3520 // Originally attributed to Tyler Close.
3523 // [0]: bucket count
3524 // [1]: element count
3525 // [2]: deleted element count
3526 // [3..(3 + NumberOfBuckets() - 1)]: "hash table", where each item is an
3527 // offset into the data table (see below) where the
3528 // first item in this bucket is stored.
3529 // [3 + NumberOfBuckets()..length]: "data table", an array of length
3530 // Capacity() * kEntrySize, where the first entrysize
3531 // items are handled by the derived class and the
3532 // item at kChainOffset is another entry into the
3533 // data table indicating the next entry in this hash
3536 // When we transition the table to a new version we obsolete it and reuse parts
3537 // of the memory to store information how to transition an iterator to the new
3540 // Memory layout for obsolete table:
3541 // [0]: bucket count
3542 // [1]: Next newer table
3543 // [2]: Number of removed holes or -1 when the table was cleared.
3544 // [3..(3 + NumberOfRemovedHoles() - 1)]: The indexes of the removed holes.
3545 // [3 + NumberOfRemovedHoles()..length]: Not used
3547 template<class Derived, class Iterator, int entrysize>
3548 class OrderedHashTable: public FixedArray {
3550 // Returns an OrderedHashTable with a capacity of at least |capacity|.
3551 static Handle<Derived> Allocate(
3552 Isolate* isolate, int capacity, PretenureFlag pretenure = NOT_TENURED);
3554 // Returns an OrderedHashTable (possibly |table|) with enough space
3555 // to add at least one new element.
3556 static Handle<Derived> EnsureGrowable(Handle<Derived> table);
3558 // Returns an OrderedHashTable (possibly |table|) that's shrunken
3560 static Handle<Derived> Shrink(Handle<Derived> table);
3562 // Returns a new empty OrderedHashTable and records the clearing so that
3563 // exisiting iterators can be updated.
3564 static Handle<Derived> Clear(Handle<Derived> table);
3566 int NumberOfElements() {
3567 return Smi::cast(get(kNumberOfElementsIndex))->value();
3570 int NumberOfDeletedElements() {
3571 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3574 int UsedCapacity() { return NumberOfElements() + NumberOfDeletedElements(); }
3576 int NumberOfBuckets() {
3577 return Smi::cast(get(kNumberOfBucketsIndex))->value();
3580 // Returns an index into |this| for the given entry.
3581 int EntryToIndex(int entry) {
3582 return kHashTableStartIndex + NumberOfBuckets() + (entry * kEntrySize);
3585 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3588 return !get(kNextTableIndex)->IsSmi();
3591 // The next newer table. This is only valid if the table is obsolete.
3592 Derived* NextTable() {
3593 return Derived::cast(get(kNextTableIndex));
3596 // When the table is obsolete we store the indexes of the removed holes.
3597 int RemovedIndexAt(int index) {
3598 return Smi::cast(get(kRemovedHolesIndex + index))->value();
3601 static const int kNotFound = -1;
3602 static const int kMinCapacity = 4;
3604 static const int kNumberOfBucketsIndex = 0;
3605 static const int kNumberOfElementsIndex = kNumberOfBucketsIndex + 1;
3606 static const int kNumberOfDeletedElementsIndex = kNumberOfElementsIndex + 1;
3607 static const int kHashTableStartIndex = kNumberOfDeletedElementsIndex + 1;
3608 static const int kNextTableIndex = kNumberOfElementsIndex;
3610 static const int kNumberOfBucketsOffset =
3611 kHeaderSize + kNumberOfBucketsIndex * kPointerSize;
3612 static const int kNumberOfElementsOffset =
3613 kHeaderSize + kNumberOfElementsIndex * kPointerSize;
3614 static const int kNumberOfDeletedElementsOffset =
3615 kHeaderSize + kNumberOfDeletedElementsIndex * kPointerSize;
3616 static const int kHashTableStartOffset =
3617 kHeaderSize + kHashTableStartIndex * kPointerSize;
3618 static const int kNextTableOffset =
3619 kHeaderSize + kNextTableIndex * kPointerSize;
3621 static const int kEntrySize = entrysize + 1;
3622 static const int kChainOffset = entrysize;
3624 static const int kLoadFactor = 2;
3626 // NumberOfDeletedElements is set to kClearedTableSentinel when
3627 // the table is cleared, which allows iterator transitions to
3628 // optimize that case.
3629 static const int kClearedTableSentinel = -1;
3632 static Handle<Derived> Rehash(Handle<Derived> table, int new_capacity);
3634 void SetNumberOfBuckets(int num) {
3635 set(kNumberOfBucketsIndex, Smi::FromInt(num));
3638 void SetNumberOfElements(int num) {
3639 set(kNumberOfElementsIndex, Smi::FromInt(num));
3642 void SetNumberOfDeletedElements(int num) {
3643 set(kNumberOfDeletedElementsIndex, Smi::FromInt(num));
3647 return NumberOfBuckets() * kLoadFactor;
3650 void SetNextTable(Derived* next_table) {
3651 set(kNextTableIndex, next_table);
3654 void SetRemovedIndexAt(int index, int removed_index) {
3655 return set(kRemovedHolesIndex + index, Smi::FromInt(removed_index));
3658 static const int kRemovedHolesIndex = kHashTableStartIndex;
3660 static const int kMaxCapacity =
3661 (FixedArray::kMaxLength - kHashTableStartIndex)
3662 / (1 + (kEntrySize * kLoadFactor));
3666 class JSSetIterator;
3669 class OrderedHashSet: public OrderedHashTable<
3670 OrderedHashSet, JSSetIterator, 1> {
3672 DECLARE_CAST(OrderedHashSet)
3676 class JSMapIterator;
3679 class OrderedHashMap
3680 : public OrderedHashTable<OrderedHashMap, JSMapIterator, 2> {
3682 DECLARE_CAST(OrderedHashMap)
3684 inline Object* ValueAt(int entry);
3686 static const int kValueOffset = 1;
3690 template <int entrysize>
3691 class WeakHashTableShape : public BaseShape<Handle<Object> > {
3693 static inline bool IsMatch(Handle<Object> key, Object* other);
3694 static inline uint32_t Hash(Handle<Object> key);
3695 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3696 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3697 static const int kPrefixSize = 0;
3698 static const int kEntrySize = entrysize;
3702 // WeakHashTable maps keys that are arbitrary heap objects to heap object
3703 // values. The table wraps the keys in weak cells and store values directly.
3704 // Thus it references keys weakly and values strongly.
3705 class WeakHashTable: public HashTable<WeakHashTable,
3706 WeakHashTableShape<2>,
3709 WeakHashTable, WeakHashTableShape<2>, Handle<Object> > DerivedHashTable;
3711 DECLARE_CAST(WeakHashTable)
3713 // Looks up the value associated with the given key. The hole value is
3714 // returned in case the key is not present.
3715 Object* Lookup(Handle<HeapObject> key);
3717 // Adds (or overwrites) the value associated with the given key. Mapping a
3718 // key to the hole value causes removal of the whole entry.
3719 MUST_USE_RESULT static Handle<WeakHashTable> Put(Handle<WeakHashTable> table,
3720 Handle<HeapObject> key,
3721 Handle<HeapObject> value);
3723 static Handle<FixedArray> GetValues(Handle<WeakHashTable> table);
3726 friend class MarkCompactCollector;
3728 void AddEntry(int entry, Handle<WeakCell> key, Handle<HeapObject> value);
3730 // Returns the index to the value of an entry.
3731 static inline int EntryToValueIndex(int entry) {
3732 return EntryToIndex(entry) + 1;
3737 class WeakValueHashTable : public ObjectHashTable {
3739 DECLARE_CAST(WeakValueHashTable)
3742 // Looks up the value associated with the given key. The hole value is
3743 // returned in case the key is not present.
3744 Object* LookupWeak(Handle<Object> key);
3747 // Adds (or overwrites) the value associated with the given key. Mapping a
3748 // key to the hole value causes removal of the whole entry.
3749 MUST_USE_RESULT static Handle<WeakValueHashTable> PutWeak(
3750 Handle<WeakValueHashTable> table, Handle<Object> key,
3751 Handle<HeapObject> value);
3753 static Handle<FixedArray> GetWeakValues(Handle<WeakValueHashTable> table);
3757 // ScopeInfo represents information about different scopes of a source
3758 // program and the allocation of the scope's variables. Scope information
3759 // is stored in a compressed form in ScopeInfo objects and is used
3760 // at runtime (stack dumps, deoptimization, etc.).
3762 // This object provides quick access to scope info details for runtime
3764 class ScopeInfo : public FixedArray {
3766 DECLARE_CAST(ScopeInfo)
3768 // Return the type of this scope.
3769 ScopeType scope_type();
3771 // Does this scope call eval?
3774 // Return the language mode of this scope.
3775 LanguageMode language_mode();
3777 // Does this scope make a sloppy eval call?
3778 bool CallsSloppyEval() { return CallsEval() && is_sloppy(language_mode()); }
3780 // Return the total number of locals allocated on the stack and in the
3781 // context. This includes the parameters that are allocated in the context.
3784 // Return the number of stack slots for code. This number consists of two
3786 // 1. One stack slot per stack allocated local.
3787 // 2. One stack slot for the function name if it is stack allocated.
3788 int StackSlotCount();
3790 // Return the number of context slots for code if a context is allocated. This
3791 // number consists of three parts:
3792 // 1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
3793 // 2. One context slot per context allocated local.
3794 // 3. One context slot for the function name if it is context allocated.
3795 // Parameters allocated in the context count as context allocated locals. If
3796 // no contexts are allocated for this scope ContextLength returns 0.
3797 int ContextLength();
3799 // Does this scope declare a "this" binding?
3802 // Does this scope declare a "this" binding, and the "this" binding is stack-
3803 // or context-allocated?
3804 bool HasAllocatedReceiver();
3806 // Is this scope the scope of a named function expression?
3807 bool HasFunctionName();
3809 // Return if this has context allocated locals.
3810 bool HasHeapAllocatedLocals();
3812 // Return if contexts are allocated for this scope.
3815 // Return if this is a function scope with "use asm".
3816 inline bool IsAsmModule();
3818 // Return if this is a nested function within an asm module scope.
3819 inline bool IsAsmFunction();
3821 inline bool HasSimpleParameters();
3823 // Return the function_name if present.
3824 String* FunctionName();
3826 // Return the name of the given parameter.
3827 String* ParameterName(int var);
3829 // Return the name of the given local.
3830 String* LocalName(int var);
3832 // Return the name of the given stack local.
3833 String* StackLocalName(int var);
3835 // Return the name of the given stack local.
3836 int StackLocalIndex(int var);
3838 // Return the name of the given context local.
3839 String* ContextLocalName(int var);
3841 // Return the mode of the given context local.
3842 VariableMode ContextLocalMode(int var);
3844 // Return the initialization flag of the given context local.
3845 InitializationFlag ContextLocalInitFlag(int var);
3847 // Return the initialization flag of the given context local.
3848 MaybeAssignedFlag ContextLocalMaybeAssignedFlag(int var);
3850 // Return true if this local was introduced by the compiler, and should not be
3851 // exposed to the user in a debugger.
3852 bool LocalIsSynthetic(int var);
3854 String* StrongModeFreeVariableName(int var);
3855 int StrongModeFreeVariableStartPosition(int var);
3856 int StrongModeFreeVariableEndPosition(int var);
3858 // Lookup support for serialized scope info. Returns the
3859 // the stack slot index for a given slot name if the slot is
3860 // present; otherwise returns a value < 0. The name must be an internalized
3862 int StackSlotIndex(String* name);
3864 // Lookup support for serialized scope info. Returns the
3865 // context slot index for a given slot name if the slot is present; otherwise
3866 // returns a value < 0. The name must be an internalized string.
3867 // If the slot is present and mode != NULL, sets *mode to the corresponding
3868 // mode for that variable.
3869 static int ContextSlotIndex(Handle<ScopeInfo> scope_info, Handle<String> name,
3870 VariableMode* mode, VariableLocation* location,
3871 InitializationFlag* init_flag,
3872 MaybeAssignedFlag* maybe_assigned_flag);
3874 // Lookup the name of a certain context slot by its index.
3875 String* ContextSlotName(int slot_index);
3877 // Lookup support for serialized scope info. Returns the
3878 // parameter index for a given parameter name if the parameter is present;
3879 // otherwise returns a value < 0. The name must be an internalized string.
3880 int ParameterIndex(String* name);
3882 // Lookup support for serialized scope info. Returns the function context
3883 // slot index if the function name is present and context-allocated (named
3884 // function expressions, only), otherwise returns a value < 0. The name
3885 // must be an internalized string.
3886 int FunctionContextSlotIndex(String* name, VariableMode* mode);
3888 // Lookup support for serialized scope info. Returns the receiver context
3889 // slot index if scope has a "this" binding, and the binding is
3890 // context-allocated. Otherwise returns a value < 0.
3891 int ReceiverContextSlotIndex();
3893 FunctionKind function_kind();
3895 static Handle<ScopeInfo> Create(Isolate* isolate, Zone* zone, Scope* scope);
3896 static Handle<ScopeInfo> CreateGlobalThisBinding(Isolate* isolate);
3898 // Serializes empty scope info.
3899 static ScopeInfo* Empty(Isolate* isolate);
3905 // The layout of the static part of a ScopeInfo is as follows. Each entry is
3906 // numeric and occupies one array slot.
3907 // 1. A set of properties of the scope
3908 // 2. The number of parameters. This only applies to function scopes. For
3909 // non-function scopes this is 0.
3910 // 3. The number of non-parameter variables allocated on the stack.
3911 // 4. The number of non-parameter and parameter variables allocated in the
3913 #define FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(V) \
3916 V(StackLocalCount) \
3917 V(ContextLocalCount) \
3918 V(ContextGlobalCount) \
3919 V(StrongModeFreeVariableCount)
3921 #define FIELD_ACCESSORS(name) \
3922 inline void Set##name(int value); \
3924 FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(FIELD_ACCESSORS)
3925 #undef FIELD_ACCESSORS
3929 #define DECL_INDEX(name) k##name,
3930 FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(DECL_INDEX)
3935 // The layout of the variable part of a ScopeInfo is as follows:
3936 // 1. ParameterEntries:
3937 // This part stores the names of the parameters for function scopes. One
3938 // slot is used per parameter, so in total this part occupies
3939 // ParameterCount() slots in the array. For other scopes than function
3940 // scopes ParameterCount() is 0.
3941 // 2. StackLocalFirstSlot:
3942 // Index of a first stack slot for stack local. Stack locals belonging to
3943 // this scope are located on a stack at slots starting from this index.
3944 // 3. StackLocalEntries:
3945 // Contains the names of local variables that are allocated on the stack,
3946 // in increasing order of the stack slot index. First local variable has
3947 // a stack slot index defined in StackLocalFirstSlot (point 2 above).
3948 // One slot is used per stack local, so in total this part occupies
3949 // StackLocalCount() slots in the array.
3950 // 4. ContextLocalNameEntries:
3951 // Contains the names of local variables and parameters that are allocated
3952 // in the context. They are stored in increasing order of the context slot
3953 // index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
3954 // context local, so in total this part occupies ContextLocalCount() slots
3956 // 5. ContextLocalInfoEntries:
3957 // Contains the variable modes and initialization flags corresponding to
3958 // the context locals in ContextLocalNameEntries. One slot is used per
3959 // context local, so in total this part occupies ContextLocalCount()
3960 // slots in the array.
3961 // 6. StrongModeFreeVariableNameEntries:
3962 // Stores the names of strong mode free variables.
3963 // 7. StrongModeFreeVariablePositionEntries:
3964 // Stores the locations (start and end position) of strong mode free
3966 // 8. RecieverEntryIndex:
3967 // If the scope binds a "this" value, one slot is reserved to hold the
3968 // context or stack slot index for the variable.
3969 // 9. FunctionNameEntryIndex:
3970 // If the scope belongs to a named function expression this part contains
3971 // information about the function variable. It always occupies two array
3972 // slots: a. The name of the function variable.
3973 // b. The context or stack slot index for the variable.
3974 int ParameterEntriesIndex();
3975 int StackLocalFirstSlotIndex();
3976 int StackLocalEntriesIndex();
3977 int ContextLocalNameEntriesIndex();
3978 int ContextGlobalNameEntriesIndex();
3979 int ContextLocalInfoEntriesIndex();
3980 int ContextGlobalInfoEntriesIndex();
3981 int StrongModeFreeVariableNameEntriesIndex();
3982 int StrongModeFreeVariablePositionEntriesIndex();
3983 int ReceiverEntryIndex();
3984 int FunctionNameEntryIndex();
3986 int Lookup(Handle<String> name, int start, int end, VariableMode* mode,
3987 VariableLocation* location, InitializationFlag* init_flag,
3988 MaybeAssignedFlag* maybe_assigned_flag);
3990 // Used for the function name variable for named function expressions, and for
3992 enum VariableAllocationInfo { NONE, STACK, CONTEXT, UNUSED };
3994 // Properties of scopes.
3995 class ScopeTypeField : public BitField<ScopeType, 0, 4> {};
3996 class CallsEvalField : public BitField<bool, ScopeTypeField::kNext, 1> {};
3997 STATIC_ASSERT(LANGUAGE_END == 3);
3998 class LanguageModeField
3999 : public BitField<LanguageMode, CallsEvalField::kNext, 2> {};
4000 class ReceiverVariableField
4001 : public BitField<VariableAllocationInfo, LanguageModeField::kNext, 2> {};
4002 class FunctionVariableField
4003 : public BitField<VariableAllocationInfo, ReceiverVariableField::kNext,
4005 class FunctionVariableMode
4006 : public BitField<VariableMode, FunctionVariableField::kNext, 3> {};
4007 class AsmModuleField : public BitField<bool, FunctionVariableMode::kNext, 1> {
4009 class AsmFunctionField : public BitField<bool, AsmModuleField::kNext, 1> {};
4010 class HasSimpleParametersField
4011 : public BitField<bool, AsmFunctionField::kNext, 1> {};
4012 class FunctionKindField
4013 : public BitField<FunctionKind, HasSimpleParametersField::kNext, 8> {};
4015 // BitFields representing the encoded information for context locals in the
4016 // ContextLocalInfoEntries part.
4017 class ContextLocalMode: public BitField<VariableMode, 0, 3> {};
4018 class ContextLocalInitFlag: public BitField<InitializationFlag, 3, 1> {};
4019 class ContextLocalMaybeAssignedFlag
4020 : public BitField<MaybeAssignedFlag, 4, 1> {};
4022 friend class ScopeIterator;
4026 // The cache for maps used by normalized (dictionary mode) objects.
4027 // Such maps do not have property descriptors, so a typical program
4028 // needs very limited number of distinct normalized maps.
4029 class NormalizedMapCache: public FixedArray {
4031 static Handle<NormalizedMapCache> New(Isolate* isolate);
4033 MUST_USE_RESULT MaybeHandle<Map> Get(Handle<Map> fast_map,
4034 PropertyNormalizationMode mode);
4035 void Set(Handle<Map> fast_map, Handle<Map> normalized_map);
4039 DECLARE_CAST(NormalizedMapCache)
4041 static inline bool IsNormalizedMapCache(const Object* obj);
4043 DECLARE_VERIFIER(NormalizedMapCache)
4045 static const int kEntries = 64;
4047 static inline int GetIndex(Handle<Map> map);
4049 // The following declarations hide base class methods.
4050 Object* get(int index);
4051 void set(int index, Object* value);
4055 // ByteArray represents fixed sized byte arrays. Used for the relocation info
4056 // that is attached to code objects.
4057 class ByteArray: public FixedArrayBase {
4061 // Setter and getter.
4062 inline byte get(int index);
4063 inline void set(int index, byte value);
4065 // Treat contents as an int array.
4066 inline int get_int(int index);
4068 static int SizeFor(int length) {
4069 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4071 // We use byte arrays for free blocks in the heap. Given a desired size in
4072 // bytes that is a multiple of the word size and big enough to hold a byte
4073 // array, this function returns the number of elements a byte array should
4075 static int LengthFor(int size_in_bytes) {
4076 DCHECK(IsAligned(size_in_bytes, kPointerSize));
4077 DCHECK(size_in_bytes >= kHeaderSize);
4078 return size_in_bytes - kHeaderSize;
4081 // Returns data start address.
4082 inline Address GetDataStartAddress();
4084 // Returns a pointer to the ByteArray object for a given data start address.
4085 static inline ByteArray* FromDataStartAddress(Address address);
4087 DECLARE_CAST(ByteArray)
4089 // Dispatched behavior.
4090 inline int ByteArraySize();
4091 DECLARE_PRINTER(ByteArray)
4092 DECLARE_VERIFIER(ByteArray)
4094 // Layout description.
4095 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4097 // Maximal memory consumption for a single ByteArray.
4098 static const int kMaxSize = 512 * MB;
4099 // Maximal length of a single ByteArray.
4100 static const int kMaxLength = kMaxSize - kHeaderSize;
4103 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4107 // BytecodeArray represents a sequence of interpreter bytecodes.
4108 class BytecodeArray : public FixedArrayBase {
4110 static int SizeFor(int length) {
4111 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4114 // Setter and getter
4115 inline byte get(int index);
4116 inline void set(int index, byte value);
4118 // Returns data start address.
4119 inline Address GetFirstBytecodeAddress();
4121 // Accessors for frame size and the number of locals
4122 inline int frame_size() const;
4123 inline void set_frame_size(int value);
4125 DECLARE_CAST(BytecodeArray)
4127 // Dispatched behavior.
4128 inline int BytecodeArraySize();
4130 DECLARE_PRINTER(BytecodeArray)
4131 DECLARE_VERIFIER(BytecodeArray)
4133 void Disassemble(std::ostream& os);
4135 // Layout description.
4136 static const int kFrameSizeOffset = FixedArrayBase::kHeaderSize;
4137 static const int kHeaderSize = kFrameSizeOffset + kIntSize;
4139 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4141 // Maximal memory consumption for a single BytecodeArray.
4142 static const int kMaxSize = 512 * MB;
4143 // Maximal length of a single BytecodeArray.
4144 static const int kMaxLength = kMaxSize - kHeaderSize;
4147 DISALLOW_IMPLICIT_CONSTRUCTORS(BytecodeArray);
4151 // FreeSpace are fixed-size free memory blocks used by the heap and GC.
4152 // They look like heap objects (are heap object tagged and have a map) so that
4153 // the heap remains iterable. They have a size and a next pointer.
4154 // The next pointer is the raw address of the next FreeSpace object (or NULL)
4155 // in the free list.
4156 class FreeSpace: public HeapObject {
4158 // [size]: size of the free space including the header.
4159 inline int size() const;
4160 inline void set_size(int value);
4162 inline int nobarrier_size() const;
4163 inline void nobarrier_set_size(int value);
4167 // Accessors for the next field.
4168 inline FreeSpace* next();
4169 inline FreeSpace** next_address();
4170 inline void set_next(FreeSpace* next);
4172 inline static FreeSpace* cast(HeapObject* obj);
4174 // Dispatched behavior.
4175 DECLARE_PRINTER(FreeSpace)
4176 DECLARE_VERIFIER(FreeSpace)
4178 // Layout description.
4179 // Size is smi tagged when it is stored.
4180 static const int kSizeOffset = HeapObject::kHeaderSize;
4181 static const int kNextOffset = POINTER_SIZE_ALIGN(kSizeOffset + kPointerSize);
4184 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
4188 // V has parameters (Type, type, TYPE, C type, element_size)
4189 #define TYPED_ARRAYS(V) \
4190 V(Uint8, uint8, UINT8, uint8_t, 1) \
4191 V(Int8, int8, INT8, int8_t, 1) \
4192 V(Uint16, uint16, UINT16, uint16_t, 2) \
4193 V(Int16, int16, INT16, int16_t, 2) \
4194 V(Uint32, uint32, UINT32, uint32_t, 4) \
4195 V(Int32, int32, INT32, int32_t, 4) \
4196 V(Float32, float32, FLOAT32, float, 4) \
4197 V(Float64, float64, FLOAT64, double, 8) \
4198 V(Uint8Clamped, uint8_clamped, UINT8_CLAMPED, uint8_t, 1)
4201 class FixedTypedArrayBase: public FixedArrayBase {
4203 // [base_pointer]: Either points to the FixedTypedArrayBase itself or nullptr.
4204 DECL_ACCESSORS(base_pointer, Object)
4206 // [external_pointer]: Contains the offset between base_pointer and the start
4207 // of the data. If the base_pointer is a nullptr, the external_pointer
4208 // therefore points to the actual backing store.
4209 DECL_ACCESSORS(external_pointer, void)
4211 // Dispatched behavior.
4212 inline void FixedTypedArrayBaseIterateBody(ObjectVisitor* v);
4214 template <typename StaticVisitor>
4215 inline void FixedTypedArrayBaseIterateBody();
4217 DECLARE_CAST(FixedTypedArrayBase)
4219 static const int kBasePointerOffset = FixedArrayBase::kHeaderSize;
4220 static const int kExternalPointerOffset = kBasePointerOffset + kPointerSize;
4221 static const int kHeaderSize =
4222 DOUBLE_POINTER_ALIGN(kExternalPointerOffset + kPointerSize);
4224 static const int kDataOffset = kHeaderSize;
4228 static inline int TypedArraySize(InstanceType type, int length);
4229 inline int TypedArraySize(InstanceType type);
4231 // Use with care: returns raw pointer into heap.
4232 inline void* DataPtr();
4234 inline int DataSize();
4237 static inline int ElementSize(InstanceType type);
4239 inline int DataSize(InstanceType type);
4241 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
4245 template <class Traits>
4246 class FixedTypedArray: public FixedTypedArrayBase {
4248 typedef typename Traits::ElementType ElementType;
4249 static const InstanceType kInstanceType = Traits::kInstanceType;
4251 DECLARE_CAST(FixedTypedArray<Traits>)
4253 inline ElementType get_scalar(int index);
4254 static inline Handle<Object> get(Handle<FixedTypedArray> array, int index);
4255 inline void set(int index, ElementType value);
4257 static inline ElementType from_int(int value);
4258 static inline ElementType from_double(double value);
4260 // This accessor applies the correct conversion from Smi, HeapNumber
4262 void SetValue(uint32_t index, Object* value);
4264 DECLARE_PRINTER(FixedTypedArray)
4265 DECLARE_VERIFIER(FixedTypedArray)
4268 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
4271 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size) \
4272 class Type##ArrayTraits { \
4273 public: /* NOLINT */ \
4274 typedef elementType ElementType; \
4275 static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE; \
4276 static const char* Designator() { return #type " array"; } \
4277 static inline Handle<Object> ToHandle(Isolate* isolate, \
4278 elementType scalar); \
4279 static inline elementType defaultValue(); \
4282 typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
4284 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
4286 #undef FIXED_TYPED_ARRAY_TRAITS
4289 // DeoptimizationInputData is a fixed array used to hold the deoptimization
4290 // data for code generated by the Hydrogen/Lithium compiler. It also
4291 // contains information about functions that were inlined. If N different
4292 // functions were inlined then first N elements of the literal array will
4293 // contain these functions.
4296 class DeoptimizationInputData: public FixedArray {
4298 // Layout description. Indices in the array.
4299 static const int kTranslationByteArrayIndex = 0;
4300 static const int kInlinedFunctionCountIndex = 1;
4301 static const int kLiteralArrayIndex = 2;
4302 static const int kOsrAstIdIndex = 3;
4303 static const int kOsrPcOffsetIndex = 4;
4304 static const int kOptimizationIdIndex = 5;
4305 static const int kSharedFunctionInfoIndex = 6;
4306 static const int kWeakCellCacheIndex = 7;
4307 static const int kFirstDeoptEntryIndex = 8;
4309 // Offsets of deopt entry elements relative to the start of the entry.
4310 static const int kAstIdRawOffset = 0;
4311 static const int kTranslationIndexOffset = 1;
4312 static const int kArgumentsStackHeightOffset = 2;
4313 static const int kPcOffset = 3;
4314 static const int kDeoptEntrySize = 4;
4316 // Simple element accessors.
4317 #define DECLARE_ELEMENT_ACCESSORS(name, type) \
4318 inline type* name(); \
4319 inline void Set##name(type* value);
4321 DECLARE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
4322 DECLARE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
4323 DECLARE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
4324 DECLARE_ELEMENT_ACCESSORS(OsrAstId, Smi)
4325 DECLARE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
4326 DECLARE_ELEMENT_ACCESSORS(OptimizationId, Smi)
4327 DECLARE_ELEMENT_ACCESSORS(SharedFunctionInfo, Object)
4328 DECLARE_ELEMENT_ACCESSORS(WeakCellCache, Object)
4330 #undef DECLARE_ELEMENT_ACCESSORS
4332 // Accessors for elements of the ith deoptimization entry.
4333 #define DECLARE_ENTRY_ACCESSORS(name, type) \
4334 inline type* name(int i); \
4335 inline void Set##name(int i, type* value);
4337 DECLARE_ENTRY_ACCESSORS(AstIdRaw, Smi)
4338 DECLARE_ENTRY_ACCESSORS(TranslationIndex, Smi)
4339 DECLARE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
4340 DECLARE_ENTRY_ACCESSORS(Pc, Smi)
4342 #undef DECLARE_ENTRY_ACCESSORS
4344 inline BailoutId AstId(int i);
4346 inline void SetAstId(int i, BailoutId value);
4348 inline int DeoptCount();
4350 // Allocates a DeoptimizationInputData.
4351 static Handle<DeoptimizationInputData> New(Isolate* isolate,
4352 int deopt_entry_count,
4353 PretenureFlag pretenure);
4355 DECLARE_CAST(DeoptimizationInputData)
4357 #ifdef ENABLE_DISASSEMBLER
4358 void DeoptimizationInputDataPrint(std::ostream& os); // NOLINT
4362 static int IndexForEntry(int i) {
4363 return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
4367 static int LengthFor(int entry_count) { return IndexForEntry(entry_count); }
4371 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
4372 // data for code generated by the full compiler.
4373 // The format of the these objects is
4374 // [i * 2]: Ast ID for ith deoptimization.
4375 // [i * 2 + 1]: PC and state of ith deoptimization
4376 class DeoptimizationOutputData: public FixedArray {
4378 inline int DeoptPoints();
4380 inline BailoutId AstId(int index);
4382 inline void SetAstId(int index, BailoutId id);
4384 inline Smi* PcAndState(int index);
4385 inline void SetPcAndState(int index, Smi* offset);
4387 static int LengthOfFixedArray(int deopt_points) {
4388 return deopt_points * 2;
4391 // Allocates a DeoptimizationOutputData.
4392 static Handle<DeoptimizationOutputData> New(Isolate* isolate,
4393 int number_of_deopt_points,
4394 PretenureFlag pretenure);
4396 DECLARE_CAST(DeoptimizationOutputData)
4398 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4399 void DeoptimizationOutputDataPrint(std::ostream& os); // NOLINT
4404 // HandlerTable is a fixed array containing entries for exception handlers in
4405 // the code object it is associated with. The tables comes in two flavors:
4406 // 1) Based on ranges: Used for unoptimized code. Contains one entry per
4407 // exception handler and a range representing the try-block covered by that
4408 // handler. Layout looks as follows:
4409 // [ range-start , range-end , handler-offset , stack-depth ]
4410 // 2) Based on return addresses: Used for turbofanned code. Contains one entry
4411 // per call-site that could throw an exception. Layout looks as follows:
4412 // [ return-address-offset , handler-offset ]
4413 class HandlerTable : public FixedArray {
4415 // Conservative prediction whether a given handler will locally catch an
4416 // exception or cause a re-throw to outside the code boundary. Since this is
4417 // undecidable it is merely an approximation (e.g. useful for debugger).
4418 enum CatchPrediction { UNCAUGHT, CAUGHT };
4420 // Accessors for handler table based on ranges.
4421 inline void SetRangeStart(int index, int value);
4422 inline void SetRangeEnd(int index, int value);
4423 inline void SetRangeHandler(int index, int offset, CatchPrediction pred);
4424 inline void SetRangeDepth(int index, int value);
4426 // Accessors for handler table based on return addresses.
4427 inline void SetReturnOffset(int index, int value);
4428 inline void SetReturnHandler(int index, int offset, CatchPrediction pred);
4430 // Lookup handler in a table based on ranges.
4431 int LookupRange(int pc_offset, int* stack_depth, CatchPrediction* prediction);
4433 // Lookup handler in a table based on return addresses.
4434 int LookupReturn(int pc_offset, CatchPrediction* prediction);
4436 // Returns the required length of the underlying fixed array.
4437 static int LengthForRange(int entries) { return entries * kRangeEntrySize; }
4438 static int LengthForReturn(int entries) { return entries * kReturnEntrySize; }
4440 DECLARE_CAST(HandlerTable)
4442 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4443 void HandlerTableRangePrint(std::ostream& os); // NOLINT
4444 void HandlerTableReturnPrint(std::ostream& os); // NOLINT
4448 // Layout description for handler table based on ranges.
4449 static const int kRangeStartIndex = 0;
4450 static const int kRangeEndIndex = 1;
4451 static const int kRangeHandlerIndex = 2;
4452 static const int kRangeDepthIndex = 3;
4453 static const int kRangeEntrySize = 4;
4455 // Layout description for handler table based on return addresses.
4456 static const int kReturnOffsetIndex = 0;
4457 static const int kReturnHandlerIndex = 1;
4458 static const int kReturnEntrySize = 2;
4460 // Encoding of the {handler} field.
4461 class HandlerPredictionField : public BitField<CatchPrediction, 0, 1> {};
4462 class HandlerOffsetField : public BitField<int, 1, 30> {};
4466 // Code describes objects with on-the-fly generated machine code.
4467 class Code: public HeapObject {
4469 // Opaque data type for encapsulating code flags like kind, inline
4470 // cache state, and arguments count.
4471 typedef uint32_t Flags;
4473 #define NON_IC_KIND_LIST(V) \
4475 V(OPTIMIZED_FUNCTION) \
4481 #define IC_KIND_LIST(V) \
4492 #define CODE_KIND_LIST(V) \
4493 NON_IC_KIND_LIST(V) \
4497 #define DEFINE_CODE_KIND_ENUM(name) name,
4498 CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
4499 #undef DEFINE_CODE_KIND_ENUM
4503 // No more than 16 kinds. The value is currently encoded in four bits in
4505 STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
4507 static const char* Kind2String(Kind kind);
4515 static const int kPrologueOffsetNotSet = -1;
4517 #ifdef ENABLE_DISASSEMBLER
4519 static const char* ICState2String(InlineCacheState state);
4520 static const char* StubType2String(StubType type);
4521 static void PrintExtraICState(std::ostream& os, // NOLINT
4522 Kind kind, ExtraICState extra);
4523 void Disassemble(const char* name, std::ostream& os); // NOLINT
4524 #endif // ENABLE_DISASSEMBLER
4526 // [instruction_size]: Size of the native instructions
4527 inline int instruction_size() const;
4528 inline void set_instruction_size(int value);
4530 // [relocation_info]: Code relocation information
4531 DECL_ACCESSORS(relocation_info, ByteArray)
4532 void InvalidateRelocation();
4533 void InvalidateEmbeddedObjects();
4535 // [handler_table]: Fixed array containing offsets of exception handlers.
4536 DECL_ACCESSORS(handler_table, FixedArray)
4538 // [deoptimization_data]: Array containing data for deopt.
4539 DECL_ACCESSORS(deoptimization_data, FixedArray)
4541 // [raw_type_feedback_info]: This field stores various things, depending on
4542 // the kind of the code object.
4543 // FUNCTION => type feedback information.
4544 // STUB and ICs => major/minor key as Smi.
4545 DECL_ACCESSORS(raw_type_feedback_info, Object)
4546 inline Object* type_feedback_info();
4547 inline void set_type_feedback_info(
4548 Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
4549 inline uint32_t stub_key();
4550 inline void set_stub_key(uint32_t key);
4552 // [next_code_link]: Link for lists of optimized or deoptimized code.
4553 // Note that storage for this field is overlapped with typefeedback_info.
4554 DECL_ACCESSORS(next_code_link, Object)
4556 // [gc_metadata]: Field used to hold GC related metadata. The contents of this
4557 // field does not have to be traced during garbage collection since
4558 // it is only used by the garbage collector itself.
4559 DECL_ACCESSORS(gc_metadata, Object)
4561 // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
4562 // at the moment when this object was created.
4563 inline void set_ic_age(int count);
4564 inline int ic_age() const;
4566 // [prologue_offset]: Offset of the function prologue, used for aging
4567 // FUNCTIONs and OPTIMIZED_FUNCTIONs.
4568 inline int prologue_offset() const;
4569 inline void set_prologue_offset(int offset);
4571 // [constant_pool offset]: Offset of the constant pool.
4572 // Valid for FLAG_enable_embedded_constant_pool only
4573 inline int constant_pool_offset() const;
4574 inline void set_constant_pool_offset(int offset);
4576 // Unchecked accessors to be used during GC.
4577 inline ByteArray* unchecked_relocation_info();
4579 inline int relocation_size();
4581 // [flags]: Various code flags.
4582 inline Flags flags();
4583 inline void set_flags(Flags flags);
4585 // [flags]: Access to specific code flags.
4587 inline InlineCacheState ic_state(); // Only valid for IC stubs.
4588 inline ExtraICState extra_ic_state(); // Only valid for IC stubs.
4590 inline StubType type(); // Only valid for monomorphic IC stubs.
4592 // Testers for IC stub kinds.
4593 inline bool is_inline_cache_stub();
4594 inline bool is_debug_stub();
4595 inline bool is_handler();
4596 inline bool is_load_stub();
4597 inline bool is_keyed_load_stub();
4598 inline bool is_store_stub();
4599 inline bool is_keyed_store_stub();
4600 inline bool is_call_stub();
4601 inline bool is_binary_op_stub();
4602 inline bool is_compare_ic_stub();
4603 inline bool is_compare_nil_ic_stub();
4604 inline bool is_to_boolean_ic_stub();
4605 inline bool is_keyed_stub();
4606 inline bool is_optimized_code();
4607 inline bool embeds_maps_weakly();
4609 inline bool IsCodeStubOrIC();
4611 inline void set_raw_kind_specific_flags1(int value);
4612 inline void set_raw_kind_specific_flags2(int value);
4614 // [is_crankshafted]: For kind STUB or ICs, tells whether or not a code
4615 // object was generated by either the hydrogen or the TurboFan optimizing
4616 // compiler (but it may not be an optimized function).
4617 inline bool is_crankshafted();
4618 inline bool is_hydrogen_stub(); // Crankshafted, but not a function.
4619 inline void set_is_crankshafted(bool value);
4621 // [is_turbofanned]: For kind STUB or OPTIMIZED_FUNCTION, tells whether the
4622 // code object was generated by the TurboFan optimizing compiler.
4623 inline bool is_turbofanned();
4624 inline void set_is_turbofanned(bool value);
4626 // [can_have_weak_objects]: For kind OPTIMIZED_FUNCTION, tells whether the
4627 // embedded objects in code should be treated weakly.
4628 inline bool can_have_weak_objects();
4629 inline void set_can_have_weak_objects(bool value);
4631 // [has_deoptimization_support]: For FUNCTION kind, tells if it has
4632 // deoptimization support.
4633 inline bool has_deoptimization_support();
4634 inline void set_has_deoptimization_support(bool value);
4636 // [has_debug_break_slots]: For FUNCTION kind, tells if it has
4637 // been compiled with debug break slots.
4638 inline bool has_debug_break_slots();
4639 inline void set_has_debug_break_slots(bool value);
4641 // [has_reloc_info_for_serialization]: For FUNCTION kind, tells if its
4642 // reloc info includes runtime and external references to support
4643 // serialization/deserialization.
4644 inline bool has_reloc_info_for_serialization();
4645 inline void set_has_reloc_info_for_serialization(bool value);
4647 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
4648 // how long the function has been marked for OSR and therefore which
4649 // level of loop nesting we are willing to do on-stack replacement
4651 inline void set_allow_osr_at_loop_nesting_level(int level);
4652 inline int allow_osr_at_loop_nesting_level();
4654 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
4655 // the code object was seen on the stack with no IC patching going on.
4656 inline int profiler_ticks();
4657 inline void set_profiler_ticks(int ticks);
4659 // [builtin_index]: For BUILTIN kind, tells which builtin index it has.
4660 // For builtins, tells which builtin index it has.
4661 // Note that builtins can have a code kind other than BUILTIN, which means
4662 // that for arbitrary code objects, this index value may be random garbage.
4663 // To verify in that case, compare the code object to the indexed builtin.
4664 inline int builtin_index();
4665 inline void set_builtin_index(int id);
4667 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
4668 // reserved in the code prologue.
4669 inline unsigned stack_slots();
4670 inline void set_stack_slots(unsigned slots);
4672 // [safepoint_table_start]: For kind OPTIMIZED_FUNCTION, the offset in
4673 // the instruction stream where the safepoint table starts.
4674 inline unsigned safepoint_table_offset();
4675 inline void set_safepoint_table_offset(unsigned offset);
4677 // [back_edge_table_start]: For kind FUNCTION, the offset in the
4678 // instruction stream where the back edge table starts.
4679 inline unsigned back_edge_table_offset();
4680 inline void set_back_edge_table_offset(unsigned offset);
4682 inline bool back_edges_patched_for_osr();
4684 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
4685 inline uint16_t to_boolean_state();
4687 // [has_function_cache]: For kind STUB tells whether there is a function
4688 // cache is passed to the stub.
4689 inline bool has_function_cache();
4690 inline void set_has_function_cache(bool flag);
4693 // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
4694 // the code is going to be deoptimized because of dead embedded maps.
4695 inline bool marked_for_deoptimization();
4696 inline void set_marked_for_deoptimization(bool flag);
4698 // [constant_pool]: The constant pool for this function.
4699 inline Address constant_pool();
4701 // Get the safepoint entry for the given pc.
4702 SafepointEntry GetSafepointEntry(Address pc);
4704 // Find an object in a stub with a specified map
4705 Object* FindNthObject(int n, Map* match_map);
4707 // Find the first allocation site in an IC stub.
4708 AllocationSite* FindFirstAllocationSite();
4710 // Find the first map in an IC stub.
4711 Map* FindFirstMap();
4712 void FindAllMaps(MapHandleList* maps);
4714 // Find the first handler in an IC stub.
4715 Code* FindFirstHandler();
4717 // Find |length| handlers and put them into |code_list|. Returns false if not
4718 // enough handlers can be found.
4719 bool FindHandlers(CodeHandleList* code_list, int length = -1);
4721 // Find the handler for |map|.
4722 MaybeHandle<Code> FindHandlerForMap(Map* map);
4724 // Find the first name in an IC stub.
4725 Name* FindFirstName();
4727 class FindAndReplacePattern;
4728 // For each (map-to-find, object-to-replace) pair in the pattern, this
4729 // function replaces the corresponding placeholder in the code with the
4730 // object-to-replace. The function assumes that pairs in the pattern come in
4731 // the same order as the placeholders in the code.
4732 // If the placeholder is a weak cell, then the value of weak cell is matched
4733 // against the map-to-find.
4734 void FindAndReplace(const FindAndReplacePattern& pattern);
4736 // The entire code object including its header is copied verbatim to the
4737 // snapshot so that it can be written in one, fast, memcpy during
4738 // deserialization. The deserializer will overwrite some pointers, rather
4739 // like a runtime linker, but the random allocation addresses used in the
4740 // mksnapshot process would still be present in the unlinked snapshot data,
4741 // which would make snapshot production non-reproducible. This method wipes
4742 // out the to-be-overwritten header data for reproducible snapshots.
4743 inline void WipeOutHeader();
4745 // Flags operations.
4746 static inline Flags ComputeFlags(
4747 Kind kind, InlineCacheState ic_state = UNINITIALIZED,
4748 ExtraICState extra_ic_state = kNoExtraICState, StubType type = NORMAL,
4749 CacheHolderFlag holder = kCacheOnReceiver);
4751 static inline Flags ComputeMonomorphicFlags(
4752 Kind kind, ExtraICState extra_ic_state = kNoExtraICState,
4753 CacheHolderFlag holder = kCacheOnReceiver, StubType type = NORMAL);
4755 static inline Flags ComputeHandlerFlags(
4756 Kind handler_kind, StubType type = NORMAL,
4757 CacheHolderFlag holder = kCacheOnReceiver);
4759 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
4760 static inline StubType ExtractTypeFromFlags(Flags flags);
4761 static inline CacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
4762 static inline Kind ExtractKindFromFlags(Flags flags);
4763 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
4765 static inline Flags RemoveTypeFromFlags(Flags flags);
4766 static inline Flags RemoveTypeAndHolderFromFlags(Flags flags);
4768 // Convert a target address into a code object.
4769 static inline Code* GetCodeFromTargetAddress(Address address);
4771 // Convert an entry address into an object.
4772 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
4774 // Returns the address of the first instruction.
4775 inline byte* instruction_start();
4777 // Returns the address right after the last instruction.
4778 inline byte* instruction_end();
4780 // Returns the size of the instructions, padding, and relocation information.
4781 inline int body_size();
4783 // Returns the address of the first relocation info (read backwards!).
4784 inline byte* relocation_start();
4786 // Code entry point.
4787 inline byte* entry();
4789 // Returns true if pc is inside this object's instructions.
4790 inline bool contains(byte* pc);
4792 // Relocate the code by delta bytes. Called to signal that this code
4793 // object has been moved by delta bytes.
4794 void Relocate(intptr_t delta);
4796 // Migrate code described by desc.
4797 void CopyFrom(const CodeDesc& desc);
4799 // Returns the object size for a given body (used for allocation).
4800 static int SizeFor(int body_size) {
4801 DCHECK_SIZE_TAG_ALIGNED(body_size);
4802 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
4805 // Calculate the size of the code object to report for log events. This takes
4806 // the layout of the code object into account.
4807 inline int ExecutableSize();
4809 // Locating source position.
4810 int SourcePosition(Address pc);
4811 int SourceStatementPosition(Address pc);
4815 // Dispatched behavior.
4816 inline int CodeSize();
4817 inline void CodeIterateBody(ObjectVisitor* v);
4819 template<typename StaticVisitor>
4820 inline void CodeIterateBody(Heap* heap);
4822 DECLARE_PRINTER(Code)
4823 DECLARE_VERIFIER(Code)
4825 void ClearInlineCaches();
4826 void ClearInlineCaches(Kind kind);
4828 BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
4829 uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
4831 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
4833 kToBeExecutedOnceCodeAge = -3,
4834 kNotExecutedCodeAge = -2,
4835 kExecutedOnceCodeAge = -1,
4837 CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
4839 kFirstCodeAge = kToBeExecutedOnceCodeAge,
4840 kLastCodeAge = kAfterLastCodeAge - 1,
4841 kCodeAgeCount = kAfterLastCodeAge - kFirstCodeAge - 1,
4842 kIsOldCodeAge = kSexagenarianCodeAge,
4843 kPreAgedCodeAge = kIsOldCodeAge - 1
4845 #undef DECLARE_CODE_AGE_ENUM
4847 // Code aging. Indicates how many full GCs this code has survived without
4848 // being entered through the prologue. Used to determine when it is
4849 // relatively safe to flush this code object and replace it with the lazy
4850 // compilation stub.
4851 static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
4852 static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
4853 void MakeYoung(Isolate* isolate);
4854 void MarkToBeExecutedOnce(Isolate* isolate);
4855 void MakeOlder(MarkingParity);
4856 static bool IsYoungSequence(Isolate* isolate, byte* sequence);
4859 static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
4860 return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
4863 void PrintDeoptLocation(FILE* out, Address pc);
4864 bool CanDeoptAt(Address pc);
4867 void VerifyEmbeddedObjectsDependency();
4871 enum VerifyMode { kNoContextSpecificPointers, kNoContextRetainingPointers };
4872 void VerifyEmbeddedObjects(VerifyMode mode = kNoContextRetainingPointers);
4873 static void VerifyRecompiledCode(Code* old_code, Code* new_code);
4876 inline bool CanContainWeakObjects();
4878 inline bool IsWeakObject(Object* object);
4880 static inline bool IsWeakObjectInOptimizedCode(Object* object);
4882 static Handle<WeakCell> WeakCellFor(Handle<Code> code);
4883 WeakCell* CachedWeakCell();
4885 // Max loop nesting marker used to postpose OSR. We don't take loop
4886 // nesting that is deeper than 5 levels into account.
4887 static const int kMaxLoopNestingMarker = 6;
4889 static const int kConstantPoolSize =
4890 FLAG_enable_embedded_constant_pool ? kIntSize : 0;
4892 // Layout description.
4893 static const int kRelocationInfoOffset = HeapObject::kHeaderSize;
4894 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
4895 static const int kDeoptimizationDataOffset =
4896 kHandlerTableOffset + kPointerSize;
4897 // For FUNCTION kind, we store the type feedback info here.
4898 static const int kTypeFeedbackInfoOffset =
4899 kDeoptimizationDataOffset + kPointerSize;
4900 static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
4901 static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
4902 static const int kInstructionSizeOffset = kGCMetadataOffset + kPointerSize;
4903 static const int kICAgeOffset = kInstructionSizeOffset + kIntSize;
4904 static const int kFlagsOffset = kICAgeOffset + kIntSize;
4905 static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
4906 static const int kKindSpecificFlags2Offset =
4907 kKindSpecificFlags1Offset + kIntSize;
4908 // Note: We might be able to squeeze this into the flags above.
4909 static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
4910 static const int kConstantPoolOffset = kPrologueOffset + kIntSize;
4911 static const int kHeaderPaddingStart =
4912 kConstantPoolOffset + kConstantPoolSize;
4914 // Add padding to align the instruction start following right after
4915 // the Code object header.
4916 static const int kHeaderSize =
4917 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
4919 // Byte offsets within kKindSpecificFlags1Offset.
4920 static const int kFullCodeFlags = kKindSpecificFlags1Offset;
4921 class FullCodeFlagsHasDeoptimizationSupportField:
4922 public BitField<bool, 0, 1> {}; // NOLINT
4923 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
4924 class FullCodeFlagsHasRelocInfoForSerialization
4925 : public BitField<bool, 2, 1> {};
4926 // Bit 3 in this bitfield is unused.
4927 class ProfilerTicksField : public BitField<int, 4, 28> {};
4929 // Flags layout. BitField<type, shift, size>.
4930 class ICStateField : public BitField<InlineCacheState, 0, 4> {};
4931 class TypeField : public BitField<StubType, 4, 1> {};
4932 class CacheHolderField : public BitField<CacheHolderFlag, 5, 2> {};
4933 class KindField : public BitField<Kind, 7, 4> {};
4934 class ExtraICStateField: public BitField<ExtraICState, 11,
4935 PlatformSmiTagging::kSmiValueSize - 11 + 1> {}; // NOLINT
4937 // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
4938 static const int kStackSlotsFirstBit = 0;
4939 static const int kStackSlotsBitCount = 24;
4940 static const int kHasFunctionCacheBit =
4941 kStackSlotsFirstBit + kStackSlotsBitCount;
4942 static const int kMarkedForDeoptimizationBit = kHasFunctionCacheBit + 1;
4943 static const int kIsTurbofannedBit = kMarkedForDeoptimizationBit + 1;
4944 static const int kCanHaveWeakObjects = kIsTurbofannedBit + 1;
4946 STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
4947 STATIC_ASSERT(kCanHaveWeakObjects + 1 <= 32);
4949 class StackSlotsField: public BitField<int,
4950 kStackSlotsFirstBit, kStackSlotsBitCount> {}; // NOLINT
4951 class HasFunctionCacheField : public BitField<bool, kHasFunctionCacheBit, 1> {
4953 class MarkedForDeoptimizationField
4954 : public BitField<bool, kMarkedForDeoptimizationBit, 1> {}; // NOLINT
4955 class IsTurbofannedField : public BitField<bool, kIsTurbofannedBit, 1> {
4957 class CanHaveWeakObjectsField
4958 : public BitField<bool, kCanHaveWeakObjects, 1> {}; // NOLINT
4960 // KindSpecificFlags2 layout (ALL)
4961 static const int kIsCrankshaftedBit = 0;
4962 class IsCrankshaftedField: public BitField<bool,
4963 kIsCrankshaftedBit, 1> {}; // NOLINT
4965 // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
4966 static const int kSafepointTableOffsetFirstBit = kIsCrankshaftedBit + 1;
4967 static const int kSafepointTableOffsetBitCount = 30;
4969 STATIC_ASSERT(kSafepointTableOffsetFirstBit +
4970 kSafepointTableOffsetBitCount <= 32);
4971 STATIC_ASSERT(1 + kSafepointTableOffsetBitCount <= 32);
4973 class SafepointTableOffsetField: public BitField<int,
4974 kSafepointTableOffsetFirstBit,
4975 kSafepointTableOffsetBitCount> {}; // NOLINT
4977 // KindSpecificFlags2 layout (FUNCTION)
4978 class BackEdgeTableOffsetField: public BitField<int,
4979 kIsCrankshaftedBit + 1, 27> {}; // NOLINT
4980 class AllowOSRAtLoopNestingLevelField: public BitField<int,
4981 kIsCrankshaftedBit + 1 + 27, 4> {}; // NOLINT
4982 STATIC_ASSERT(AllowOSRAtLoopNestingLevelField::kMax >= kMaxLoopNestingMarker);
4984 static const int kArgumentsBits = 16;
4985 static const int kMaxArguments = (1 << kArgumentsBits) - 1;
4987 // This constant should be encodable in an ARM instruction.
4988 static const int kFlagsNotUsedInLookup =
4989 TypeField::kMask | CacheHolderField::kMask;
4992 friend class RelocIterator;
4993 friend class Deoptimizer; // For FindCodeAgeSequence.
4995 void ClearInlineCaches(Kind* kind);
4998 byte* FindCodeAgeSequence();
4999 static void GetCodeAgeAndParity(Code* code, Age* age,
5000 MarkingParity* parity);
5001 static void GetCodeAgeAndParity(Isolate* isolate, byte* sequence, Age* age,
5002 MarkingParity* parity);
5003 static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
5005 // Code aging -- platform-specific
5006 static void PatchPlatformCodeAge(Isolate* isolate,
5007 byte* sequence, Age age,
5008 MarkingParity parity);
5010 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5014 // This class describes the layout of dependent codes array of a map. The
5015 // array is partitioned into several groups of dependent codes. Each group
5016 // contains codes with the same dependency on the map. The array has the
5017 // following layout for n dependency groups:
5019 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5020 // | C1 | C2 | ... | Cn | group 1 | group 2 | ... | group n | undefined |
5021 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5023 // The first n elements are Smis, each of them specifies the number of codes
5024 // in the corresponding group. The subsequent elements contain grouped code
5025 // objects in weak cells. The suffix of the array can be filled with the
5026 // undefined value if the number of codes is less than the length of the
5027 // array. The order of the code objects within a group is not preserved.
5029 // All code indexes used in the class are counted starting from the first
5030 // code object of the first group. In other words, code index 0 corresponds
5031 // to array index n = kCodesStartIndex.
5033 class DependentCode: public FixedArray {
5035 enum DependencyGroup {
5036 // Group of code that weakly embed this map and depend on being
5037 // deoptimized when the map is garbage collected.
5039 // Group of code that embed a transition to this map, and depend on being
5040 // deoptimized when the transition is replaced by a new version.
5042 // Group of code that omit run-time prototype checks for prototypes
5043 // described by this map. The group is deoptimized whenever an object
5044 // described by this map changes shape (and transitions to a new map),
5045 // possibly invalidating the assumptions embedded in the code.
5046 kPrototypeCheckGroup,
5047 // Group of code that depends on global property values in property cells
5048 // not being changed.
5049 kPropertyCellChangedGroup,
5050 // Group of code that omit run-time type checks for the field(s) introduced
5053 // Group of code that omit run-time type checks for initial maps of
5055 kInitialMapChangedGroup,
5056 // Group of code that depends on tenuring information in AllocationSites
5057 // not being changed.
5058 kAllocationSiteTenuringChangedGroup,
5059 // Group of code that depends on element transition information in
5060 // AllocationSites not being changed.
5061 kAllocationSiteTransitionChangedGroup
5064 static const int kGroupCount = kAllocationSiteTransitionChangedGroup + 1;
5066 // Array for holding the index of the first code object of each group.
5067 // The last element stores the total number of code objects.
5068 class GroupStartIndexes {
5070 explicit GroupStartIndexes(DependentCode* entries);
5071 void Recompute(DependentCode* entries);
5072 int at(int i) { return start_indexes_[i]; }
5073 int number_of_entries() { return start_indexes_[kGroupCount]; }
5075 int start_indexes_[kGroupCount + 1];
5078 bool Contains(DependencyGroup group, WeakCell* code_cell);
5080 static Handle<DependentCode> InsertCompilationDependencies(
5081 Handle<DependentCode> entries, DependencyGroup group,
5082 Handle<Foreign> info);
5084 static Handle<DependentCode> InsertWeakCode(Handle<DependentCode> entries,
5085 DependencyGroup group,
5086 Handle<WeakCell> code_cell);
5088 void UpdateToFinishedCode(DependencyGroup group, Foreign* info,
5089 WeakCell* code_cell);
5091 void RemoveCompilationDependencies(DependentCode::DependencyGroup group,
5094 void DeoptimizeDependentCodeGroup(Isolate* isolate,
5095 DependentCode::DependencyGroup group);
5097 bool MarkCodeForDeoptimization(Isolate* isolate,
5098 DependentCode::DependencyGroup group);
5100 // The following low-level accessors should only be used by this class
5101 // and the mark compact collector.
5102 inline int number_of_entries(DependencyGroup group);
5103 inline void set_number_of_entries(DependencyGroup group, int value);
5104 inline Object* object_at(int i);
5105 inline void set_object_at(int i, Object* object);
5106 inline void clear_at(int i);
5107 inline void copy(int from, int to);
5108 DECLARE_CAST(DependentCode)
5110 static const char* DependencyGroupName(DependencyGroup group);
5111 static void SetMarkedForDeoptimization(Code* code, DependencyGroup group);
5114 static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5115 DependencyGroup group,
5116 Handle<Object> object);
5117 static Handle<DependentCode> EnsureSpace(Handle<DependentCode> entries);
5118 // Make a room at the end of the given group by moving out the first
5119 // code objects of the subsequent groups.
5120 inline void ExtendGroup(DependencyGroup group);
5121 // Compact by removing cleared weak cells and return true if there was
5122 // any cleared weak cell.
5124 static int Grow(int number_of_entries) {
5125 if (number_of_entries < 5) return number_of_entries + 1;
5126 return number_of_entries * 5 / 4;
5128 static const int kCodesStartIndex = kGroupCount;
5132 class PrototypeInfo;
5135 // All heap objects have a Map that describes their structure.
5136 // A Map contains information about:
5137 // - Size information about the object
5138 // - How to iterate over an object (for garbage collection)
5139 class Map: public HeapObject {
5142 // Size in bytes or kVariableSizeSentinel if instances do not have
5144 inline int instance_size();
5145 inline void set_instance_size(int value);
5147 // Only to clear an unused byte, remove once byte is used.
5148 inline void clear_unused();
5150 // [inobject_properties_or_constructor_function_index]: Provides access
5151 // to the inobject properties in case of JSObject maps, or the constructor
5152 // function index in case of primitive maps.
5153 inline int inobject_properties_or_constructor_function_index();
5154 inline void set_inobject_properties_or_constructor_function_index(int value);
5155 // Count of properties allocated in the object (JSObject only).
5156 inline int GetInObjectProperties();
5157 inline void SetInObjectProperties(int value);
5158 // Index of the constructor function in the native context (primitives only),
5159 // or the special sentinel value to indicate that there is no object wrapper
5160 // for the primitive (i.e. in case of null or undefined).
5161 static const int kNoConstructorFunctionIndex = 0;
5162 inline int GetConstructorFunctionIndex();
5163 inline void SetConstructorFunctionIndex(int value);
5166 inline InstanceType instance_type();
5167 inline void set_instance_type(InstanceType value);
5169 // Tells how many unused property fields are available in the
5170 // instance (only used for JSObject in fast mode).
5171 inline int unused_property_fields();
5172 inline void set_unused_property_fields(int value);
5175 inline byte bit_field() const;
5176 inline void set_bit_field(byte value);
5179 inline byte bit_field2() const;
5180 inline void set_bit_field2(byte value);
5183 inline uint32_t bit_field3() const;
5184 inline void set_bit_field3(uint32_t bits);
5186 class EnumLengthBits: public BitField<int,
5187 0, kDescriptorIndexBitCount> {}; // NOLINT
5188 class NumberOfOwnDescriptorsBits: public BitField<int,
5189 kDescriptorIndexBitCount, kDescriptorIndexBitCount> {}; // NOLINT
5190 STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
5191 class DictionaryMap : public BitField<bool, 20, 1> {};
5192 class OwnsDescriptors : public BitField<bool, 21, 1> {};
5193 class HasInstanceCallHandler : public BitField<bool, 22, 1> {};
5194 class Deprecated : public BitField<bool, 23, 1> {};
5195 class IsUnstable : public BitField<bool, 24, 1> {};
5196 class IsMigrationTarget : public BitField<bool, 25, 1> {};
5197 class IsStrong : public BitField<bool, 26, 1> {};
5200 // Keep this bit field at the very end for better code in
5201 // Builtins::kJSConstructStubGeneric stub.
5202 // This counter is used for in-object slack tracking and for map aging.
5203 // The in-object slack tracking is considered enabled when the counter is
5204 // in the range [kSlackTrackingCounterStart, kSlackTrackingCounterEnd].
5205 class Counter : public BitField<int, 28, 4> {};
5206 static const int kSlackTrackingCounterStart = 14;
5207 static const int kSlackTrackingCounterEnd = 8;
5208 static const int kRetainingCounterStart = kSlackTrackingCounterEnd - 1;
5209 static const int kRetainingCounterEnd = 0;
5211 // Tells whether the object in the prototype property will be used
5212 // for instances created from this function. If the prototype
5213 // property is set to a value that is not a JSObject, the prototype
5214 // property will not be used to create instances of the function.
5215 // See ECMA-262, 13.2.2.
5216 inline void set_non_instance_prototype(bool value);
5217 inline bool has_non_instance_prototype();
5219 // Tells whether function has special prototype property. If not, prototype
5220 // property will not be created when accessed (will return undefined),
5221 // and construction from this function will not be allowed.
5222 inline void set_function_with_prototype(bool value);
5223 inline bool function_with_prototype();
5225 // Tells whether the instance with this map should be ignored by the
5226 // Object.getPrototypeOf() function and the __proto__ accessor.
5227 inline void set_is_hidden_prototype();
5228 inline bool is_hidden_prototype();
5230 // Records and queries whether the instance has a named interceptor.
5231 inline void set_has_named_interceptor();
5232 inline bool has_named_interceptor();
5234 // Records and queries whether the instance has an indexed interceptor.
5235 inline void set_has_indexed_interceptor();
5236 inline bool has_indexed_interceptor();
5238 // Tells whether the instance is undetectable.
5239 // An undetectable object is a special class of JSObject: 'typeof' operator
5240 // returns undefined, ToBoolean returns false. Otherwise it behaves like
5241 // a normal JS object. It is useful for implementing undetectable
5242 // document.all in Firefox & Safari.
5243 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
5244 inline void set_is_undetectable();
5245 inline bool is_undetectable();
5247 // Tells whether the instance has a call-as-function handler.
5248 inline void set_is_observed();
5249 inline bool is_observed();
5251 inline void set_is_strong();
5252 inline bool is_strong();
5253 inline void set_is_extensible(bool value);
5254 inline bool is_extensible();
5255 inline void set_is_prototype_map(bool value);
5256 inline bool is_prototype_map() const;
5258 inline void set_elements_kind(ElementsKind elements_kind);
5259 inline ElementsKind elements_kind();
5261 // Tells whether the instance has fast elements that are only Smis.
5262 inline bool has_fast_smi_elements();
5264 // Tells whether the instance has fast elements.
5265 inline bool has_fast_object_elements();
5266 inline bool has_fast_smi_or_object_elements();
5267 inline bool has_fast_double_elements();
5268 inline bool has_fast_elements();
5269 inline bool has_sloppy_arguments_elements();
5270 inline bool has_fixed_typed_array_elements();
5271 inline bool has_dictionary_elements();
5273 static bool IsValidElementsTransition(ElementsKind from_kind,
5274 ElementsKind to_kind);
5276 // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
5277 // map with DICTIONARY_ELEMENTS was found in the prototype chain.
5278 bool DictionaryElementsInPrototypeChainOnly();
5280 inline Map* ElementsTransitionMap();
5282 inline FixedArrayBase* GetInitialElements();
5284 // [raw_transitions]: Provides access to the transitions storage field.
5285 // Don't call set_raw_transitions() directly to overwrite transitions, use
5286 // the TransitionArray::ReplaceTransitions() wrapper instead!
5287 DECL_ACCESSORS(raw_transitions, Object)
5288 // [prototype_info]: Per-prototype metadata. Aliased with transitions
5289 // (which prototype maps don't have).
5290 DECL_ACCESSORS(prototype_info, Object)
5291 // PrototypeInfo is created lazily using this helper (which installs it on
5292 // the given prototype's map).
5293 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5294 Handle<JSObject> prototype, Isolate* isolate);
5295 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5296 Handle<Map> prototype_map, Isolate* isolate);
5298 // [prototype chain validity cell]: Associated with a prototype object,
5299 // stored in that object's map's PrototypeInfo, indicates that prototype
5300 // chains through this object are currently valid. The cell will be
5301 // invalidated and replaced when the prototype chain changes.
5302 static Handle<Cell> GetOrCreatePrototypeChainValidityCell(Handle<Map> map,
5304 static const int kPrototypeChainValid = 0;
5305 static const int kPrototypeChainInvalid = 1;
5308 Map* FindFieldOwner(int descriptor);
5310 inline int GetInObjectPropertyOffset(int index);
5312 int NumberOfFields();
5314 // TODO(ishell): candidate with JSObject::MigrateToMap().
5315 bool InstancesNeedRewriting(Map* target, int target_number_of_fields,
5316 int target_inobject, int target_unused,
5317 int* old_number_of_fields);
5318 // TODO(ishell): moveit!
5319 static Handle<Map> GeneralizeAllFieldRepresentations(Handle<Map> map);
5320 MUST_USE_RESULT static Handle<HeapType> GeneralizeFieldType(
5321 Handle<HeapType> type1,
5322 Handle<HeapType> type2,
5324 static void GeneralizeFieldType(Handle<Map> map, int modify_index,
5325 Representation new_representation,
5326 Handle<HeapType> new_field_type);
5327 static Handle<Map> ReconfigureProperty(Handle<Map> map, int modify_index,
5328 PropertyKind new_kind,
5329 PropertyAttributes new_attributes,
5330 Representation new_representation,
5331 Handle<HeapType> new_field_type,
5332 StoreMode store_mode);
5333 static Handle<Map> CopyGeneralizeAllRepresentations(
5334 Handle<Map> map, int modify_index, StoreMode store_mode,
5335 PropertyKind kind, PropertyAttributes attributes, const char* reason);
5337 static Handle<Map> PrepareForDataProperty(Handle<Map> old_map,
5338 int descriptor_number,
5339 Handle<Object> value);
5341 static Handle<Map> Normalize(Handle<Map> map, PropertyNormalizationMode mode,
5342 const char* reason);
5344 // Returns the constructor name (the name (possibly, inferred name) of the
5345 // function that was used to instantiate the object).
5346 String* constructor_name();
5348 // Tells whether the map is used for JSObjects in dictionary mode (ie
5349 // normalized objects, ie objects for which HasFastProperties returns false).
5350 // A map can never be used for both dictionary mode and fast mode JSObjects.
5351 // False by default and for HeapObjects that are not JSObjects.
5352 inline void set_dictionary_map(bool value);
5353 inline bool is_dictionary_map();
5355 // Tells whether the instance needs security checks when accessing its
5357 inline void set_is_access_check_needed(bool access_check_needed);
5358 inline bool is_access_check_needed();
5360 // Returns true if map has a non-empty stub code cache.
5361 inline bool has_code_cache();
5363 // [prototype]: implicit prototype object.
5364 DECL_ACCESSORS(prototype, Object)
5365 // TODO(jkummerow): make set_prototype private.
5366 static void SetPrototype(
5367 Handle<Map> map, Handle<Object> prototype,
5368 PrototypeOptimizationMode proto_mode = FAST_PROTOTYPE);
5370 // [constructor]: points back to the function responsible for this map.
5371 // The field overlaps with the back pointer. All maps in a transition tree
5372 // have the same constructor, so maps with back pointers can walk the
5373 // back pointer chain until they find the map holding their constructor.
5374 DECL_ACCESSORS(constructor_or_backpointer, Object)
5375 inline Object* GetConstructor() const;
5376 inline void SetConstructor(Object* constructor,
5377 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5378 // [back pointer]: points back to the parent map from which a transition
5379 // leads to this map. The field overlaps with the constructor (see above).
5380 inline Object* GetBackPointer();
5381 inline void SetBackPointer(Object* value,
5382 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5384 // [instance descriptors]: describes the object.
5385 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
5387 // [layout descriptor]: describes the object layout.
5388 DECL_ACCESSORS(layout_descriptor, LayoutDescriptor)
5389 // |layout descriptor| accessor which can be used from GC.
5390 inline LayoutDescriptor* layout_descriptor_gc_safe();
5391 inline bool HasFastPointerLayout() const;
5393 // |layout descriptor| accessor that is safe to call even when
5394 // FLAG_unbox_double_fields is disabled (in this case Map does not contain
5395 // |layout_descriptor| field at all).
5396 inline LayoutDescriptor* GetLayoutDescriptor();
5398 inline void UpdateDescriptors(DescriptorArray* descriptors,
5399 LayoutDescriptor* layout_descriptor);
5400 inline void InitializeDescriptors(DescriptorArray* descriptors,
5401 LayoutDescriptor* layout_descriptor);
5403 // [stub cache]: contains stubs compiled for this map.
5404 DECL_ACCESSORS(code_cache, Object)
5406 // [dependent code]: list of optimized codes that weakly embed this map.
5407 DECL_ACCESSORS(dependent_code, DependentCode)
5409 // [weak cell cache]: cache that stores a weak cell pointing to this map.
5410 DECL_ACCESSORS(weak_cell_cache, Object)
5412 inline PropertyDetails GetLastDescriptorDetails();
5414 inline int LastAdded();
5416 inline int NumberOfOwnDescriptors();
5417 inline void SetNumberOfOwnDescriptors(int number);
5419 inline Cell* RetrieveDescriptorsPointer();
5421 inline int EnumLength();
5422 inline void SetEnumLength(int length);
5424 inline bool owns_descriptors();
5425 inline void set_owns_descriptors(bool owns_descriptors);
5426 inline bool has_instance_call_handler();
5427 inline void set_has_instance_call_handler();
5428 inline void mark_unstable();
5429 inline bool is_stable();
5430 inline void set_migration_target(bool value);
5431 inline bool is_migration_target();
5432 inline void set_counter(int value);
5433 inline int counter();
5434 inline void deprecate();
5435 inline bool is_deprecated();
5436 inline bool CanBeDeprecated();
5437 // Returns a non-deprecated version of the input. If the input was not
5438 // deprecated, it is directly returned. Otherwise, the non-deprecated version
5439 // is found by re-transitioning from the root of the transition tree using the
5440 // descriptor array of the map. Returns MaybeHandle<Map>() if no updated map
5442 static MaybeHandle<Map> TryUpdate(Handle<Map> map) WARN_UNUSED_RESULT;
5444 // Returns a non-deprecated version of the input. This method may deprecate
5445 // existing maps along the way if encodings conflict. Not for use while
5446 // gathering type feedback. Use TryUpdate in those cases instead.
5447 static Handle<Map> Update(Handle<Map> map);
5449 static Handle<Map> CopyDropDescriptors(Handle<Map> map);
5450 static Handle<Map> CopyInsertDescriptor(Handle<Map> map,
5451 Descriptor* descriptor,
5452 TransitionFlag flag);
5454 MUST_USE_RESULT static MaybeHandle<Map> CopyWithField(
5457 Handle<HeapType> type,
5458 PropertyAttributes attributes,
5459 Representation representation,
5460 TransitionFlag flag);
5462 MUST_USE_RESULT static MaybeHandle<Map> CopyWithConstant(
5465 Handle<Object> constant,
5466 PropertyAttributes attributes,
5467 TransitionFlag flag);
5469 // Returns a new map with all transitions dropped from the given map and
5470 // the ElementsKind set.
5471 static Handle<Map> TransitionElementsTo(Handle<Map> map,
5472 ElementsKind to_kind);
5474 static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
5476 static Handle<Map> CopyAsElementsKind(Handle<Map> map,
5478 TransitionFlag flag);
5480 static Handle<Map> CopyForObserved(Handle<Map> map);
5482 static Handle<Map> CopyForPreventExtensions(Handle<Map> map,
5483 PropertyAttributes attrs_to_add,
5484 Handle<Symbol> transition_marker,
5485 const char* reason);
5487 static Handle<Map> FixProxy(Handle<Map> map, InstanceType type, int size);
5490 // Maximal number of fast properties. Used to restrict the number of map
5491 // transitions to avoid an explosion in the number of maps for objects used as
5493 inline bool TooManyFastProperties(StoreFromKeyed store_mode);
5494 static Handle<Map> TransitionToDataProperty(Handle<Map> map,
5496 Handle<Object> value,
5497 PropertyAttributes attributes,
5498 StoreFromKeyed store_mode);
5499 static Handle<Map> TransitionToAccessorProperty(
5500 Handle<Map> map, Handle<Name> name, AccessorComponent component,
5501 Handle<Object> accessor, PropertyAttributes attributes);
5502 static Handle<Map> ReconfigureExistingProperty(Handle<Map> map,
5505 PropertyAttributes attributes);
5507 inline void AppendDescriptor(Descriptor* desc);
5509 // Returns a copy of the map, prepared for inserting into the transition
5510 // tree (if the |map| owns descriptors then the new one will share
5511 // descriptors with |map|).
5512 static Handle<Map> CopyForTransition(Handle<Map> map, const char* reason);
5514 // Returns a copy of the map, with all transitions dropped from the
5515 // instance descriptors.
5516 static Handle<Map> Copy(Handle<Map> map, const char* reason);
5517 static Handle<Map> Create(Isolate* isolate, int inobject_properties);
5519 // Returns the next free property index (only valid for FAST MODE).
5520 int NextFreePropertyIndex();
5522 // Returns the number of properties described in instance_descriptors
5523 // filtering out properties with the specified attributes.
5524 int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
5525 PropertyAttributes filter = NONE);
5529 // Code cache operations.
5531 // Clears the code cache.
5532 inline void ClearCodeCache(Heap* heap);
5534 // Update code cache.
5535 static void UpdateCodeCache(Handle<Map> map,
5539 // Extend the descriptor array of the map with the list of descriptors.
5540 // In case of duplicates, the latest descriptor is used.
5541 static void AppendCallbackDescriptors(Handle<Map> map,
5542 Handle<Object> descriptors);
5544 static inline int SlackForArraySize(int old_size, int size_limit);
5546 static void EnsureDescriptorSlack(Handle<Map> map, int slack);
5548 // Returns the found code or undefined if absent.
5549 Object* FindInCodeCache(Name* name, Code::Flags flags);
5551 // Returns the non-negative index of the code object if it is in the
5552 // cache and -1 otherwise.
5553 int IndexInCodeCache(Object* name, Code* code);
5555 // Removes a code object from the code cache at the given index.
5556 void RemoveFromCodeCache(Name* name, Code* code, int index);
5558 // Computes a hash value for this map, to be used in HashTables and such.
5561 // Returns the map that this map transitions to if its elements_kind
5562 // is changed to |elements_kind|, or NULL if no such map is cached yet.
5563 // |safe_to_add_transitions| is set to false if adding transitions is not
5565 Map* LookupElementsTransitionMap(ElementsKind elements_kind);
5567 // Returns the transitioned map for this map with the most generic
5568 // elements_kind that's found in |candidates|, or null handle if no match is
5570 static Handle<Map> FindTransitionedMap(Handle<Map> map,
5571 MapHandleList* candidates);
5573 inline bool CanTransition();
5575 inline bool IsPrimitiveMap();
5576 inline bool IsJSObjectMap();
5577 inline bool IsJSArrayMap();
5578 inline bool IsStringMap();
5579 inline bool IsJSProxyMap();
5580 inline bool IsJSGlobalProxyMap();
5581 inline bool IsJSGlobalObjectMap();
5582 inline bool IsGlobalObjectMap();
5584 inline bool CanOmitMapChecks();
5586 static void AddDependentCode(Handle<Map> map,
5587 DependentCode::DependencyGroup group,
5590 bool IsMapInArrayPrototypeChain();
5592 static Handle<WeakCell> WeakCellForMap(Handle<Map> map);
5594 // Dispatched behavior.
5595 DECLARE_PRINTER(Map)
5596 DECLARE_VERIFIER(Map)
5599 void DictionaryMapVerify();
5600 void VerifyOmittedMapChecks();
5603 inline int visitor_id();
5604 inline void set_visitor_id(int visitor_id);
5606 static Handle<Map> TransitionToPrototype(Handle<Map> map,
5607 Handle<Object> prototype,
5608 PrototypeOptimizationMode mode);
5610 static const int kMaxPreAllocatedPropertyFields = 255;
5612 // Layout description.
5613 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
5614 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
5615 static const int kBitField3Offset = kInstanceAttributesOffset + kIntSize;
5616 static const int kPrototypeOffset = kBitField3Offset + kPointerSize;
5617 static const int kConstructorOrBackPointerOffset =
5618 kPrototypeOffset + kPointerSize;
5619 // When there is only one transition, it is stored directly in this field;
5620 // otherwise a transition array is used.
5621 // For prototype maps, this slot is used to store this map's PrototypeInfo
5623 static const int kTransitionsOrPrototypeInfoOffset =
5624 kConstructorOrBackPointerOffset + kPointerSize;
5625 static const int kDescriptorsOffset =
5626 kTransitionsOrPrototypeInfoOffset + kPointerSize;
5627 #if V8_DOUBLE_FIELDS_UNBOXING
5628 static const int kLayoutDecriptorOffset = kDescriptorsOffset + kPointerSize;
5629 static const int kCodeCacheOffset = kLayoutDecriptorOffset + kPointerSize;
5631 static const int kLayoutDecriptorOffset = 1; // Must not be ever accessed.
5632 static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
5634 static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
5635 static const int kWeakCellCacheOffset = kDependentCodeOffset + kPointerSize;
5636 static const int kSize = kWeakCellCacheOffset + kPointerSize;
5638 // Layout of pointer fields. Heap iteration code relies on them
5639 // being continuously allocated.
5640 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
5641 static const int kPointerFieldsEndOffset = kSize;
5643 // Byte offsets within kInstanceSizesOffset.
5644 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
5645 static const int kInObjectPropertiesOrConstructorFunctionIndexByte = 1;
5646 static const int kInObjectPropertiesOrConstructorFunctionIndexOffset =
5647 kInstanceSizesOffset + kInObjectPropertiesOrConstructorFunctionIndexByte;
5648 // Note there is one byte available for use here.
5649 static const int kUnusedByte = 2;
5650 static const int kUnusedOffset = kInstanceSizesOffset + kUnusedByte;
5651 static const int kVisitorIdByte = 3;
5652 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
5654 // Byte offsets within kInstanceAttributesOffset attributes.
5655 #if V8_TARGET_LITTLE_ENDIAN
5656 // Order instance type and bit field together such that they can be loaded
5657 // together as a 16-bit word with instance type in the lower 8 bits regardless
5658 // of endianess. Also provide endian-independent offset to that 16-bit word.
5659 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
5660 static const int kBitFieldOffset = kInstanceAttributesOffset + 1;
5662 static const int kBitFieldOffset = kInstanceAttributesOffset + 0;
5663 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 1;
5665 static const int kInstanceTypeAndBitFieldOffset =
5666 kInstanceAttributesOffset + 0;
5667 static const int kBitField2Offset = kInstanceAttributesOffset + 2;
5668 static const int kUnusedPropertyFieldsByte = 3;
5669 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 3;
5671 STATIC_ASSERT(kInstanceTypeAndBitFieldOffset ==
5672 Internals::kMapInstanceTypeAndBitFieldOffset);
5674 // Bit positions for bit field.
5675 static const int kHasNonInstancePrototype = 0;
5676 static const int kIsHiddenPrototype = 1;
5677 static const int kHasNamedInterceptor = 2;
5678 static const int kHasIndexedInterceptor = 3;
5679 static const int kIsUndetectable = 4;
5680 static const int kIsObserved = 5;
5681 static const int kIsAccessCheckNeeded = 6;
5682 class FunctionWithPrototype: public BitField<bool, 7, 1> {};
5684 // Bit positions for bit field 2
5685 static const int kIsExtensible = 0;
5686 static const int kStringWrapperSafeForDefaultValueOf = 1;
5687 class IsPrototypeMapBits : public BitField<bool, 2, 1> {};
5688 class ElementsKindBits: public BitField<ElementsKind, 3, 5> {};
5690 // Derived values from bit field 2
5691 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
5692 (FAST_ELEMENTS + 1) << Map::ElementsKindBits::kShift) - 1;
5693 static const int8_t kMaximumBitField2FastSmiElementValue =
5694 static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
5695 Map::ElementsKindBits::kShift) - 1;
5696 static const int8_t kMaximumBitField2FastHoleyElementValue =
5697 static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
5698 Map::ElementsKindBits::kShift) - 1;
5699 static const int8_t kMaximumBitField2FastHoleySmiElementValue =
5700 static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
5701 Map::ElementsKindBits::kShift) - 1;
5703 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
5704 kPointerFieldsEndOffset,
5705 kSize> BodyDescriptor;
5707 // Compares this map to another to see if they describe equivalent objects.
5708 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
5709 // it had exactly zero inobject properties.
5710 // The "shared" flags of both this map and |other| are ignored.
5711 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
5713 // Returns true if given field is unboxed double.
5714 inline bool IsUnboxedDoubleField(FieldIndex index);
5717 static void TraceTransition(const char* what, Map* from, Map* to, Name* name);
5718 static void TraceAllTransitions(Map* map);
5721 static inline Handle<Map> CopyInstallDescriptorsForTesting(
5722 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5723 Handle<LayoutDescriptor> layout_descriptor);
5726 static void ConnectTransition(Handle<Map> parent, Handle<Map> child,
5727 Handle<Name> name, SimpleTransitionFlag flag);
5729 bool EquivalentToForTransition(Map* other);
5730 static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
5731 static Handle<Map> ShareDescriptor(Handle<Map> map,
5732 Handle<DescriptorArray> descriptors,
5733 Descriptor* descriptor);
5734 static Handle<Map> CopyInstallDescriptors(
5735 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5736 Handle<LayoutDescriptor> layout_descriptor);
5737 static Handle<Map> CopyAddDescriptor(Handle<Map> map,
5738 Descriptor* descriptor,
5739 TransitionFlag flag);
5740 static Handle<Map> CopyReplaceDescriptors(
5741 Handle<Map> map, Handle<DescriptorArray> descriptors,
5742 Handle<LayoutDescriptor> layout_descriptor, TransitionFlag flag,
5743 MaybeHandle<Name> maybe_name, const char* reason,
5744 SimpleTransitionFlag simple_flag);
5746 static Handle<Map> CopyReplaceDescriptor(Handle<Map> map,
5747 Handle<DescriptorArray> descriptors,
5748 Descriptor* descriptor,
5750 TransitionFlag flag);
5751 static MUST_USE_RESULT MaybeHandle<Map> TryReconfigureExistingProperty(
5752 Handle<Map> map, int descriptor, PropertyKind kind,
5753 PropertyAttributes attributes, const char** reason);
5755 static Handle<Map> CopyNormalized(Handle<Map> map,
5756 PropertyNormalizationMode mode);
5758 // Fires when the layout of an object with a leaf map changes.
5759 // This includes adding transitions to the leaf map or changing
5760 // the descriptor array.
5761 inline void NotifyLeafMapLayoutChange();
5763 void DeprecateTransitionTree();
5764 bool DeprecateTarget(PropertyKind kind, Name* key,
5765 PropertyAttributes attributes,
5766 DescriptorArray* new_descriptors,
5767 LayoutDescriptor* new_layout_descriptor);
5769 Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
5771 // Update field type of the given descriptor to new representation and new
5772 // type. The type must be prepared for storing in descriptor array:
5773 // it must be either a simple type or a map wrapped in a weak cell.
5774 void UpdateFieldType(int descriptor_number, Handle<Name> name,
5775 Representation new_representation,
5776 Handle<Object> new_wrapped_type);
5778 void PrintReconfiguration(FILE* file, int modify_index, PropertyKind kind,
5779 PropertyAttributes attributes);
5780 void PrintGeneralization(FILE* file,
5785 bool constant_to_field,
5786 Representation old_representation,
5787 Representation new_representation,
5788 HeapType* old_field_type,
5789 HeapType* new_field_type);
5791 static const int kFastPropertiesSoftLimit = 12;
5792 static const int kMaxFastProperties = 128;
5794 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
5798 // An abstract superclass, a marker class really, for simple structure classes.
5799 // It doesn't carry much functionality but allows struct classes to be
5800 // identified in the type system.
5801 class Struct: public HeapObject {
5803 inline void InitializeBody(int object_size);
5804 DECLARE_CAST(Struct)
5808 // A simple one-element struct, useful where smis need to be boxed.
5809 class Box : public Struct {
5811 // [value]: the boxed contents.
5812 DECL_ACCESSORS(value, Object)
5816 // Dispatched behavior.
5817 DECLARE_PRINTER(Box)
5818 DECLARE_VERIFIER(Box)
5820 static const int kValueOffset = HeapObject::kHeaderSize;
5821 static const int kSize = kValueOffset + kPointerSize;
5824 DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
5828 // Container for metadata stored on each prototype map.
5829 class PrototypeInfo : public Struct {
5831 static const int UNREGISTERED = -1;
5833 // [prototype_users]: WeakFixedArray containing maps using this prototype,
5834 // or Smi(0) if uninitialized.
5835 DECL_ACCESSORS(prototype_users, Object)
5836 // [registry_slot]: Slot in prototype's user registry where this user
5837 // is stored. Returns UNREGISTERED if this prototype has not been registered.
5838 inline int registry_slot() const;
5839 inline void set_registry_slot(int slot);
5840 // [validity_cell]: Cell containing the validity bit for prototype chains
5841 // going through this object, or Smi(0) if uninitialized.
5842 DECL_ACCESSORS(validity_cell, Object)
5843 // [constructor_name]: User-friendly name of the original constructor.
5844 DECL_ACCESSORS(constructor_name, Object)
5846 DECLARE_CAST(PrototypeInfo)
5848 // Dispatched behavior.
5849 DECLARE_PRINTER(PrototypeInfo)
5850 DECLARE_VERIFIER(PrototypeInfo)
5852 static const int kPrototypeUsersOffset = HeapObject::kHeaderSize;
5853 static const int kRegistrySlotOffset = kPrototypeUsersOffset + kPointerSize;
5854 static const int kValidityCellOffset = kRegistrySlotOffset + kPointerSize;
5855 static const int kConstructorNameOffset = kValidityCellOffset + kPointerSize;
5856 static const int kSize = kConstructorNameOffset + kPointerSize;
5859 DISALLOW_IMPLICIT_CONSTRUCTORS(PrototypeInfo);
5863 // Script describes a script which has been added to the VM.
5864 class Script: public Struct {
5873 // Script compilation types.
5874 enum CompilationType {
5875 COMPILATION_TYPE_HOST = 0,
5876 COMPILATION_TYPE_EVAL = 1
5879 // Script compilation state.
5880 enum CompilationState {
5881 COMPILATION_STATE_INITIAL = 0,
5882 COMPILATION_STATE_COMPILED = 1
5885 // [source]: the script source.
5886 DECL_ACCESSORS(source, Object)
5888 // [name]: the script name.
5889 DECL_ACCESSORS(name, Object)
5891 // [id]: the script id.
5892 DECL_ACCESSORS(id, Smi)
5894 // [line_offset]: script line offset in resource from where it was extracted.
5895 DECL_ACCESSORS(line_offset, Smi)
5897 // [column_offset]: script column offset in resource from where it was
5899 DECL_ACCESSORS(column_offset, Smi)
5901 // [context_data]: context data for the context this script was compiled in.
5902 DECL_ACCESSORS(context_data, Object)
5904 // [wrapper]: the wrapper cache. This is either undefined or a WeakCell.
5905 DECL_ACCESSORS(wrapper, HeapObject)
5907 // [type]: the script type.
5908 DECL_ACCESSORS(type, Smi)
5910 // [line_ends]: FixedArray of line ends positions.
5911 DECL_ACCESSORS(line_ends, Object)
5913 // [eval_from_shared]: for eval scripts the shared funcion info for the
5914 // function from which eval was called.
5915 DECL_ACCESSORS(eval_from_shared, Object)
5917 // [eval_from_instructions_offset]: the instruction offset in the code for the
5918 // function from which eval was called where eval was called.
5919 DECL_ACCESSORS(eval_from_instructions_offset, Smi)
5921 // [shared_function_infos]: weak fixed array containing all shared
5922 // function infos created from this script.
5923 DECL_ACCESSORS(shared_function_infos, Object)
5925 // [flags]: Holds an exciting bitfield.
5926 DECL_ACCESSORS(flags, Smi)
5928 // [source_url]: sourceURL from magic comment
5929 DECL_ACCESSORS(source_url, Object)
5931 // [source_url]: sourceMappingURL magic comment
5932 DECL_ACCESSORS(source_mapping_url, Object)
5934 // [compilation_type]: how the the script was compiled. Encoded in the
5936 inline CompilationType compilation_type();
5937 inline void set_compilation_type(CompilationType type);
5939 // [compilation_state]: determines whether the script has already been
5940 // compiled. Encoded in the 'flags' field.
5941 inline CompilationState compilation_state();
5942 inline void set_compilation_state(CompilationState state);
5944 // [origin_options]: optional attributes set by the embedder via ScriptOrigin,
5945 // and used by the embedder to make decisions about the script. V8 just passes
5946 // this through. Encoded in the 'flags' field.
5947 inline v8::ScriptOriginOptions origin_options();
5948 inline void set_origin_options(ScriptOriginOptions origin_options);
5950 DECLARE_CAST(Script)
5952 // If script source is an external string, check that the underlying
5953 // resource is accessible. Otherwise, always return true.
5954 inline bool HasValidSource();
5956 // Convert code position into column number.
5957 static int GetColumnNumber(Handle<Script> script, int code_pos);
5959 // Convert code position into (zero-based) line number.
5960 // The non-handlified version does not allocate, but may be much slower.
5961 static int GetLineNumber(Handle<Script> script, int code_pos);
5962 int GetLineNumber(int code_pos);
5964 static Handle<Object> GetNameOrSourceURL(Handle<Script> script);
5966 // Init line_ends array with code positions of line ends inside script source.
5967 static void InitLineEnds(Handle<Script> script);
5969 // Get the JS object wrapping the given script; create it if none exists.
5970 static Handle<JSObject> GetWrapper(Handle<Script> script);
5972 // Look through the list of existing shared function infos to find one
5973 // that matches the function literal. Return empty handle if not found.
5974 MaybeHandle<SharedFunctionInfo> FindSharedFunctionInfo(FunctionLiteral* fun);
5976 // Dispatched behavior.
5977 DECLARE_PRINTER(Script)
5978 DECLARE_VERIFIER(Script)
5980 static const int kSourceOffset = HeapObject::kHeaderSize;
5981 static const int kNameOffset = kSourceOffset + kPointerSize;
5982 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
5983 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
5984 static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
5985 static const int kWrapperOffset = kContextOffset + kPointerSize;
5986 static const int kTypeOffset = kWrapperOffset + kPointerSize;
5987 static const int kLineEndsOffset = kTypeOffset + kPointerSize;
5988 static const int kIdOffset = kLineEndsOffset + kPointerSize;
5989 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
5990 static const int kEvalFrominstructionsOffsetOffset =
5991 kEvalFromSharedOffset + kPointerSize;
5992 static const int kSharedFunctionInfosOffset =
5993 kEvalFrominstructionsOffsetOffset + kPointerSize;
5994 static const int kFlagsOffset = kSharedFunctionInfosOffset + kPointerSize;
5995 static const int kSourceUrlOffset = kFlagsOffset + kPointerSize;
5996 static const int kSourceMappingUrlOffset = kSourceUrlOffset + kPointerSize;
5997 static const int kSize = kSourceMappingUrlOffset + kPointerSize;
6000 int GetLineNumberWithArray(int code_pos);
6002 // Bit positions in the flags field.
6003 static const int kCompilationTypeBit = 0;
6004 static const int kCompilationStateBit = 1;
6005 static const int kOriginOptionsShift = 2;
6006 static const int kOriginOptionsSize = 3;
6007 static const int kOriginOptionsMask = ((1 << kOriginOptionsSize) - 1)
6008 << kOriginOptionsShift;
6010 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6014 // List of builtin functions we want to identify to improve code
6017 // Each entry has a name of a global object property holding an object
6018 // optionally followed by ".prototype", a name of a builtin function
6019 // on the object (the one the id is set for), and a label.
6021 // Installation of ids for the selected builtin functions is handled
6022 // by the bootstrapper.
6023 #define FUNCTIONS_WITH_ID_LIST(V) \
6024 V(Array.prototype, indexOf, ArrayIndexOf) \
6025 V(Array.prototype, lastIndexOf, ArrayLastIndexOf) \
6026 V(Array.prototype, push, ArrayPush) \
6027 V(Array.prototype, pop, ArrayPop) \
6028 V(Array.prototype, shift, ArrayShift) \
6029 V(Function.prototype, apply, FunctionApply) \
6030 V(Function.prototype, call, FunctionCall) \
6031 V(String.prototype, charCodeAt, StringCharCodeAt) \
6032 V(String.prototype, charAt, StringCharAt) \
6033 V(String, fromCharCode, StringFromCharCode) \
6034 V(Math, random, MathRandom) \
6035 V(Math, floor, MathFloor) \
6036 V(Math, round, MathRound) \
6037 V(Math, ceil, MathCeil) \
6038 V(Math, abs, MathAbs) \
6039 V(Math, log, MathLog) \
6040 V(Math, exp, MathExp) \
6041 V(Math, sqrt, MathSqrt) \
6042 V(Math, pow, MathPow) \
6043 V(Math, max, MathMax) \
6044 V(Math, min, MathMin) \
6045 V(Math, cos, MathCos) \
6046 V(Math, sin, MathSin) \
6047 V(Math, tan, MathTan) \
6048 V(Math, acos, MathAcos) \
6049 V(Math, asin, MathAsin) \
6050 V(Math, atan, MathAtan) \
6051 V(Math, atan2, MathAtan2) \
6052 V(Math, imul, MathImul) \
6053 V(Math, clz32, MathClz32) \
6054 V(Math, fround, MathFround)
6056 #define ATOMIC_FUNCTIONS_WITH_ID_LIST(V) \
6057 V(Atomics, load, AtomicsLoad) \
6058 V(Atomics, store, AtomicsStore)
6060 enum BuiltinFunctionId {
6062 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
6064 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6065 ATOMIC_FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6066 #undef DECLARE_FUNCTION_ID
6067 // Fake id for a special case of Math.pow. Note, it continues the
6068 // list of math functions.
6073 // Result of searching in an optimized code map of a SharedFunctionInfo. Note
6074 // that both {code} and {literals} can be NULL to pass search result status.
6075 struct CodeAndLiterals {
6076 Code* code; // Cached optimized code.
6077 FixedArray* literals; // Cached literals array.
6081 // SharedFunctionInfo describes the JSFunction information that can be
6082 // shared by multiple instances of the function.
6083 class SharedFunctionInfo: public HeapObject {
6085 // [name]: Function name.
6086 DECL_ACCESSORS(name, Object)
6088 // [code]: Function code.
6089 DECL_ACCESSORS(code, Code)
6090 inline void ReplaceCode(Code* code);
6092 // [optimized_code_map]: Map from native context to optimized code
6093 // and a shared literals array or Smi(0) if none.
6094 DECL_ACCESSORS(optimized_code_map, Object)
6096 // Returns entry from optimized code map for specified context and OSR entry.
6097 // Note that {code == nullptr} indicates no matching entry has been found,
6098 // whereas {literals == nullptr} indicates the code is context-independent.
6099 CodeAndLiterals SearchOptimizedCodeMap(Context* native_context,
6100 BailoutId osr_ast_id);
6102 // Clear optimized code map.
6103 void ClearOptimizedCodeMap();
6105 // Removed a specific optimized code object from the optimized code map.
6106 void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
6108 // Trims the optimized code map after entries have been removed.
6109 void TrimOptimizedCodeMap(int shrink_by);
6111 // Add a new entry to the optimized code map for context-independent code.
6112 static void AddSharedCodeToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6115 // Add a new entry to the optimized code map for context-dependent code.
6116 static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6117 Handle<Context> native_context,
6119 Handle<FixedArray> literals,
6120 BailoutId osr_ast_id);
6122 // Set up the link between shared function info and the script. The shared
6123 // function info is added to the list on the script.
6124 static void SetScript(Handle<SharedFunctionInfo> shared,
6125 Handle<Object> script_object);
6127 // Layout description of the optimized code map.
6128 static const int kNextMapIndex = 0;
6129 static const int kSharedCodeIndex = 1;
6130 static const int kEntriesStart = 2;
6131 static const int kContextOffset = 0;
6132 static const int kCachedCodeOffset = 1;
6133 static const int kLiteralsOffset = 2;
6134 static const int kOsrAstIdOffset = 3;
6135 static const int kEntryLength = 4;
6136 static const int kInitialLength = kEntriesStart + kEntryLength;
6138 // [scope_info]: Scope info.
6139 DECL_ACCESSORS(scope_info, ScopeInfo)
6141 // [construct stub]: Code stub for constructing instances of this function.
6142 DECL_ACCESSORS(construct_stub, Code)
6144 // Returns if this function has been compiled to native code yet.
6145 inline bool is_compiled();
6147 // [length]: The function length - usually the number of declared parameters.
6148 // Use up to 2^30 parameters.
6149 inline int length() const;
6150 inline void set_length(int value);
6152 // [internal formal parameter count]: The declared number of parameters.
6153 // For subclass constructors, also includes new.target.
6154 // The size of function's frame is internal_formal_parameter_count + 1.
6155 inline int internal_formal_parameter_count() const;
6156 inline void set_internal_formal_parameter_count(int value);
6158 // Set the formal parameter count so the function code will be
6159 // called without using argument adaptor frames.
6160 inline void DontAdaptArguments();
6162 // [expected_nof_properties]: Expected number of properties for the function.
6163 inline int expected_nof_properties() const;
6164 inline void set_expected_nof_properties(int value);
6166 // [feedback_vector] - accumulates ast node feedback from full-codegen and
6167 // (increasingly) from crankshafted code where sufficient feedback isn't
6169 DECL_ACCESSORS(feedback_vector, TypeFeedbackVector)
6171 // Unconditionally clear the type feedback vector (including vector ICs).
6172 void ClearTypeFeedbackInfo();
6174 // Clear the type feedback vector with a more subtle policy at GC time.
6175 void ClearTypeFeedbackInfoAtGCTime();
6178 // [unique_id] - For --trace-maps purposes, an identifier that's persistent
6179 // even if the GC moves this SharedFunctionInfo.
6180 inline int unique_id() const;
6181 inline void set_unique_id(int value);
6184 // [instance class name]: class name for instances.
6185 DECL_ACCESSORS(instance_class_name, Object)
6187 // [function data]: This field holds some additional data for function.
6188 // Currently it has one of:
6189 // - a FunctionTemplateInfo to make benefit the API [IsApiFunction()].
6190 // - a Smi identifying a builtin function [HasBuiltinFunctionId()].
6191 // - a BytecodeArray for the interpreter [HasBytecodeArray()].
6192 // In the long run we don't want all functions to have this field but
6193 // we can fix that when we have a better model for storing hidden data
6195 DECL_ACCESSORS(function_data, Object)
6197 inline bool IsApiFunction();
6198 inline FunctionTemplateInfo* get_api_func_data();
6199 inline bool HasBuiltinFunctionId();
6200 inline BuiltinFunctionId builtin_function_id();
6201 inline bool HasBytecodeArray();
6202 inline BytecodeArray* bytecode_array();
6204 // [script info]: Script from which the function originates.
6205 DECL_ACCESSORS(script, Object)
6207 // [num_literals]: Number of literals used by this function.
6208 inline int num_literals() const;
6209 inline void set_num_literals(int value);
6211 // [start_position_and_type]: Field used to store both the source code
6212 // position, whether or not the function is a function expression,
6213 // and whether or not the function is a toplevel function. The two
6214 // least significants bit indicates whether the function is an
6215 // expression and the rest contains the source code position.
6216 inline int start_position_and_type() const;
6217 inline void set_start_position_and_type(int value);
6219 // The function is subject to debugging if a debug info is attached.
6220 inline bool HasDebugInfo();
6221 inline DebugInfo* GetDebugInfo();
6223 // A function has debug code if the compiled code has debug break slots.
6224 inline bool HasDebugCode();
6226 // [debug info]: Debug information.
6227 DECL_ACCESSORS(debug_info, Object)
6229 // [inferred name]: Name inferred from variable or property
6230 // assignment of this function. Used to facilitate debugging and
6231 // profiling of JavaScript code written in OO style, where almost
6232 // all functions are anonymous but are assigned to object
6234 DECL_ACCESSORS(inferred_name, String)
6236 // The function's name if it is non-empty, otherwise the inferred name.
6237 String* DebugName();
6239 // Position of the 'function' token in the script source.
6240 inline int function_token_position() const;
6241 inline void set_function_token_position(int function_token_position);
6243 // Position of this function in the script source.
6244 inline int start_position() const;
6245 inline void set_start_position(int start_position);
6247 // End position of this function in the script source.
6248 inline int end_position() const;
6249 inline void set_end_position(int end_position);
6251 // Is this function a function expression in the source code.
6252 DECL_BOOLEAN_ACCESSORS(is_expression)
6254 // Is this function a top-level function (scripts, evals).
6255 DECL_BOOLEAN_ACCESSORS(is_toplevel)
6257 // Bit field containing various information collected by the compiler to
6258 // drive optimization.
6259 inline int compiler_hints() const;
6260 inline void set_compiler_hints(int value);
6262 inline int ast_node_count() const;
6263 inline void set_ast_node_count(int count);
6265 inline int profiler_ticks() const;
6266 inline void set_profiler_ticks(int ticks);
6268 // Inline cache age is used to infer whether the function survived a context
6269 // disposal or not. In the former case we reset the opt_count.
6270 inline int ic_age();
6271 inline void set_ic_age(int age);
6273 // Indicates if this function can be lazy compiled.
6274 // This is used to determine if we can safely flush code from a function
6275 // when doing GC if we expect that the function will no longer be used.
6276 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
6278 // Indicates if this function can be lazy compiled without a context.
6279 // This is used to determine if we can force compilation without reaching
6280 // the function through program execution but through other means (e.g. heap
6281 // iteration by the debugger).
6282 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
6284 // Indicates whether optimizations have been disabled for this
6285 // shared function info. If a function is repeatedly optimized or if
6286 // we cannot optimize the function we disable optimization to avoid
6287 // spending time attempting to optimize it again.
6288 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
6290 // Indicates the language mode.
6291 inline LanguageMode language_mode();
6292 inline void set_language_mode(LanguageMode language_mode);
6294 // False if the function definitely does not allocate an arguments object.
6295 DECL_BOOLEAN_ACCESSORS(uses_arguments)
6297 // Indicates that this function uses a super property (or an eval that may
6298 // use a super property).
6299 // This is needed to set up the [[HomeObject]] on the function instance.
6300 DECL_BOOLEAN_ACCESSORS(needs_home_object)
6302 // True if the function has any duplicated parameter names.
6303 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
6305 // Indicates whether the function is a native function.
6306 // These needs special treatment in .call and .apply since
6307 // null passed as the receiver should not be translated to the
6309 DECL_BOOLEAN_ACCESSORS(native)
6311 // Indicate that this function should always be inlined in optimized code.
6312 DECL_BOOLEAN_ACCESSORS(force_inline)
6314 // Indicates that the function was created by the Function function.
6315 // Though it's anonymous, toString should treat it as if it had the name
6316 // "anonymous". We don't set the name itself so that the system does not
6317 // see a binding for it.
6318 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
6320 // Indicates whether the function is a bound function created using
6321 // the bind function.
6322 DECL_BOOLEAN_ACCESSORS(bound)
6324 // Indicates that the function is anonymous (the name field can be set
6325 // through the API, which does not change this flag).
6326 DECL_BOOLEAN_ACCESSORS(is_anonymous)
6328 // Is this a function or top-level/eval code.
6329 DECL_BOOLEAN_ACCESSORS(is_function)
6331 // Indicates that code for this function cannot be compiled with Crankshaft.
6332 DECL_BOOLEAN_ACCESSORS(dont_crankshaft)
6334 // Indicates that code for this function cannot be flushed.
6335 DECL_BOOLEAN_ACCESSORS(dont_flush)
6337 // Indicates that this function is a generator.
6338 DECL_BOOLEAN_ACCESSORS(is_generator)
6340 // Indicates that this function is an arrow function.
6341 DECL_BOOLEAN_ACCESSORS(is_arrow)
6343 // Indicates that this function is a concise method.
6344 DECL_BOOLEAN_ACCESSORS(is_concise_method)
6346 // Indicates that this function is an accessor (getter or setter).
6347 DECL_BOOLEAN_ACCESSORS(is_accessor_function)
6349 // Indicates that this function is a default constructor.
6350 DECL_BOOLEAN_ACCESSORS(is_default_constructor)
6352 // Indicates that this function is an asm function.
6353 DECL_BOOLEAN_ACCESSORS(asm_function)
6355 // Indicates that the the shared function info is deserialized from cache.
6356 DECL_BOOLEAN_ACCESSORS(deserialized)
6358 // Indicates that the the shared function info has never been compiled before.
6359 DECL_BOOLEAN_ACCESSORS(never_compiled)
6361 inline FunctionKind kind();
6362 inline void set_kind(FunctionKind kind);
6364 // Indicates whether or not the code in the shared function support
6366 inline bool has_deoptimization_support();
6368 // Enable deoptimization support through recompiled code.
6369 void EnableDeoptimizationSupport(Code* recompiled);
6371 // Disable (further) attempted optimization of all functions sharing this
6372 // shared function info.
6373 void DisableOptimization(BailoutReason reason);
6375 inline BailoutReason disable_optimization_reason();
6377 // Lookup the bailout ID and DCHECK that it exists in the non-optimized
6378 // code, returns whether it asserted (i.e., always true if assertions are
6380 bool VerifyBailoutId(BailoutId id);
6382 // [source code]: Source code for the function.
6383 bool HasSourceCode() const;
6384 Handle<Object> GetSourceCode();
6386 // Number of times the function was optimized.
6387 inline int opt_count();
6388 inline void set_opt_count(int opt_count);
6390 // Number of times the function was deoptimized.
6391 inline void set_deopt_count(int value);
6392 inline int deopt_count();
6393 inline void increment_deopt_count();
6395 // Number of time we tried to re-enable optimization after it
6396 // was disabled due to high number of deoptimizations.
6397 inline void set_opt_reenable_tries(int value);
6398 inline int opt_reenable_tries();
6400 inline void TryReenableOptimization();
6402 // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
6403 inline void set_counters(int value);
6404 inline int counters() const;
6406 // Stores opt_count and bailout_reason as bit-fields.
6407 inline void set_opt_count_and_bailout_reason(int value);
6408 inline int opt_count_and_bailout_reason() const;
6410 inline void set_disable_optimization_reason(BailoutReason reason);
6412 // Tells whether this function should be subject to debugging.
6413 inline bool IsSubjectToDebugging();
6415 // Check whether or not this function is inlineable.
6416 bool IsInlineable();
6418 // Source size of this function.
6421 // Calculate the instance size.
6422 int CalculateInstanceSize();
6424 // Calculate the number of in-object properties.
6425 int CalculateInObjectProperties();
6427 inline bool has_simple_parameters();
6429 // Initialize a SharedFunctionInfo from a parsed function literal.
6430 static void InitFromFunctionLiteral(Handle<SharedFunctionInfo> shared_info,
6431 FunctionLiteral* lit);
6433 // Dispatched behavior.
6434 DECLARE_PRINTER(SharedFunctionInfo)
6435 DECLARE_VERIFIER(SharedFunctionInfo)
6437 void ResetForNewContext(int new_ic_age);
6439 DECLARE_CAST(SharedFunctionInfo)
6442 static const int kDontAdaptArgumentsSentinel = -1;
6444 // Layout description.
6446 static const int kNameOffset = HeapObject::kHeaderSize;
6447 static const int kCodeOffset = kNameOffset + kPointerSize;
6448 static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
6449 static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
6450 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
6451 static const int kInstanceClassNameOffset =
6452 kConstructStubOffset + kPointerSize;
6453 static const int kFunctionDataOffset =
6454 kInstanceClassNameOffset + kPointerSize;
6455 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
6456 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
6457 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
6458 static const int kFeedbackVectorOffset =
6459 kInferredNameOffset + kPointerSize;
6461 static const int kUniqueIdOffset = kFeedbackVectorOffset + kPointerSize;
6462 static const int kLastPointerFieldOffset = kUniqueIdOffset;
6464 // Just to not break the postmortrem support with conditional offsets
6465 static const int kUniqueIdOffset = kFeedbackVectorOffset;
6466 static const int kLastPointerFieldOffset = kFeedbackVectorOffset;
6469 #if V8_HOST_ARCH_32_BIT
6471 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6472 static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
6473 static const int kExpectedNofPropertiesOffset =
6474 kFormalParameterCountOffset + kPointerSize;
6475 static const int kNumLiteralsOffset =
6476 kExpectedNofPropertiesOffset + kPointerSize;
6477 static const int kStartPositionAndTypeOffset =
6478 kNumLiteralsOffset + kPointerSize;
6479 static const int kEndPositionOffset =
6480 kStartPositionAndTypeOffset + kPointerSize;
6481 static const int kFunctionTokenPositionOffset =
6482 kEndPositionOffset + kPointerSize;
6483 static const int kCompilerHintsOffset =
6484 kFunctionTokenPositionOffset + kPointerSize;
6485 static const int kOptCountAndBailoutReasonOffset =
6486 kCompilerHintsOffset + kPointerSize;
6487 static const int kCountersOffset =
6488 kOptCountAndBailoutReasonOffset + kPointerSize;
6489 static const int kAstNodeCountOffset =
6490 kCountersOffset + kPointerSize;
6491 static const int kProfilerTicksOffset =
6492 kAstNodeCountOffset + kPointerSize;
6495 static const int kSize = kProfilerTicksOffset + kPointerSize;
6497 // The only reason to use smi fields instead of int fields
6498 // is to allow iteration without maps decoding during
6499 // garbage collections.
6500 // To avoid wasting space on 64-bit architectures we use
6501 // the following trick: we group integer fields into pairs
6502 // The least significant integer in each pair is shifted left by 1.
6503 // By doing this we guarantee that LSB of each kPointerSize aligned
6504 // word is not set and thus this word cannot be treated as pointer
6505 // to HeapObject during old space traversal.
6506 #if V8_TARGET_LITTLE_ENDIAN
6507 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6508 static const int kFormalParameterCountOffset =
6509 kLengthOffset + kIntSize;
6511 static const int kExpectedNofPropertiesOffset =
6512 kFormalParameterCountOffset + kIntSize;
6513 static const int kNumLiteralsOffset =
6514 kExpectedNofPropertiesOffset + kIntSize;
6516 static const int kEndPositionOffset =
6517 kNumLiteralsOffset + kIntSize;
6518 static const int kStartPositionAndTypeOffset =
6519 kEndPositionOffset + kIntSize;
6521 static const int kFunctionTokenPositionOffset =
6522 kStartPositionAndTypeOffset + kIntSize;
6523 static const int kCompilerHintsOffset =
6524 kFunctionTokenPositionOffset + kIntSize;
6526 static const int kOptCountAndBailoutReasonOffset =
6527 kCompilerHintsOffset + kIntSize;
6528 static const int kCountersOffset =
6529 kOptCountAndBailoutReasonOffset + kIntSize;
6531 static const int kAstNodeCountOffset =
6532 kCountersOffset + kIntSize;
6533 static const int kProfilerTicksOffset =
6534 kAstNodeCountOffset + kIntSize;
6537 static const int kSize = kProfilerTicksOffset + kIntSize;
6539 #elif V8_TARGET_BIG_ENDIAN
6540 static const int kFormalParameterCountOffset =
6541 kLastPointerFieldOffset + kPointerSize;
6542 static const int kLengthOffset = kFormalParameterCountOffset + kIntSize;
6544 static const int kNumLiteralsOffset = kLengthOffset + kIntSize;
6545 static const int kExpectedNofPropertiesOffset = kNumLiteralsOffset + kIntSize;
6547 static const int kStartPositionAndTypeOffset =
6548 kExpectedNofPropertiesOffset + kIntSize;
6549 static const int kEndPositionOffset = kStartPositionAndTypeOffset + kIntSize;
6551 static const int kCompilerHintsOffset = kEndPositionOffset + kIntSize;
6552 static const int kFunctionTokenPositionOffset =
6553 kCompilerHintsOffset + kIntSize;
6555 static const int kCountersOffset = kFunctionTokenPositionOffset + kIntSize;
6556 static const int kOptCountAndBailoutReasonOffset = kCountersOffset + kIntSize;
6558 static const int kProfilerTicksOffset =
6559 kOptCountAndBailoutReasonOffset + kIntSize;
6560 static const int kAstNodeCountOffset = kProfilerTicksOffset + kIntSize;
6563 static const int kSize = kAstNodeCountOffset + kIntSize;
6566 #error Unknown byte ordering
6567 #endif // Big endian
6571 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
6573 typedef FixedBodyDescriptor<kNameOffset,
6574 kLastPointerFieldOffset + kPointerSize,
6575 kSize> BodyDescriptor;
6577 // Bit positions in start_position_and_type.
6578 // The source code start position is in the 30 most significant bits of
6579 // the start_position_and_type field.
6580 static const int kIsExpressionBit = 0;
6581 static const int kIsTopLevelBit = 1;
6582 static const int kStartPositionShift = 2;
6583 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
6585 // Bit positions in compiler_hints.
6586 enum CompilerHints {
6587 kAllowLazyCompilation,
6588 kAllowLazyCompilationWithoutContext,
6589 kOptimizationDisabled,
6590 kStrictModeFunction,
6591 kStrongModeFunction,
6594 kHasDuplicateParameters,
6599 kNameShouldPrintAsAnonymous,
6606 kIsAccessorFunction,
6607 kIsDefaultConstructor,
6608 kIsSubclassConstructor,
6614 kCompilerHintsCount // Pseudo entry
6616 // Add hints for other modes when they're added.
6617 STATIC_ASSERT(LANGUAGE_END == 3);
6619 class FunctionKindBits : public BitField<FunctionKind, kIsArrow, 8> {};
6621 class DeoptCountBits : public BitField<int, 0, 4> {};
6622 class OptReenableTriesBits : public BitField<int, 4, 18> {};
6623 class ICAgeBits : public BitField<int, 22, 8> {};
6625 class OptCountBits : public BitField<int, 0, 22> {};
6626 class DisabledOptimizationReasonBits : public BitField<int, 22, 8> {};
6629 #if V8_HOST_ARCH_32_BIT
6630 // On 32 bit platforms, compiler hints is a smi.
6631 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
6632 static const int kCompilerHintsSize = kPointerSize;
6634 // On 64 bit platforms, compiler hints is not a smi, see comment above.
6635 static const int kCompilerHintsSmiTagSize = 0;
6636 static const int kCompilerHintsSize = kIntSize;
6639 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
6640 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
6643 // Constants for optimizing codegen for strict mode function and
6645 // Allows to use byte-width instructions.
6646 static const int kStrictModeBitWithinByte =
6647 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6648 static const int kStrongModeBitWithinByte =
6649 (kStrongModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6651 static const int kNativeBitWithinByte =
6652 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
6654 #if defined(V8_TARGET_LITTLE_ENDIAN)
6655 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6656 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6657 static const int kStrongModeByteOffset =
6658 kCompilerHintsOffset +
6659 (kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6660 static const int kNativeByteOffset = kCompilerHintsOffset +
6661 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
6662 #elif defined(V8_TARGET_BIG_ENDIAN)
6663 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6664 (kCompilerHintsSize - 1) -
6665 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6666 static const int kStrongModeByteOffset =
6667 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6668 ((kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6669 static const int kNativeByteOffset = kCompilerHintsOffset +
6670 (kCompilerHintsSize - 1) -
6671 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
6673 #error Unknown byte ordering
6677 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
6681 // Printing support.
6682 struct SourceCodeOf {
6683 explicit SourceCodeOf(SharedFunctionInfo* v, int max = -1)
6684 : value(v), max_length(max) {}
6685 const SharedFunctionInfo* value;
6690 std::ostream& operator<<(std::ostream& os, const SourceCodeOf& v);
6693 class JSGeneratorObject: public JSObject {
6695 // [function]: The function corresponding to this generator object.
6696 DECL_ACCESSORS(function, JSFunction)
6698 // [context]: The context of the suspended computation.
6699 DECL_ACCESSORS(context, Context)
6701 // [receiver]: The receiver of the suspended computation.
6702 DECL_ACCESSORS(receiver, Object)
6704 // [continuation]: Offset into code of continuation.
6706 // A positive offset indicates a suspended generator. The special
6707 // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
6708 // cannot be resumed.
6709 inline int continuation() const;
6710 inline void set_continuation(int continuation);
6711 inline bool is_closed();
6712 inline bool is_executing();
6713 inline bool is_suspended();
6715 // [operand_stack]: Saved operand stack.
6716 DECL_ACCESSORS(operand_stack, FixedArray)
6718 DECLARE_CAST(JSGeneratorObject)
6720 // Dispatched behavior.
6721 DECLARE_PRINTER(JSGeneratorObject)
6722 DECLARE_VERIFIER(JSGeneratorObject)
6724 // Magic sentinel values for the continuation.
6725 static const int kGeneratorExecuting = -1;
6726 static const int kGeneratorClosed = 0;
6728 // Layout description.
6729 static const int kFunctionOffset = JSObject::kHeaderSize;
6730 static const int kContextOffset = kFunctionOffset + kPointerSize;
6731 static const int kReceiverOffset = kContextOffset + kPointerSize;
6732 static const int kContinuationOffset = kReceiverOffset + kPointerSize;
6733 static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
6734 static const int kSize = kOperandStackOffset + kPointerSize;
6736 // Resume mode, for use by runtime functions.
6737 enum ResumeMode { NEXT, THROW };
6739 // Yielding from a generator returns an object with the following inobject
6740 // properties. See Context::iterator_result_map() for the map.
6741 static const int kResultValuePropertyIndex = 0;
6742 static const int kResultDonePropertyIndex = 1;
6743 static const int kResultPropertyCount = 2;
6745 static const int kResultValuePropertyOffset = JSObject::kHeaderSize;
6746 static const int kResultDonePropertyOffset =
6747 kResultValuePropertyOffset + kPointerSize;
6748 static const int kResultSize = kResultDonePropertyOffset + kPointerSize;
6751 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
6755 // Representation for module instance objects.
6756 class JSModule: public JSObject {
6758 // [context]: the context holding the module's locals, or undefined if none.
6759 DECL_ACCESSORS(context, Object)
6761 // [scope_info]: Scope info.
6762 DECL_ACCESSORS(scope_info, ScopeInfo)
6764 DECLARE_CAST(JSModule)
6766 // Dispatched behavior.
6767 DECLARE_PRINTER(JSModule)
6768 DECLARE_VERIFIER(JSModule)
6770 // Layout description.
6771 static const int kContextOffset = JSObject::kHeaderSize;
6772 static const int kScopeInfoOffset = kContextOffset + kPointerSize;
6773 static const int kSize = kScopeInfoOffset + kPointerSize;
6776 DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
6780 // JSFunction describes JavaScript functions.
6781 class JSFunction: public JSObject {
6783 // [prototype_or_initial_map]:
6784 DECL_ACCESSORS(prototype_or_initial_map, Object)
6786 // [shared]: The information about the function that
6787 // can be shared by instances.
6788 DECL_ACCESSORS(shared, SharedFunctionInfo)
6790 // [context]: The context for this function.
6791 inline Context* context();
6792 inline void set_context(Object* context);
6793 inline JSObject* global_proxy();
6795 // [code]: The generated code object for this function. Executed
6796 // when the function is invoked, e.g. foo() or new foo(). See
6797 // [[Call]] and [[Construct]] description in ECMA-262, section
6799 inline Code* code();
6800 inline void set_code(Code* code);
6801 inline void set_code_no_write_barrier(Code* code);
6802 inline void ReplaceCode(Code* code);
6804 // Tells whether this function is builtin.
6805 inline bool IsBuiltin();
6807 // Tells whether this function inlines the given shared function info.
6808 bool Inlines(SharedFunctionInfo* candidate);
6810 // Tells whether this function should be subject to debugging.
6811 inline bool IsSubjectToDebugging();
6813 // Tells whether or not the function needs arguments adaption.
6814 inline bool NeedsArgumentsAdaption();
6816 // Tells whether or not this function has been optimized.
6817 inline bool IsOptimized();
6819 // Mark this function for lazy recompilation. The function will be
6820 // recompiled the next time it is executed.
6821 void MarkForOptimization();
6822 void AttemptConcurrentOptimization();
6824 // Tells whether or not the function is already marked for lazy
6826 inline bool IsMarkedForOptimization();
6827 inline bool IsMarkedForConcurrentOptimization();
6829 // Tells whether or not the function is on the concurrent recompilation queue.
6830 inline bool IsInOptimizationQueue();
6832 // Inobject slack tracking is the way to reclaim unused inobject space.
6834 // The instance size is initially determined by adding some slack to
6835 // expected_nof_properties (to allow for a few extra properties added
6836 // after the constructor). There is no guarantee that the extra space
6837 // will not be wasted.
6839 // Here is the algorithm to reclaim the unused inobject space:
6840 // - Detect the first constructor call for this JSFunction.
6841 // When it happens enter the "in progress" state: initialize construction
6842 // counter in the initial_map.
6843 // - While the tracking is in progress create objects filled with
6844 // one_pointer_filler_map instead of undefined_value. This way they can be
6845 // resized quickly and safely.
6846 // - Once enough objects have been created compute the 'slack'
6847 // (traverse the map transition tree starting from the
6848 // initial_map and find the lowest value of unused_property_fields).
6849 // - Traverse the transition tree again and decrease the instance size
6850 // of every map. Existing objects will resize automatically (they are
6851 // filled with one_pointer_filler_map). All further allocations will
6852 // use the adjusted instance size.
6853 // - SharedFunctionInfo's expected_nof_properties left unmodified since
6854 // allocations made using different closures could actually create different
6855 // kind of objects (see prototype inheritance pattern).
6857 // Important: inobject slack tracking is not attempted during the snapshot
6860 // True if the initial_map is set and the object constructions countdown
6861 // counter is not zero.
6862 static const int kGenerousAllocationCount =
6863 Map::kSlackTrackingCounterStart - Map::kSlackTrackingCounterEnd + 1;
6864 inline bool IsInobjectSlackTrackingInProgress();
6866 // Starts the tracking.
6867 // Initializes object constructions countdown counter in the initial map.
6868 void StartInobjectSlackTracking();
6870 // Completes the tracking.
6871 void CompleteInobjectSlackTracking();
6873 // [literals_or_bindings]: Fixed array holding either
6874 // the materialized literals or the bindings of a bound function.
6876 // If the function contains object, regexp or array literals, the
6877 // literals array prefix contains the object, regexp, and array
6878 // function to be used when creating these literals. This is
6879 // necessary so that we do not dynamically lookup the object, regexp
6880 // or array functions. Performing a dynamic lookup, we might end up
6881 // using the functions from a new context that we should not have
6884 // On bound functions, the array is a (copy-on-write) fixed-array containing
6885 // the function that was bound, bound this-value and any bound
6886 // arguments. Bound functions never contain literals.
6887 DECL_ACCESSORS(literals_or_bindings, FixedArray)
6889 inline FixedArray* literals();
6890 inline void set_literals(FixedArray* literals);
6892 inline FixedArray* function_bindings();
6893 inline void set_function_bindings(FixedArray* bindings);
6895 // The initial map for an object created by this constructor.
6896 inline Map* initial_map();
6897 static void SetInitialMap(Handle<JSFunction> function, Handle<Map> map,
6898 Handle<Object> prototype);
6899 inline bool has_initial_map();
6900 static void EnsureHasInitialMap(Handle<JSFunction> function);
6902 // Get and set the prototype property on a JSFunction. If the
6903 // function has an initial map the prototype is set on the initial
6904 // map. Otherwise, the prototype is put in the initial map field
6905 // until an initial map is needed.
6906 inline bool has_prototype();
6907 inline bool has_instance_prototype();
6908 inline Object* prototype();
6909 inline Object* instance_prototype();
6910 static void SetPrototype(Handle<JSFunction> function,
6911 Handle<Object> value);
6912 static void SetInstancePrototype(Handle<JSFunction> function,
6913 Handle<Object> value);
6915 // Creates a new closure for the fucntion with the same bindings,
6916 // bound values, and prototype. An equivalent of spec operations
6917 // ``CloneMethod`` and ``CloneBoundFunction``.
6918 static Handle<JSFunction> CloneClosure(Handle<JSFunction> function);
6920 // After prototype is removed, it will not be created when accessed, and
6921 // [[Construct]] from this function will not be allowed.
6922 bool RemovePrototype();
6923 inline bool should_have_prototype();
6925 // Accessor for this function's initial map's [[class]]
6926 // property. This is primarily used by ECMA native functions. This
6927 // method sets the class_name field of this function's initial map
6928 // to a given value. It creates an initial map if this function does
6929 // not have one. Note that this method does not copy the initial map
6930 // if it has one already, but simply replaces it with the new value.
6931 // Instances created afterwards will have a map whose [[class]] is
6932 // set to 'value', but there is no guarantees on instances created
6934 void SetInstanceClassName(String* name);
6936 // Returns if this function has been compiled to native code yet.
6937 inline bool is_compiled();
6939 // Returns `false` if formal parameters include rest parameters, optional
6940 // parameters, or destructuring parameters.
6941 // TODO(caitp): make this a flag set during parsing
6942 inline bool has_simple_parameters();
6944 // [next_function_link]: Links functions into various lists, e.g. the list
6945 // of optimized functions hanging off the native_context. The CodeFlusher
6946 // uses this link to chain together flushing candidates. Treated weakly
6947 // by the garbage collector.
6948 DECL_ACCESSORS(next_function_link, Object)
6950 // Prints the name of the function using PrintF.
6951 void PrintName(FILE* out = stdout);
6953 DECLARE_CAST(JSFunction)
6955 // Iterates the objects, including code objects indirectly referenced
6956 // through pointers to the first instruction in the code object.
6957 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
6959 // Dispatched behavior.
6960 DECLARE_PRINTER(JSFunction)
6961 DECLARE_VERIFIER(JSFunction)
6963 // Returns the number of allocated literals.
6964 inline int NumberOfLiterals();
6966 // Used for flags such as --hydrogen-filter.
6967 bool PassesFilter(const char* raw_filter);
6969 // The function's name if it is configured, otherwise shared function info
6971 static Handle<String> GetDebugName(Handle<JSFunction> function);
6973 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
6974 // kSize) is weak and has special handling during garbage collection.
6975 static const int kCodeEntryOffset = JSObject::kHeaderSize;
6976 static const int kPrototypeOrInitialMapOffset =
6977 kCodeEntryOffset + kPointerSize;
6978 static const int kSharedFunctionInfoOffset =
6979 kPrototypeOrInitialMapOffset + kPointerSize;
6980 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
6981 static const int kLiteralsOffset = kContextOffset + kPointerSize;
6982 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
6983 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
6984 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
6986 // Layout of the bound-function binding array.
6987 static const int kBoundFunctionIndex = 0;
6988 static const int kBoundThisIndex = 1;
6989 static const int kBoundArgumentsStartIndex = 2;
6992 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
6996 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
6997 // and the prototype is hidden. JSGlobalProxy always delegates
6998 // property accesses to its prototype if the prototype is not null.
7000 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7002 // Accessing a JSGlobalProxy requires security check.
7004 class JSGlobalProxy : public JSObject {
7006 // [native_context]: the owner native context of this global proxy object.
7007 // It is null value if this object is not used by any context.
7008 DECL_ACCESSORS(native_context, Object)
7010 // [hash]: The hash code property (undefined if not initialized yet).
7011 DECL_ACCESSORS(hash, Object)
7013 DECLARE_CAST(JSGlobalProxy)
7015 inline bool IsDetachedFrom(GlobalObject* global) const;
7017 // Dispatched behavior.
7018 DECLARE_PRINTER(JSGlobalProxy)
7019 DECLARE_VERIFIER(JSGlobalProxy)
7021 // Layout description.
7022 static const int kNativeContextOffset = JSObject::kHeaderSize;
7023 static const int kHashOffset = kNativeContextOffset + kPointerSize;
7024 static const int kSize = kHashOffset + kPointerSize;
7027 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7031 // Common super class for JavaScript global objects and the special
7032 // builtins global objects.
7033 class GlobalObject: public JSObject {
7035 // [builtins]: the object holding the runtime routines written in JS.
7036 DECL_ACCESSORS(builtins, JSBuiltinsObject)
7038 // [native context]: the natives corresponding to this global object.
7039 DECL_ACCESSORS(native_context, Context)
7041 // [global proxy]: the global proxy object of the context
7042 DECL_ACCESSORS(global_proxy, JSObject)
7044 DECLARE_CAST(GlobalObject)
7046 static void InvalidatePropertyCell(Handle<GlobalObject> object,
7048 // Ensure that the global object has a cell for the given property name.
7049 static Handle<PropertyCell> EnsurePropertyCell(Handle<GlobalObject> global,
7052 // Layout description.
7053 static const int kBuiltinsOffset = JSObject::kHeaderSize;
7054 static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7055 static const int kGlobalProxyOffset = kNativeContextOffset + kPointerSize;
7056 static const int kHeaderSize = kGlobalProxyOffset + kPointerSize;
7059 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7063 // JavaScript global object.
7064 class JSGlobalObject: public GlobalObject {
7066 DECLARE_CAST(JSGlobalObject)
7068 inline bool IsDetached();
7070 // Dispatched behavior.
7071 DECLARE_PRINTER(JSGlobalObject)
7072 DECLARE_VERIFIER(JSGlobalObject)
7074 // Layout description.
7075 static const int kSize = GlobalObject::kHeaderSize;
7078 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7082 // Builtins global object which holds the runtime routines written in
7084 class JSBuiltinsObject: public GlobalObject {
7086 // Accessors for the runtime routines written in JavaScript.
7087 inline Object* javascript_builtin(Builtins::JavaScript id);
7088 inline void set_javascript_builtin(Builtins::JavaScript id, Object* value);
7090 DECLARE_CAST(JSBuiltinsObject)
7092 // Dispatched behavior.
7093 DECLARE_PRINTER(JSBuiltinsObject)
7094 DECLARE_VERIFIER(JSBuiltinsObject)
7096 // Layout description. The size of the builtins object includes
7097 // room for two pointers per runtime routine written in javascript
7098 // (function and code object).
7099 static const int kJSBuiltinsCount = Builtins::id_count;
7100 static const int kJSBuiltinsOffset = GlobalObject::kHeaderSize;
7101 static const int kSize =
7102 GlobalObject::kHeaderSize + (kJSBuiltinsCount * kPointerSize);
7104 static int OffsetOfFunctionWithId(Builtins::JavaScript id) {
7105 return kJSBuiltinsOffset + id * kPointerSize;
7109 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7113 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
7114 class JSValue: public JSObject {
7116 // [value]: the object being wrapped.
7117 DECL_ACCESSORS(value, Object)
7119 DECLARE_CAST(JSValue)
7121 // Dispatched behavior.
7122 DECLARE_PRINTER(JSValue)
7123 DECLARE_VERIFIER(JSValue)
7125 // Layout description.
7126 static const int kValueOffset = JSObject::kHeaderSize;
7127 static const int kSize = kValueOffset + kPointerSize;
7130 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
7136 // Representation for JS date objects.
7137 class JSDate: public JSObject {
7139 // If one component is NaN, all of them are, indicating a NaN time value.
7140 // [value]: the time value.
7141 DECL_ACCESSORS(value, Object)
7142 // [year]: caches year. Either undefined, smi, or NaN.
7143 DECL_ACCESSORS(year, Object)
7144 // [month]: caches month. Either undefined, smi, or NaN.
7145 DECL_ACCESSORS(month, Object)
7146 // [day]: caches day. Either undefined, smi, or NaN.
7147 DECL_ACCESSORS(day, Object)
7148 // [weekday]: caches day of week. Either undefined, smi, or NaN.
7149 DECL_ACCESSORS(weekday, Object)
7150 // [hour]: caches hours. Either undefined, smi, or NaN.
7151 DECL_ACCESSORS(hour, Object)
7152 // [min]: caches minutes. Either undefined, smi, or NaN.
7153 DECL_ACCESSORS(min, Object)
7154 // [sec]: caches seconds. Either undefined, smi, or NaN.
7155 DECL_ACCESSORS(sec, Object)
7156 // [cache stamp]: sample of the date cache stamp at the
7157 // moment when chached fields were cached.
7158 DECL_ACCESSORS(cache_stamp, Object)
7160 DECLARE_CAST(JSDate)
7162 // Returns the date field with the specified index.
7163 // See FieldIndex for the list of date fields.
7164 static Object* GetField(Object* date, Smi* index);
7166 void SetValue(Object* value, bool is_value_nan);
7169 // Dispatched behavior.
7170 DECLARE_PRINTER(JSDate)
7171 DECLARE_VERIFIER(JSDate)
7173 // The order is important. It must be kept in sync with date macros
7184 kFirstUncachedField,
7185 kMillisecond = kFirstUncachedField,
7189 kYearUTC = kFirstUTCField,
7202 // Layout description.
7203 static const int kValueOffset = JSObject::kHeaderSize;
7204 static const int kYearOffset = kValueOffset + kPointerSize;
7205 static const int kMonthOffset = kYearOffset + kPointerSize;
7206 static const int kDayOffset = kMonthOffset + kPointerSize;
7207 static const int kWeekdayOffset = kDayOffset + kPointerSize;
7208 static const int kHourOffset = kWeekdayOffset + kPointerSize;
7209 static const int kMinOffset = kHourOffset + kPointerSize;
7210 static const int kSecOffset = kMinOffset + kPointerSize;
7211 static const int kCacheStampOffset = kSecOffset + kPointerSize;
7212 static const int kSize = kCacheStampOffset + kPointerSize;
7215 inline Object* DoGetField(FieldIndex index);
7217 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
7219 // Computes and caches the cacheable fields of the date.
7220 inline void SetCachedFields(int64_t local_time_ms, DateCache* date_cache);
7223 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
7227 // Representation of message objects used for error reporting through
7228 // the API. The messages are formatted in JavaScript so this object is
7229 // a real JavaScript object. The information used for formatting the
7230 // error messages are not directly accessible from JavaScript to
7231 // prevent leaking information to user code called during error
7233 class JSMessageObject: public JSObject {
7235 // [type]: the type of error message.
7236 inline int type() const;
7237 inline void set_type(int value);
7239 // [arguments]: the arguments for formatting the error message.
7240 DECL_ACCESSORS(argument, Object)
7242 // [script]: the script from which the error message originated.
7243 DECL_ACCESSORS(script, Object)
7245 // [stack_frames]: an array of stack frames for this error object.
7246 DECL_ACCESSORS(stack_frames, Object)
7248 // [start_position]: the start position in the script for the error message.
7249 inline int start_position() const;
7250 inline void set_start_position(int value);
7252 // [end_position]: the end position in the script for the error message.
7253 inline int end_position() const;
7254 inline void set_end_position(int value);
7256 DECLARE_CAST(JSMessageObject)
7258 // Dispatched behavior.
7259 DECLARE_PRINTER(JSMessageObject)
7260 DECLARE_VERIFIER(JSMessageObject)
7262 // Layout description.
7263 static const int kTypeOffset = JSObject::kHeaderSize;
7264 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
7265 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
7266 static const int kStackFramesOffset = kScriptOffset + kPointerSize;
7267 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
7268 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
7269 static const int kSize = kEndPositionOffset + kPointerSize;
7271 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
7272 kStackFramesOffset + kPointerSize,
7273 kSize> BodyDescriptor;
7277 // Regular expressions
7278 // The regular expression holds a single reference to a FixedArray in
7279 // the kDataOffset field.
7280 // The FixedArray contains the following data:
7281 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
7282 // - reference to the original source string
7283 // - reference to the original flag string
7284 // If it is an atom regexp
7285 // - a reference to a literal string to search for
7286 // If it is an irregexp regexp:
7287 // - a reference to code for Latin1 inputs (bytecode or compiled), or a smi
7288 // used for tracking the last usage (used for code flushing).
7289 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
7290 // used for tracking the last usage (used for code flushing)..
7291 // - max number of registers used by irregexp implementations.
7292 // - number of capture registers (output values) of the regexp.
7293 class JSRegExp: public JSObject {
7296 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
7297 // ATOM: A simple string to match against using an indexOf operation.
7298 // IRREGEXP: Compiled with Irregexp.
7299 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
7300 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
7307 UNICODE_ESCAPES = 16
7312 explicit Flags(uint32_t value) : value_(value) { }
7313 bool is_global() { return (value_ & GLOBAL) != 0; }
7314 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
7315 bool is_multiline() { return (value_ & MULTILINE) != 0; }
7316 bool is_sticky() { return (value_ & STICKY) != 0; }
7317 bool is_unicode() { return (value_ & UNICODE_ESCAPES) != 0; }
7318 uint32_t value() { return value_; }
7323 DECL_ACCESSORS(data, Object)
7325 inline Type TypeTag();
7326 inline int CaptureCount();
7327 inline Flags GetFlags();
7328 inline String* Pattern();
7329 inline Object* DataAt(int index);
7330 // Set implementation data after the object has been prepared.
7331 inline void SetDataAt(int index, Object* value);
7333 static int code_index(bool is_latin1) {
7335 return kIrregexpLatin1CodeIndex;
7337 return kIrregexpUC16CodeIndex;
7341 static int saved_code_index(bool is_latin1) {
7343 return kIrregexpLatin1CodeSavedIndex;
7345 return kIrregexpUC16CodeSavedIndex;
7349 DECLARE_CAST(JSRegExp)
7351 // Dispatched behavior.
7352 DECLARE_VERIFIER(JSRegExp)
7354 static const int kDataOffset = JSObject::kHeaderSize;
7355 static const int kSize = kDataOffset + kPointerSize;
7357 // Indices in the data array.
7358 static const int kTagIndex = 0;
7359 static const int kSourceIndex = kTagIndex + 1;
7360 static const int kFlagsIndex = kSourceIndex + 1;
7361 static const int kDataIndex = kFlagsIndex + 1;
7362 // The data fields are used in different ways depending on the
7363 // value of the tag.
7364 // Atom regexps (literal strings).
7365 static const int kAtomPatternIndex = kDataIndex;
7367 static const int kAtomDataSize = kAtomPatternIndex + 1;
7369 // Irregexp compiled code or bytecode for Latin1. If compilation
7370 // fails, this fields hold an exception object that should be
7371 // thrown if the regexp is used again.
7372 static const int kIrregexpLatin1CodeIndex = kDataIndex;
7373 // Irregexp compiled code or bytecode for UC16. If compilation
7374 // fails, this fields hold an exception object that should be
7375 // thrown if the regexp is used again.
7376 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
7378 // Saved instance of Irregexp compiled code or bytecode for Latin1 that
7379 // is a potential candidate for flushing.
7380 static const int kIrregexpLatin1CodeSavedIndex = kDataIndex + 2;
7381 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
7382 // a potential candidate for flushing.
7383 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
7385 // Maximal number of registers used by either Latin1 or UC16.
7386 // Only used to check that there is enough stack space
7387 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
7388 // Number of captures in the compiled regexp.
7389 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
7391 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
7393 // Offsets directly into the data fixed array.
7394 static const int kDataTagOffset =
7395 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
7396 static const int kDataOneByteCodeOffset =
7397 FixedArray::kHeaderSize + kIrregexpLatin1CodeIndex * kPointerSize;
7398 static const int kDataUC16CodeOffset =
7399 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
7400 static const int kIrregexpCaptureCountOffset =
7401 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
7403 // In-object fields.
7404 static const int kSourceFieldIndex = 0;
7405 static const int kGlobalFieldIndex = 1;
7406 static const int kIgnoreCaseFieldIndex = 2;
7407 static const int kMultilineFieldIndex = 3;
7408 static const int kLastIndexFieldIndex = 4;
7409 static const int kInObjectFieldCount = 5;
7411 // The uninitialized value for a regexp code object.
7412 static const int kUninitializedValue = -1;
7414 // The compilation error value for the regexp code object. The real error
7415 // object is in the saved code field.
7416 static const int kCompilationErrorValue = -2;
7418 // When we store the sweep generation at which we moved the code from the
7419 // code index to the saved code index we mask it of to be in the [0:255]
7421 static const int kCodeAgeMask = 0xff;
7425 class CompilationCacheShape : public BaseShape<HashTableKey*> {
7427 static inline bool IsMatch(HashTableKey* key, Object* value) {
7428 return key->IsMatch(value);
7431 static inline uint32_t Hash(HashTableKey* key) {
7435 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7436 return key->HashForObject(object);
7439 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7441 static const int kPrefixSize = 0;
7442 static const int kEntrySize = 2;
7446 // This cache is used in two different variants. For regexp caching, it simply
7447 // maps identifying info of the regexp to the cached regexp object. Scripts and
7448 // eval code only gets cached after a second probe for the code object. To do
7449 // so, on first "put" only a hash identifying the source is entered into the
7450 // cache, mapping it to a lifetime count of the hash. On each call to Age all
7451 // such lifetimes get reduced, and removed once they reach zero. If a second put
7452 // is called while such a hash is live in the cache, the hash gets replaced by
7453 // an actual cache entry. Age also removes stale live entries from the cache.
7454 // Such entries are identified by SharedFunctionInfos pointing to either the
7455 // recompilation stub, or to "old" code. This avoids memory leaks due to
7456 // premature caching of scripts and eval strings that are never needed later.
7457 class CompilationCacheTable: public HashTable<CompilationCacheTable,
7458 CompilationCacheShape,
7461 // Find cached value for a string key, otherwise return null.
7462 Handle<Object> Lookup(
7463 Handle<String> src, Handle<Context> context, LanguageMode language_mode);
7464 Handle<Object> LookupEval(
7465 Handle<String> src, Handle<SharedFunctionInfo> shared,
7466 LanguageMode language_mode, int scope_position);
7467 Handle<Object> LookupRegExp(Handle<String> source, JSRegExp::Flags flags);
7468 static Handle<CompilationCacheTable> Put(
7469 Handle<CompilationCacheTable> cache, Handle<String> src,
7470 Handle<Context> context, LanguageMode language_mode,
7471 Handle<Object> value);
7472 static Handle<CompilationCacheTable> PutEval(
7473 Handle<CompilationCacheTable> cache, Handle<String> src,
7474 Handle<SharedFunctionInfo> context, Handle<SharedFunctionInfo> value,
7475 int scope_position);
7476 static Handle<CompilationCacheTable> PutRegExp(
7477 Handle<CompilationCacheTable> cache, Handle<String> src,
7478 JSRegExp::Flags flags, Handle<FixedArray> value);
7479 void Remove(Object* value);
7481 static const int kHashGenerations = 10;
7483 DECLARE_CAST(CompilationCacheTable)
7486 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
7490 class CodeCache: public Struct {
7492 DECL_ACCESSORS(default_cache, FixedArray)
7493 DECL_ACCESSORS(normal_type_cache, Object)
7495 // Add the code object to the cache.
7497 Handle<CodeCache> cache, Handle<Name> name, Handle<Code> code);
7499 // Lookup code object in the cache. Returns code object if found and undefined
7501 Object* Lookup(Name* name, Code::Flags flags);
7503 // Get the internal index of a code object in the cache. Returns -1 if the
7504 // code object is not in that cache. This index can be used to later call
7505 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
7507 int GetIndex(Object* name, Code* code);
7509 // Remove an object from the cache with the provided internal index.
7510 void RemoveByIndex(Object* name, Code* code, int index);
7512 DECLARE_CAST(CodeCache)
7514 // Dispatched behavior.
7515 DECLARE_PRINTER(CodeCache)
7516 DECLARE_VERIFIER(CodeCache)
7518 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
7519 static const int kNormalTypeCacheOffset =
7520 kDefaultCacheOffset + kPointerSize;
7521 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
7524 static void UpdateDefaultCache(
7525 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7526 static void UpdateNormalTypeCache(
7527 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7528 Object* LookupDefaultCache(Name* name, Code::Flags flags);
7529 Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
7531 // Code cache layout of the default cache. Elements are alternating name and
7532 // code objects for non normal load/store/call IC's.
7533 static const int kCodeCacheEntrySize = 2;
7534 static const int kCodeCacheEntryNameOffset = 0;
7535 static const int kCodeCacheEntryCodeOffset = 1;
7537 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
7541 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
7543 static inline bool IsMatch(HashTableKey* key, Object* value) {
7544 return key->IsMatch(value);
7547 static inline uint32_t Hash(HashTableKey* key) {
7551 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7552 return key->HashForObject(object);
7555 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7557 static const int kPrefixSize = 0;
7558 static const int kEntrySize = 2;
7562 class CodeCacheHashTable: public HashTable<CodeCacheHashTable,
7563 CodeCacheHashTableShape,
7566 Object* Lookup(Name* name, Code::Flags flags);
7567 static Handle<CodeCacheHashTable> Put(
7568 Handle<CodeCacheHashTable> table,
7572 int GetIndex(Name* name, Code::Flags flags);
7573 void RemoveByIndex(int index);
7575 DECLARE_CAST(CodeCacheHashTable)
7577 // Initial size of the fixed array backing the hash table.
7578 static const int kInitialSize = 64;
7581 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
7585 class PolymorphicCodeCache: public Struct {
7587 DECL_ACCESSORS(cache, Object)
7589 static void Update(Handle<PolymorphicCodeCache> cache,
7590 MapHandleList* maps,
7595 // Returns an undefined value if the entry is not found.
7596 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
7598 DECLARE_CAST(PolymorphicCodeCache)
7600 // Dispatched behavior.
7601 DECLARE_PRINTER(PolymorphicCodeCache)
7602 DECLARE_VERIFIER(PolymorphicCodeCache)
7604 static const int kCacheOffset = HeapObject::kHeaderSize;
7605 static const int kSize = kCacheOffset + kPointerSize;
7608 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
7612 class PolymorphicCodeCacheHashTable
7613 : public HashTable<PolymorphicCodeCacheHashTable,
7614 CodeCacheHashTableShape,
7617 Object* Lookup(MapHandleList* maps, int code_kind);
7619 static Handle<PolymorphicCodeCacheHashTable> Put(
7620 Handle<PolymorphicCodeCacheHashTable> hash_table,
7621 MapHandleList* maps,
7625 DECLARE_CAST(PolymorphicCodeCacheHashTable)
7627 static const int kInitialSize = 64;
7629 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
7633 class TypeFeedbackInfo: public Struct {
7635 inline int ic_total_count();
7636 inline void set_ic_total_count(int count);
7638 inline int ic_with_type_info_count();
7639 inline void change_ic_with_type_info_count(int delta);
7641 inline int ic_generic_count();
7642 inline void change_ic_generic_count(int delta);
7644 inline void initialize_storage();
7646 inline void change_own_type_change_checksum();
7647 inline int own_type_change_checksum();
7649 inline void set_inlined_type_change_checksum(int checksum);
7650 inline bool matches_inlined_type_change_checksum(int checksum);
7652 DECLARE_CAST(TypeFeedbackInfo)
7654 // Dispatched behavior.
7655 DECLARE_PRINTER(TypeFeedbackInfo)
7656 DECLARE_VERIFIER(TypeFeedbackInfo)
7658 static const int kStorage1Offset = HeapObject::kHeaderSize;
7659 static const int kStorage2Offset = kStorage1Offset + kPointerSize;
7660 static const int kStorage3Offset = kStorage2Offset + kPointerSize;
7661 static const int kSize = kStorage3Offset + kPointerSize;
7664 static const int kTypeChangeChecksumBits = 7;
7666 class ICTotalCountField: public BitField<int, 0,
7667 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7668 class OwnTypeChangeChecksum: public BitField<int,
7669 kSmiValueSize - kTypeChangeChecksumBits,
7670 kTypeChangeChecksumBits> {}; // NOLINT
7671 class ICsWithTypeInfoCountField: public BitField<int, 0,
7672 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7673 class InlinedTypeChangeChecksum: public BitField<int,
7674 kSmiValueSize - kTypeChangeChecksumBits,
7675 kTypeChangeChecksumBits> {}; // NOLINT
7677 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
7681 enum AllocationSiteMode {
7682 DONT_TRACK_ALLOCATION_SITE,
7683 TRACK_ALLOCATION_SITE,
7684 LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
7688 class AllocationSite: public Struct {
7690 static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
7691 static const double kPretenureRatio;
7692 static const int kPretenureMinimumCreated = 100;
7694 // Values for pretenure decision field.
7695 enum PretenureDecision {
7701 kLastPretenureDecisionValue = kZombie
7704 const char* PretenureDecisionName(PretenureDecision decision);
7706 DECL_ACCESSORS(transition_info, Object)
7707 // nested_site threads a list of sites that represent nested literals
7708 // walked in a particular order. So [[1, 2], 1, 2] will have one
7709 // nested_site, but [[1, 2], 3, [4]] will have a list of two.
7710 DECL_ACCESSORS(nested_site, Object)
7711 DECL_ACCESSORS(pretenure_data, Smi)
7712 DECL_ACCESSORS(pretenure_create_count, Smi)
7713 DECL_ACCESSORS(dependent_code, DependentCode)
7714 DECL_ACCESSORS(weak_next, Object)
7716 inline void Initialize();
7718 // This method is expensive, it should only be called for reporting.
7719 bool IsNestedSite();
7721 // transition_info bitfields, for constructed array transition info.
7722 class ElementsKindBits: public BitField<ElementsKind, 0, 15> {};
7723 class UnusedBits: public BitField<int, 15, 14> {};
7724 class DoNotInlineBit: public BitField<bool, 29, 1> {};
7726 // Bitfields for pretenure_data
7727 class MementoFoundCountBits: public BitField<int, 0, 26> {};
7728 class PretenureDecisionBits: public BitField<PretenureDecision, 26, 3> {};
7729 class DeoptDependentCodeBit: public BitField<bool, 29, 1> {};
7730 STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
7732 // Increments the mementos found counter and returns true when the first
7733 // memento was found for a given allocation site.
7734 inline bool IncrementMementoFoundCount();
7736 inline void IncrementMementoCreateCount();
7738 PretenureFlag GetPretenureMode();
7740 void ResetPretenureDecision();
7742 inline PretenureDecision pretenure_decision();
7743 inline void set_pretenure_decision(PretenureDecision decision);
7745 inline bool deopt_dependent_code();
7746 inline void set_deopt_dependent_code(bool deopt);
7748 inline int memento_found_count();
7749 inline void set_memento_found_count(int count);
7751 inline int memento_create_count();
7752 inline void set_memento_create_count(int count);
7754 // The pretenuring decision is made during gc, and the zombie state allows
7755 // us to recognize when an allocation site is just being kept alive because
7756 // a later traversal of new space may discover AllocationMementos that point
7757 // to this AllocationSite.
7758 inline bool IsZombie();
7760 inline bool IsMaybeTenure();
7762 inline void MarkZombie();
7764 inline bool MakePretenureDecision(PretenureDecision current_decision,
7766 bool maximum_size_scavenge);
7768 inline bool DigestPretenuringFeedback(bool maximum_size_scavenge);
7770 inline ElementsKind GetElementsKind();
7771 inline void SetElementsKind(ElementsKind kind);
7773 inline bool CanInlineCall();
7774 inline void SetDoNotInlineCall();
7776 inline bool SitePointsToLiteral();
7778 static void DigestTransitionFeedback(Handle<AllocationSite> site,
7779 ElementsKind to_kind);
7781 DECLARE_PRINTER(AllocationSite)
7782 DECLARE_VERIFIER(AllocationSite)
7784 DECLARE_CAST(AllocationSite)
7785 static inline AllocationSiteMode GetMode(
7786 ElementsKind boilerplate_elements_kind);
7787 static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
7788 static inline bool CanTrack(InstanceType type);
7790 static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
7791 static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
7792 static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
7793 static const int kPretenureCreateCountOffset =
7794 kPretenureDataOffset + kPointerSize;
7795 static const int kDependentCodeOffset =
7796 kPretenureCreateCountOffset + kPointerSize;
7797 static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
7798 static const int kSize = kWeakNextOffset + kPointerSize;
7800 // During mark compact we need to take special care for the dependent code
7802 static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
7803 static const int kPointerFieldsEndOffset = kWeakNextOffset;
7805 // For other visitors, use the fixed body descriptor below.
7806 typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
7807 kDependentCodeOffset + kPointerSize,
7808 kSize> BodyDescriptor;
7811 inline bool PretenuringDecisionMade();
7813 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
7817 class AllocationMemento: public Struct {
7819 static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
7820 static const int kSize = kAllocationSiteOffset + kPointerSize;
7822 DECL_ACCESSORS(allocation_site, Object)
7824 inline bool IsValid();
7825 inline AllocationSite* GetAllocationSite();
7827 DECLARE_PRINTER(AllocationMemento)
7828 DECLARE_VERIFIER(AllocationMemento)
7830 DECLARE_CAST(AllocationMemento)
7833 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
7837 // Representation of a slow alias as part of a sloppy arguments objects.
7838 // For fast aliases (if HasSloppyArgumentsElements()):
7839 // - the parameter map contains an index into the context
7840 // - all attributes of the element have default values
7841 // For slow aliases (if HasDictionaryArgumentsElements()):
7842 // - the parameter map contains no fast alias mapping (i.e. the hole)
7843 // - this struct (in the slow backing store) contains an index into the context
7844 // - all attributes are available as part if the property details
7845 class AliasedArgumentsEntry: public Struct {
7847 inline int aliased_context_slot() const;
7848 inline void set_aliased_context_slot(int count);
7850 DECLARE_CAST(AliasedArgumentsEntry)
7852 // Dispatched behavior.
7853 DECLARE_PRINTER(AliasedArgumentsEntry)
7854 DECLARE_VERIFIER(AliasedArgumentsEntry)
7856 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
7857 static const int kSize = kAliasedContextSlot + kPointerSize;
7860 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
7864 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
7865 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
7868 class StringHasher {
7870 explicit inline StringHasher(int length, uint32_t seed);
7872 template <typename schar>
7873 static inline uint32_t HashSequentialString(const schar* chars,
7877 // Reads all the data, even for long strings and computes the utf16 length.
7878 static uint32_t ComputeUtf8Hash(Vector<const char> chars,
7880 int* utf16_length_out);
7882 // Calculated hash value for a string consisting of 1 to
7883 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
7884 // value is represented decimal value.
7885 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
7887 // No string is allowed to have a hash of zero. That value is reserved
7888 // for internal properties. If the hash calculation yields zero then we
7890 static const int kZeroHash = 27;
7892 // Reusable parts of the hashing algorithm.
7893 INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
7894 INLINE(static uint32_t GetHashCore(uint32_t running_hash));
7895 INLINE(static uint32_t ComputeRunningHash(uint32_t running_hash,
7896 const uc16* chars, int length));
7897 INLINE(static uint32_t ComputeRunningHashOneByte(uint32_t running_hash,
7902 // Returns the value to store in the hash field of a string with
7903 // the given length and contents.
7904 uint32_t GetHashField();
7905 // Returns true if the hash of this string can be computed without
7906 // looking at the contents.
7907 inline bool has_trivial_hash();
7908 // Adds a block of characters to the hash.
7909 template<typename Char>
7910 inline void AddCharacters(const Char* chars, int len);
7913 // Add a character to the hash.
7914 inline void AddCharacter(uint16_t c);
7915 // Update index. Returns true if string is still an index.
7916 inline bool UpdateIndex(uint16_t c);
7919 uint32_t raw_running_hash_;
7920 uint32_t array_index_;
7921 bool is_array_index_;
7922 bool is_first_char_;
7923 DISALLOW_COPY_AND_ASSIGN(StringHasher);
7927 class IteratingStringHasher : public StringHasher {
7929 static inline uint32_t Hash(String* string, uint32_t seed);
7930 inline void VisitOneByteString(const uint8_t* chars, int length);
7931 inline void VisitTwoByteString(const uint16_t* chars, int length);
7934 inline IteratingStringHasher(int len, uint32_t seed);
7935 void VisitConsString(ConsString* cons_string);
7936 DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher);
7940 // The characteristics of a string are stored in its map. Retrieving these
7941 // few bits of information is moderately expensive, involving two memory
7942 // loads where the second is dependent on the first. To improve efficiency
7943 // the shape of the string is given its own class so that it can be retrieved
7944 // once and used for several string operations. A StringShape is small enough
7945 // to be passed by value and is immutable, but be aware that flattening a
7946 // string can potentially alter its shape. Also be aware that a GC caused by
7947 // something else can alter the shape of a string due to ConsString
7948 // shortcutting. Keeping these restrictions in mind has proven to be error-
7949 // prone and so we no longer put StringShapes in variables unless there is a
7950 // concrete performance benefit at that particular point in the code.
7951 class StringShape BASE_EMBEDDED {
7953 inline explicit StringShape(const String* s);
7954 inline explicit StringShape(Map* s);
7955 inline explicit StringShape(InstanceType t);
7956 inline bool IsSequential();
7957 inline bool IsExternal();
7958 inline bool IsCons();
7959 inline bool IsSliced();
7960 inline bool IsIndirect();
7961 inline bool IsExternalOneByte();
7962 inline bool IsExternalTwoByte();
7963 inline bool IsSequentialOneByte();
7964 inline bool IsSequentialTwoByte();
7965 inline bool IsInternalized();
7966 inline StringRepresentationTag representation_tag();
7967 inline uint32_t encoding_tag();
7968 inline uint32_t full_representation_tag();
7969 inline uint32_t size_tag();
7971 inline uint32_t type() { return type_; }
7972 inline void invalidate() { valid_ = false; }
7973 inline bool valid() { return valid_; }
7975 inline void invalidate() { }
7981 inline void set_valid() { valid_ = true; }
7984 inline void set_valid() { }
7989 // The Name abstract class captures anything that can be used as a property
7990 // name, i.e., strings and symbols. All names store a hash value.
7991 class Name: public HeapObject {
7993 // Get and set the hash field of the name.
7994 inline uint32_t hash_field();
7995 inline void set_hash_field(uint32_t value);
7997 // Tells whether the hash code has been computed.
7998 inline bool HasHashCode();
8000 // Returns a hash value used for the property table
8001 inline uint32_t Hash();
8003 // Equality operations.
8004 inline bool Equals(Name* other);
8005 inline static bool Equals(Handle<Name> one, Handle<Name> two);
8008 inline bool AsArrayIndex(uint32_t* index);
8010 // If the name is private, it can only name own properties.
8011 inline bool IsPrivate();
8013 // If the name is a non-flat string, this method returns a flat version of the
8014 // string. Otherwise it'll just return the input.
8015 static inline Handle<Name> Flatten(Handle<Name> name,
8016 PretenureFlag pretenure = NOT_TENURED);
8020 DECLARE_PRINTER(Name)
8022 void NameShortPrint();
8023 int NameShortPrint(Vector<char> str);
8026 // Layout description.
8027 static const int kHashFieldSlot = HeapObject::kHeaderSize;
8028 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
8029 static const int kHashFieldOffset = kHashFieldSlot;
8031 static const int kHashFieldOffset = kHashFieldSlot + kIntSize;
8033 static const int kSize = kHashFieldSlot + kPointerSize;
8035 // Mask constant for checking if a name has a computed hash code
8036 // and if it is a string that is an array index. The least significant bit
8037 // indicates whether a hash code has been computed. If the hash code has
8038 // been computed the 2nd bit tells whether the string can be used as an
8040 static const int kHashNotComputedMask = 1;
8041 static const int kIsNotArrayIndexMask = 1 << 1;
8042 static const int kNofHashBitFields = 2;
8044 // Shift constant retrieving hash code from hash field.
8045 static const int kHashShift = kNofHashBitFields;
8047 // Only these bits are relevant in the hash, since the top two are shifted
8049 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8051 // Array index strings this short can keep their index in the hash field.
8052 static const int kMaxCachedArrayIndexLength = 7;
8054 // For strings which are array indexes the hash value has the string length
8055 // mixed into the hash, mainly to avoid a hash value of zero which would be
8056 // the case for the string '0'. 24 bits are used for the array index value.
8057 static const int kArrayIndexValueBits = 24;
8058 static const int kArrayIndexLengthBits =
8059 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8061 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8063 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8064 kArrayIndexValueBits> {}; // NOLINT
8065 class ArrayIndexLengthBits : public BitField<unsigned int,
8066 kNofHashBitFields + kArrayIndexValueBits,
8067 kArrayIndexLengthBits> {}; // NOLINT
8069 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8070 // could use a mask to test if the length of string is less than or equal to
8071 // kMaxCachedArrayIndexLength.
8072 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8074 static const unsigned int kContainsCachedArrayIndexMask =
8075 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8076 << ArrayIndexLengthBits::kShift) |
8077 kIsNotArrayIndexMask;
8079 // Value of empty hash field indicating that the hash is not computed.
8080 static const int kEmptyHashField =
8081 kIsNotArrayIndexMask | kHashNotComputedMask;
8084 static inline bool IsHashFieldComputed(uint32_t field);
8087 DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8092 class Symbol: public Name {
8094 // [name]: The print name of a symbol, or undefined if none.
8095 DECL_ACCESSORS(name, Object)
8097 DECL_ACCESSORS(flags, Smi)
8099 // [is_private]: Whether this is a private symbol. Private symbols can only
8100 // be used to designate own properties of objects.
8101 DECL_BOOLEAN_ACCESSORS(is_private)
8103 DECLARE_CAST(Symbol)
8105 // Dispatched behavior.
8106 DECLARE_PRINTER(Symbol)
8107 DECLARE_VERIFIER(Symbol)
8109 // Layout description.
8110 static const int kNameOffset = Name::kSize;
8111 static const int kFlagsOffset = kNameOffset + kPointerSize;
8112 static const int kSize = kFlagsOffset + kPointerSize;
8114 typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
8116 void SymbolShortPrint(std::ostream& os);
8119 static const int kPrivateBit = 0;
8121 const char* PrivateSymbolToName() const;
8124 friend class Name; // For PrivateSymbolToName.
8127 DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
8133 // The String abstract class captures JavaScript string values:
8136 // 4.3.16 String Value
8137 // A string value is a member of the type String and is a finite
8138 // ordered sequence of zero or more 16-bit unsigned integer values.
8140 // All string values have a length field.
8141 class String: public Name {
8143 enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
8145 // Array index strings this short can keep their index in the hash field.
8146 static const int kMaxCachedArrayIndexLength = 7;
8148 // For strings which are array indexes the hash value has the string length
8149 // mixed into the hash, mainly to avoid a hash value of zero which would be
8150 // the case for the string '0'. 24 bits are used for the array index value.
8151 static const int kArrayIndexValueBits = 24;
8152 static const int kArrayIndexLengthBits =
8153 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8155 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8157 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8158 kArrayIndexValueBits> {}; // NOLINT
8159 class ArrayIndexLengthBits : public BitField<unsigned int,
8160 kNofHashBitFields + kArrayIndexValueBits,
8161 kArrayIndexLengthBits> {}; // NOLINT
8163 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8164 // could use a mask to test if the length of string is less than or equal to
8165 // kMaxCachedArrayIndexLength.
8166 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8168 static const unsigned int kContainsCachedArrayIndexMask =
8169 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8170 << ArrayIndexLengthBits::kShift) |
8171 kIsNotArrayIndexMask;
8173 class SubStringRange {
8175 explicit inline SubStringRange(String* string, int first = 0,
8178 inline iterator begin();
8179 inline iterator end();
8187 // Representation of the flat content of a String.
8188 // A non-flat string doesn't have flat content.
8189 // A flat string has content that's encoded as a sequence of either
8190 // one-byte chars or two-byte UC16.
8191 // Returned by String::GetFlatContent().
8194 // Returns true if the string is flat and this structure contains content.
8195 bool IsFlat() { return state_ != NON_FLAT; }
8196 // Returns true if the structure contains one-byte content.
8197 bool IsOneByte() { return state_ == ONE_BYTE; }
8198 // Returns true if the structure contains two-byte content.
8199 bool IsTwoByte() { return state_ == TWO_BYTE; }
8201 // Return the one byte content of the string. Only use if IsOneByte()
8203 Vector<const uint8_t> ToOneByteVector() {
8204 DCHECK_EQ(ONE_BYTE, state_);
8205 return Vector<const uint8_t>(onebyte_start, length_);
8207 // Return the two-byte content of the string. Only use if IsTwoByte()
8209 Vector<const uc16> ToUC16Vector() {
8210 DCHECK_EQ(TWO_BYTE, state_);
8211 return Vector<const uc16>(twobyte_start, length_);
8215 DCHECK(i < length_);
8216 DCHECK(state_ != NON_FLAT);
8217 if (state_ == ONE_BYTE) return onebyte_start[i];
8218 return twobyte_start[i];
8221 bool UsesSameString(const FlatContent& other) const {
8222 return onebyte_start == other.onebyte_start;
8226 enum State { NON_FLAT, ONE_BYTE, TWO_BYTE };
8228 // Constructors only used by String::GetFlatContent().
8229 explicit FlatContent(const uint8_t* start, int length)
8230 : onebyte_start(start), length_(length), state_(ONE_BYTE) {}
8231 explicit FlatContent(const uc16* start, int length)
8232 : twobyte_start(start), length_(length), state_(TWO_BYTE) { }
8233 FlatContent() : onebyte_start(NULL), length_(0), state_(NON_FLAT) { }
8236 const uint8_t* onebyte_start;
8237 const uc16* twobyte_start;
8242 friend class String;
8243 friend class IterableSubString;
8246 template <typename Char>
8247 INLINE(Vector<const Char> GetCharVector());
8249 // Get and set the length of the string.
8250 inline int length() const;
8251 inline void set_length(int value);
8253 // Get and set the length of the string using acquire loads and release
8255 inline int synchronized_length() const;
8256 inline void synchronized_set_length(int value);
8258 // Returns whether this string has only one-byte chars, i.e. all of them can
8259 // be one-byte encoded. This might be the case even if the string is
8260 // two-byte. Such strings may appear when the embedder prefers
8261 // two-byte external representations even for one-byte data.
8262 inline bool IsOneByteRepresentation() const;
8263 inline bool IsTwoByteRepresentation() const;
8265 // Cons and slices have an encoding flag that may not represent the actual
8266 // encoding of the underlying string. This is taken into account here.
8267 // Requires: this->IsFlat()
8268 inline bool IsOneByteRepresentationUnderneath();
8269 inline bool IsTwoByteRepresentationUnderneath();
8271 // NOTE: this should be considered only a hint. False negatives are
8273 inline bool HasOnlyOneByteChars();
8275 // Get and set individual two byte chars in the string.
8276 inline void Set(int index, uint16_t value);
8277 // Get individual two byte char in the string. Repeated calls
8278 // to this method are not efficient unless the string is flat.
8279 INLINE(uint16_t Get(int index));
8281 // Flattens the string. Checks first inline to see if it is
8282 // necessary. Does nothing if the string is not a cons string.
8283 // Flattening allocates a sequential string with the same data as
8284 // the given string and mutates the cons string to a degenerate
8285 // form, where the first component is the new sequential string and
8286 // the second component is the empty string. If allocation fails,
8287 // this function returns a failure. If flattening succeeds, this
8288 // function returns the sequential string that is now the first
8289 // component of the cons string.
8291 // Degenerate cons strings are handled specially by the garbage
8292 // collector (see IsShortcutCandidate).
8294 static inline Handle<String> Flatten(Handle<String> string,
8295 PretenureFlag pretenure = NOT_TENURED);
8297 // Tries to return the content of a flat string as a structure holding either
8298 // a flat vector of char or of uc16.
8299 // If the string isn't flat, and therefore doesn't have flat content, the
8300 // returned structure will report so, and can't provide a vector of either
8302 FlatContent GetFlatContent();
8304 // Returns the parent of a sliced string or first part of a flat cons string.
8305 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
8306 inline String* GetUnderlying();
8308 // String equality operations.
8309 inline bool Equals(String* other);
8310 inline static bool Equals(Handle<String> one, Handle<String> two);
8311 bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
8312 bool IsOneByteEqualTo(Vector<const uint8_t> str);
8313 bool IsTwoByteEqualTo(Vector<const uc16> str);
8315 // Return a UTF8 representation of the string. The string is null
8316 // terminated but may optionally contain nulls. Length is returned
8317 // in length_output if length_output is not a null pointer The string
8318 // should be nearly flat, otherwise the performance of this method may
8319 // be very slow (quadratic in the length). Setting robustness_flag to
8320 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8321 // handles unexpected data without causing assert failures and it does not
8322 // do any heap allocations. This is useful when printing stack traces.
8323 base::SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
8324 RobustnessFlag robustness_flag,
8325 int offset, int length,
8326 int* length_output = 0);
8327 base::SmartArrayPointer<char> ToCString(
8328 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
8329 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
8330 int* length_output = 0);
8332 // Return a 16 bit Unicode representation of the string.
8333 // The string should be nearly flat, otherwise the performance of
8334 // of this method may be very bad. Setting robustness_flag to
8335 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8336 // handles unexpected data without causing assert failures and it does not
8337 // do any heap allocations. This is useful when printing stack traces.
8338 base::SmartArrayPointer<uc16> ToWideCString(
8339 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
8341 bool ComputeArrayIndex(uint32_t* index);
8344 bool MakeExternal(v8::String::ExternalStringResource* resource);
8345 bool MakeExternal(v8::String::ExternalOneByteStringResource* resource);
8348 inline bool AsArrayIndex(uint32_t* index);
8350 DECLARE_CAST(String)
8352 void PrintOn(FILE* out);
8354 // For use during stack traces. Performs rudimentary sanity check.
8357 // Dispatched behavior.
8358 void StringShortPrint(StringStream* accumulator);
8359 void PrintUC16(std::ostream& os, int start = 0, int end = -1); // NOLINT
8360 #if defined(DEBUG) || defined(OBJECT_PRINT)
8361 char* ToAsciiArray();
8363 DECLARE_PRINTER(String)
8364 DECLARE_VERIFIER(String)
8366 inline bool IsFlat();
8368 // Layout description.
8369 static const int kLengthOffset = Name::kSize;
8370 static const int kSize = kLengthOffset + kPointerSize;
8372 // Maximum number of characters to consider when trying to convert a string
8373 // value into an array index.
8374 static const int kMaxArrayIndexSize = 10;
8375 STATIC_ASSERT(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
8378 static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
8379 static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
8380 static const int kMaxUtf16CodeUnit = 0xffff;
8381 static const uint32_t kMaxUtf16CodeUnitU = kMaxUtf16CodeUnit;
8383 // Value of hash field containing computed hash equal to zero.
8384 static const int kEmptyStringHash = kIsNotArrayIndexMask;
8386 // Maximal string length.
8387 static const int kMaxLength = (1 << 28) - 16;
8389 // Max length for computing hash. For strings longer than this limit the
8390 // string length is used as the hash value.
8391 static const int kMaxHashCalcLength = 16383;
8393 // Limit for truncation in short printing.
8394 static const int kMaxShortPrintLength = 1024;
8396 // Support for regular expressions.
8397 const uc16* GetTwoByteData(unsigned start);
8399 // Helper function for flattening strings.
8400 template <typename sinkchar>
8401 static void WriteToFlat(String* source,
8406 // The return value may point to the first aligned word containing the first
8407 // non-one-byte character, rather than directly to the non-one-byte character.
8408 // If the return value is >= the passed length, the entire string was
8410 static inline int NonAsciiStart(const char* chars, int length) {
8411 const char* start = chars;
8412 const char* limit = chars + length;
8414 if (length >= kIntptrSize) {
8415 // Check unaligned bytes.
8416 while (!IsAligned(reinterpret_cast<intptr_t>(chars), sizeof(uintptr_t))) {
8417 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8418 return static_cast<int>(chars - start);
8422 // Check aligned words.
8423 DCHECK(unibrow::Utf8::kMaxOneByteChar == 0x7F);
8424 const uintptr_t non_one_byte_mask = kUintptrAllBitsSet / 0xFF * 0x80;
8425 while (chars + sizeof(uintptr_t) <= limit) {
8426 if (*reinterpret_cast<const uintptr_t*>(chars) & non_one_byte_mask) {
8427 return static_cast<int>(chars - start);
8429 chars += sizeof(uintptr_t);
8432 // Check remaining unaligned bytes.
8433 while (chars < limit) {
8434 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8435 return static_cast<int>(chars - start);
8440 return static_cast<int>(chars - start);
8443 static inline bool IsAscii(const char* chars, int length) {
8444 return NonAsciiStart(chars, length) >= length;
8447 static inline bool IsAscii(const uint8_t* chars, int length) {
8449 NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
8452 static inline int NonOneByteStart(const uc16* chars, int length) {
8453 const uc16* limit = chars + length;
8454 const uc16* start = chars;
8455 while (chars < limit) {
8456 if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
8459 return static_cast<int>(chars - start);
8462 static inline bool IsOneByte(const uc16* chars, int length) {
8463 return NonOneByteStart(chars, length) >= length;
8466 template<class Visitor>
8467 static inline ConsString* VisitFlat(Visitor* visitor,
8471 static Handle<FixedArray> CalculateLineEnds(Handle<String> string,
8472 bool include_ending_line);
8474 // Use the hash field to forward to the canonical internalized string
8475 // when deserializing an internalized string.
8476 inline void SetForwardedInternalizedString(String* string);
8477 inline String* GetForwardedInternalizedString();
8481 friend class StringTableInsertionKey;
8483 static Handle<String> SlowFlatten(Handle<ConsString> cons,
8484 PretenureFlag tenure);
8486 // Slow case of String::Equals. This implementation works on any strings
8487 // but it is most efficient on strings that are almost flat.
8488 bool SlowEquals(String* other);
8490 static bool SlowEquals(Handle<String> one, Handle<String> two);
8492 // Slow case of AsArrayIndex.
8493 bool SlowAsArrayIndex(uint32_t* index);
8495 // Compute and set the hash code.
8496 uint32_t ComputeAndSetHash();
8498 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
8502 // The SeqString abstract class captures sequential string values.
8503 class SeqString: public String {
8505 DECLARE_CAST(SeqString)
8507 // Layout description.
8508 static const int kHeaderSize = String::kSize;
8510 // Truncate the string in-place if possible and return the result.
8511 // In case of new_length == 0, the empty string is returned without
8512 // truncating the original string.
8513 MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
8516 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
8520 // The OneByteString class captures sequential one-byte string objects.
8521 // Each character in the OneByteString is an one-byte character.
8522 class SeqOneByteString: public SeqString {
8524 static const bool kHasOneByteEncoding = true;
8526 // Dispatched behavior.
8527 inline uint16_t SeqOneByteStringGet(int index);
8528 inline void SeqOneByteStringSet(int index, uint16_t value);
8530 // Get the address of the characters in this string.
8531 inline Address GetCharsAddress();
8533 inline uint8_t* GetChars();
8535 DECLARE_CAST(SeqOneByteString)
8537 // Garbage collection support. This method is called by the
8538 // garbage collector to compute the actual size of an OneByteString
8540 inline int SeqOneByteStringSize(InstanceType instance_type);
8542 // Computes the size for an OneByteString instance of a given length.
8543 static int SizeFor(int length) {
8544 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
8547 // Maximal memory usage for a single sequential one-byte string.
8548 static const int kMaxSize = 512 * MB - 1;
8549 STATIC_ASSERT((kMaxSize - kHeaderSize) >= String::kMaxLength);
8552 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
8556 // The TwoByteString class captures sequential unicode string objects.
8557 // Each character in the TwoByteString is a two-byte uint16_t.
8558 class SeqTwoByteString: public SeqString {
8560 static const bool kHasOneByteEncoding = false;
8562 // Dispatched behavior.
8563 inline uint16_t SeqTwoByteStringGet(int index);
8564 inline void SeqTwoByteStringSet(int index, uint16_t value);
8566 // Get the address of the characters in this string.
8567 inline Address GetCharsAddress();
8569 inline uc16* GetChars();
8572 const uint16_t* SeqTwoByteStringGetData(unsigned start);
8574 DECLARE_CAST(SeqTwoByteString)
8576 // Garbage collection support. This method is called by the
8577 // garbage collector to compute the actual size of a TwoByteString
8579 inline int SeqTwoByteStringSize(InstanceType instance_type);
8581 // Computes the size for a TwoByteString instance of a given length.
8582 static int SizeFor(int length) {
8583 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
8586 // Maximal memory usage for a single sequential two-byte string.
8587 static const int kMaxSize = 512 * MB - 1;
8588 STATIC_ASSERT(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
8589 String::kMaxLength);
8592 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
8596 // The ConsString class describes string values built by using the
8597 // addition operator on strings. A ConsString is a pair where the
8598 // first and second components are pointers to other string values.
8599 // One or both components of a ConsString can be pointers to other
8600 // ConsStrings, creating a binary tree of ConsStrings where the leaves
8601 // are non-ConsString string values. The string value represented by
8602 // a ConsString can be obtained by concatenating the leaf string
8603 // values in a left-to-right depth-first traversal of the tree.
8604 class ConsString: public String {
8606 // First string of the cons cell.
8607 inline String* first();
8608 // Doesn't check that the result is a string, even in debug mode. This is
8609 // useful during GC where the mark bits confuse the checks.
8610 inline Object* unchecked_first();
8611 inline void set_first(String* first,
8612 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8614 // Second string of the cons cell.
8615 inline String* second();
8616 // Doesn't check that the result is a string, even in debug mode. This is
8617 // useful during GC where the mark bits confuse the checks.
8618 inline Object* unchecked_second();
8619 inline void set_second(String* second,
8620 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8622 // Dispatched behavior.
8623 uint16_t ConsStringGet(int index);
8625 DECLARE_CAST(ConsString)
8627 // Layout description.
8628 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
8629 static const int kSecondOffset = kFirstOffset + kPointerSize;
8630 static const int kSize = kSecondOffset + kPointerSize;
8632 // Minimum length for a cons string.
8633 static const int kMinLength = 13;
8635 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
8638 DECLARE_VERIFIER(ConsString)
8641 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
8645 // The Sliced String class describes strings that are substrings of another
8646 // sequential string. The motivation is to save time and memory when creating
8647 // a substring. A Sliced String is described as a pointer to the parent,
8648 // the offset from the start of the parent string and the length. Using
8649 // a Sliced String therefore requires unpacking of the parent string and
8650 // adding the offset to the start address. A substring of a Sliced String
8651 // are not nested since the double indirection is simplified when creating
8652 // such a substring.
8653 // Currently missing features are:
8654 // - handling externalized parent strings
8655 // - external strings as parent
8656 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
8657 class SlicedString: public String {
8659 inline String* parent();
8660 inline void set_parent(String* parent,
8661 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8662 inline int offset() const;
8663 inline void set_offset(int offset);
8665 // Dispatched behavior.
8666 uint16_t SlicedStringGet(int index);
8668 DECLARE_CAST(SlicedString)
8670 // Layout description.
8671 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
8672 static const int kOffsetOffset = kParentOffset + kPointerSize;
8673 static const int kSize = kOffsetOffset + kPointerSize;
8675 // Minimum length for a sliced string.
8676 static const int kMinLength = 13;
8678 typedef FixedBodyDescriptor<kParentOffset,
8679 kOffsetOffset + kPointerSize, kSize>
8682 DECLARE_VERIFIER(SlicedString)
8685 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
8689 // The ExternalString class describes string values that are backed by
8690 // a string resource that lies outside the V8 heap. ExternalStrings
8691 // consist of the length field common to all strings, a pointer to the
8692 // external resource. It is important to ensure (externally) that the
8693 // resource is not deallocated while the ExternalString is live in the
8696 // The API expects that all ExternalStrings are created through the
8697 // API. Therefore, ExternalStrings should not be used internally.
8698 class ExternalString: public String {
8700 DECLARE_CAST(ExternalString)
8702 // Layout description.
8703 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
8704 static const int kShortSize = kResourceOffset + kPointerSize;
8705 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
8706 static const int kSize = kResourceDataOffset + kPointerSize;
8708 static const int kMaxShortLength =
8709 (kShortSize - SeqString::kHeaderSize) / kCharSize;
8711 // Return whether external string is short (data pointer is not cached).
8712 inline bool is_short();
8714 STATIC_ASSERT(kResourceOffset == Internals::kStringResourceOffset);
8717 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
8721 // The ExternalOneByteString class is an external string backed by an
8723 class ExternalOneByteString : public ExternalString {
8725 static const bool kHasOneByteEncoding = true;
8727 typedef v8::String::ExternalOneByteStringResource Resource;
8729 // The underlying resource.
8730 inline const Resource* resource();
8731 inline void set_resource(const Resource* buffer);
8733 // Update the pointer cache to the external character array.
8734 // The cached pointer is always valid, as the external character array does =
8735 // not move during lifetime. Deserialization is the only exception, after
8736 // which the pointer cache has to be refreshed.
8737 inline void update_data_cache();
8739 inline const uint8_t* GetChars();
8741 // Dispatched behavior.
8742 inline uint16_t ExternalOneByteStringGet(int index);
8744 DECLARE_CAST(ExternalOneByteString)
8746 // Garbage collection support.
8747 inline void ExternalOneByteStringIterateBody(ObjectVisitor* v);
8749 template <typename StaticVisitor>
8750 inline void ExternalOneByteStringIterateBody();
8753 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalOneByteString);
8757 // The ExternalTwoByteString class is an external string backed by a UTF-16
8759 class ExternalTwoByteString: public ExternalString {
8761 static const bool kHasOneByteEncoding = false;
8763 typedef v8::String::ExternalStringResource Resource;
8765 // The underlying string resource.
8766 inline const Resource* resource();
8767 inline void set_resource(const Resource* buffer);
8769 // Update the pointer cache to the external character array.
8770 // The cached pointer is always valid, as the external character array does =
8771 // not move during lifetime. Deserialization is the only exception, after
8772 // which the pointer cache has to be refreshed.
8773 inline void update_data_cache();
8775 inline const uint16_t* GetChars();
8777 // Dispatched behavior.
8778 inline uint16_t ExternalTwoByteStringGet(int index);
8781 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
8783 DECLARE_CAST(ExternalTwoByteString)
8785 // Garbage collection support.
8786 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
8788 template<typename StaticVisitor>
8789 inline void ExternalTwoByteStringIterateBody();
8792 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
8796 // Utility superclass for stack-allocated objects that must be updated
8797 // on gc. It provides two ways for the gc to update instances, either
8798 // iterating or updating after gc.
8799 class Relocatable BASE_EMBEDDED {
8801 explicit inline Relocatable(Isolate* isolate);
8802 inline virtual ~Relocatable();
8803 virtual void IterateInstance(ObjectVisitor* v) { }
8804 virtual void PostGarbageCollection() { }
8806 static void PostGarbageCollectionProcessing(Isolate* isolate);
8807 static int ArchiveSpacePerThread();
8808 static char* ArchiveState(Isolate* isolate, char* to);
8809 static char* RestoreState(Isolate* isolate, char* from);
8810 static void Iterate(Isolate* isolate, ObjectVisitor* v);
8811 static void Iterate(ObjectVisitor* v, Relocatable* top);
8812 static char* Iterate(ObjectVisitor* v, char* t);
8820 // A flat string reader provides random access to the contents of a
8821 // string independent of the character width of the string. The handle
8822 // must be valid as long as the reader is being used.
8823 class FlatStringReader : public Relocatable {
8825 FlatStringReader(Isolate* isolate, Handle<String> str);
8826 FlatStringReader(Isolate* isolate, Vector<const char> input);
8827 void PostGarbageCollection();
8828 inline uc32 Get(int index);
8829 template <typename Char>
8830 inline Char Get(int index);
8831 int length() { return length_; }
8840 // This maintains an off-stack representation of the stack frames required
8841 // to traverse a ConsString, allowing an entirely iterative and restartable
8842 // traversal of the entire string
8843 class ConsStringIterator {
8845 inline ConsStringIterator() {}
8846 inline explicit ConsStringIterator(ConsString* cons_string, int offset = 0) {
8847 Reset(cons_string, offset);
8849 inline void Reset(ConsString* cons_string, int offset = 0) {
8851 // Next will always return NULL.
8852 if (cons_string == NULL) return;
8853 Initialize(cons_string, offset);
8855 // Returns NULL when complete.
8856 inline String* Next(int* offset_out) {
8858 if (depth_ == 0) return NULL;
8859 return Continue(offset_out);
8863 static const int kStackSize = 32;
8864 // Use a mask instead of doing modulo operations for stack wrapping.
8865 static const int kDepthMask = kStackSize-1;
8866 STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
8867 static inline int OffsetForDepth(int depth);
8869 inline void PushLeft(ConsString* string);
8870 inline void PushRight(ConsString* string);
8871 inline void AdjustMaximumDepth();
8873 inline bool StackBlown() { return maximum_depth_ - depth_ == kStackSize; }
8874 void Initialize(ConsString* cons_string, int offset);
8875 String* Continue(int* offset_out);
8876 String* NextLeaf(bool* blew_stack);
8877 String* Search(int* offset_out);
8879 // Stack must always contain only frames for which right traversal
8880 // has not yet been performed.
8881 ConsString* frames_[kStackSize];
8886 DISALLOW_COPY_AND_ASSIGN(ConsStringIterator);
8890 class StringCharacterStream {
8892 inline StringCharacterStream(String* string,
8894 inline uint16_t GetNext();
8895 inline bool HasMore();
8896 inline void Reset(String* string, int offset = 0);
8897 inline void VisitOneByteString(const uint8_t* chars, int length);
8898 inline void VisitTwoByteString(const uint16_t* chars, int length);
8901 ConsStringIterator iter_;
8904 const uint8_t* buffer8_;
8905 const uint16_t* buffer16_;
8907 const uint8_t* end_;
8908 DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
8912 template <typename T>
8913 class VectorIterator {
8915 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
8916 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
8917 T GetNext() { return data_[index_++]; }
8918 bool has_more() { return index_ < data_.length(); }
8920 Vector<const T> data_;
8925 // The Oddball describes objects null, undefined, true, and false.
8926 class Oddball: public HeapObject {
8928 // [to_string]: Cached to_string computed at startup.
8929 DECL_ACCESSORS(to_string, String)
8931 // [to_number]: Cached to_number computed at startup.
8932 DECL_ACCESSORS(to_number, Object)
8934 // [typeof]: Cached type_of computed at startup.
8935 DECL_ACCESSORS(type_of, String)
8937 inline byte kind() const;
8938 inline void set_kind(byte kind);
8940 DECLARE_CAST(Oddball)
8942 // Dispatched behavior.
8943 DECLARE_VERIFIER(Oddball)
8945 // Initialize the fields.
8946 static void Initialize(Isolate* isolate, Handle<Oddball> oddball,
8947 const char* to_string, Handle<Object> to_number,
8948 const char* type_of, byte kind);
8950 // Layout description.
8951 static const int kToStringOffset = HeapObject::kHeaderSize;
8952 static const int kToNumberOffset = kToStringOffset + kPointerSize;
8953 static const int kTypeOfOffset = kToNumberOffset + kPointerSize;
8954 static const int kKindOffset = kTypeOfOffset + kPointerSize;
8955 static const int kSize = kKindOffset + kPointerSize;
8957 static const byte kFalse = 0;
8958 static const byte kTrue = 1;
8959 static const byte kNotBooleanMask = ~1;
8960 static const byte kTheHole = 2;
8961 static const byte kNull = 3;
8962 static const byte kArgumentMarker = 4;
8963 static const byte kUndefined = 5;
8964 static const byte kUninitialized = 6;
8965 static const byte kOther = 7;
8966 static const byte kException = 8;
8968 typedef FixedBodyDescriptor<kToStringOffset, kTypeOfOffset + kPointerSize,
8969 kSize> BodyDescriptor;
8971 STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset);
8972 STATIC_ASSERT(kNull == Internals::kNullOddballKind);
8973 STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind);
8976 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
8980 class Cell: public HeapObject {
8982 // [value]: value of the cell.
8983 DECL_ACCESSORS(value, Object)
8987 static inline Cell* FromValueAddress(Address value) {
8988 Object* result = FromAddress(value - kValueOffset);
8989 return static_cast<Cell*>(result);
8992 inline Address ValueAddress() {
8993 return address() + kValueOffset;
8996 // Dispatched behavior.
8997 DECLARE_PRINTER(Cell)
8998 DECLARE_VERIFIER(Cell)
9000 // Layout description.
9001 static const int kValueOffset = HeapObject::kHeaderSize;
9002 static const int kSize = kValueOffset + kPointerSize;
9004 typedef FixedBodyDescriptor<kValueOffset,
9005 kValueOffset + kPointerSize,
9006 kSize> BodyDescriptor;
9009 DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9013 class PropertyCell : public HeapObject {
9015 // [property_details]: details of the global property.
9016 DECL_ACCESSORS(property_details_raw, Object)
9017 // [value]: value of the global property.
9018 DECL_ACCESSORS(value, Object)
9019 // [dependent_code]: dependent code that depends on the type of the global
9021 DECL_ACCESSORS(dependent_code, DependentCode)
9023 inline PropertyDetails property_details();
9024 inline void set_property_details(PropertyDetails details);
9026 PropertyCellConstantType GetConstantType();
9028 // Computes the new type of the cell's contents for the given value, but
9029 // without actually modifying the details.
9030 static PropertyCellType UpdatedType(Handle<PropertyCell> cell,
9031 Handle<Object> value,
9032 PropertyDetails details);
9033 static void UpdateCell(Handle<GlobalDictionary> dictionary, int entry,
9034 Handle<Object> value, PropertyDetails details);
9036 static Handle<PropertyCell> InvalidateEntry(
9037 Handle<GlobalDictionary> dictionary, int entry);
9039 static void SetValueWithInvalidation(Handle<PropertyCell> cell,
9040 Handle<Object> new_value);
9042 DECLARE_CAST(PropertyCell)
9044 // Dispatched behavior.
9045 DECLARE_PRINTER(PropertyCell)
9046 DECLARE_VERIFIER(PropertyCell)
9048 // Layout description.
9049 static const int kDetailsOffset = HeapObject::kHeaderSize;
9050 static const int kValueOffset = kDetailsOffset + kPointerSize;
9051 static const int kDependentCodeOffset = kValueOffset + kPointerSize;
9052 static const int kSize = kDependentCodeOffset + kPointerSize;
9054 static const int kPointerFieldsBeginOffset = kValueOffset;
9055 static const int kPointerFieldsEndOffset = kSize;
9057 typedef FixedBodyDescriptor<kValueOffset,
9059 kSize> BodyDescriptor;
9062 DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9066 class WeakCell : public HeapObject {
9068 inline Object* value() const;
9070 // This should not be called by anyone except GC.
9071 inline void clear();
9073 // This should not be called by anyone except allocator.
9074 inline void initialize(HeapObject* value);
9076 inline bool cleared() const;
9078 DECL_ACCESSORS(next, Object)
9080 inline void clear_next(Heap* heap);
9082 inline bool next_cleared();
9084 DECLARE_CAST(WeakCell)
9086 DECLARE_PRINTER(WeakCell)
9087 DECLARE_VERIFIER(WeakCell)
9089 // Layout description.
9090 static const int kValueOffset = HeapObject::kHeaderSize;
9091 static const int kNextOffset = kValueOffset + kPointerSize;
9092 static const int kSize = kNextOffset + kPointerSize;
9094 typedef FixedBodyDescriptor<kValueOffset, kSize, kSize> BodyDescriptor;
9097 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakCell);
9101 // The JSProxy describes EcmaScript Harmony proxies
9102 class JSProxy: public JSReceiver {
9104 // [handler]: The handler property.
9105 DECL_ACCESSORS(handler, Object)
9107 // [hash]: The hash code property (undefined if not initialized yet).
9108 DECL_ACCESSORS(hash, Object)
9110 DECLARE_CAST(JSProxy)
9112 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithHandler(
9113 Handle<JSProxy> proxy,
9114 Handle<Object> receiver,
9117 // If the handler defines an accessor property with a setter, invoke it.
9118 // If it defines an accessor property without a setter, or a data property
9119 // that is read-only, throw. In all these cases set '*done' to true,
9120 // otherwise set it to false.
9122 static MaybeHandle<Object> SetPropertyViaPrototypesWithHandler(
9123 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9124 Handle<Object> value, LanguageMode language_mode, bool* done);
9126 MUST_USE_RESULT static Maybe<PropertyAttributes>
9127 GetPropertyAttributesWithHandler(Handle<JSProxy> proxy,
9128 Handle<Object> receiver,
9130 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithHandler(
9131 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9132 Handle<Object> value, LanguageMode language_mode);
9134 // Turn the proxy into an (empty) JSObject.
9135 static void Fix(Handle<JSProxy> proxy);
9137 // Initializes the body after the handler slot.
9138 inline void InitializeBody(int object_size, Object* value);
9140 // Invoke a trap by name. If the trap does not exist on this's handler,
9141 // but derived_trap is non-NULL, invoke that instead. May cause GC.
9142 MUST_USE_RESULT static MaybeHandle<Object> CallTrap(
9143 Handle<JSProxy> proxy,
9145 Handle<Object> derived_trap,
9147 Handle<Object> args[]);
9149 // Dispatched behavior.
9150 DECLARE_PRINTER(JSProxy)
9151 DECLARE_VERIFIER(JSProxy)
9153 // Layout description. We add padding so that a proxy has the same
9154 // size as a virgin JSObject. This is essential for becoming a JSObject
9156 static const int kHandlerOffset = HeapObject::kHeaderSize;
9157 static const int kHashOffset = kHandlerOffset + kPointerSize;
9158 static const int kPaddingOffset = kHashOffset + kPointerSize;
9159 static const int kSize = JSObject::kHeaderSize;
9160 static const int kHeaderSize = kPaddingOffset;
9161 static const int kPaddingSize = kSize - kPaddingOffset;
9163 STATIC_ASSERT(kPaddingSize >= 0);
9165 typedef FixedBodyDescriptor<kHandlerOffset,
9167 kSize> BodyDescriptor;
9170 friend class JSReceiver;
9172 MUST_USE_RESULT static Maybe<bool> HasPropertyWithHandler(
9173 Handle<JSProxy> proxy, Handle<Name> name);
9175 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithHandler(
9176 Handle<JSProxy> proxy, Handle<Name> name, LanguageMode language_mode);
9178 MUST_USE_RESULT Object* GetIdentityHash();
9180 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
9182 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
9186 class JSFunctionProxy: public JSProxy {
9188 // [call_trap]: The call trap.
9189 DECL_ACCESSORS(call_trap, Object)
9191 // [construct_trap]: The construct trap.
9192 DECL_ACCESSORS(construct_trap, Object)
9194 DECLARE_CAST(JSFunctionProxy)
9196 // Dispatched behavior.
9197 DECLARE_PRINTER(JSFunctionProxy)
9198 DECLARE_VERIFIER(JSFunctionProxy)
9200 // Layout description.
9201 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
9202 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
9203 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
9204 static const int kSize = JSFunction::kSize;
9205 static const int kPaddingSize = kSize - kPaddingOffset;
9207 STATIC_ASSERT(kPaddingSize >= 0);
9209 typedef FixedBodyDescriptor<kHandlerOffset,
9210 kConstructTrapOffset + kPointerSize,
9211 kSize> BodyDescriptor;
9214 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
9218 class JSCollection : public JSObject {
9220 // [table]: the backing hash table
9221 DECL_ACCESSORS(table, Object)
9223 static const int kTableOffset = JSObject::kHeaderSize;
9224 static const int kSize = kTableOffset + kPointerSize;
9227 DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollection);
9231 // The JSSet describes EcmaScript Harmony sets
9232 class JSSet : public JSCollection {
9236 // Dispatched behavior.
9237 DECLARE_PRINTER(JSSet)
9238 DECLARE_VERIFIER(JSSet)
9241 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
9245 // The JSMap describes EcmaScript Harmony maps
9246 class JSMap : public JSCollection {
9250 // Dispatched behavior.
9251 DECLARE_PRINTER(JSMap)
9252 DECLARE_VERIFIER(JSMap)
9255 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
9259 // OrderedHashTableIterator is an iterator that iterates over the keys and
9260 // values of an OrderedHashTable.
9262 // The iterator has a reference to the underlying OrderedHashTable data,
9263 // [table], as well as the current [index] the iterator is at.
9265 // When the OrderedHashTable is rehashed it adds a reference from the old table
9266 // to the new table as well as storing enough data about the changes so that the
9267 // iterator [index] can be adjusted accordingly.
9269 // When the [Next] result from the iterator is requested, the iterator checks if
9270 // there is a newer table that it needs to transition to.
9271 template<class Derived, class TableType>
9272 class OrderedHashTableIterator: public JSObject {
9274 // [table]: the backing hash table mapping keys to values.
9275 DECL_ACCESSORS(table, Object)
9277 // [index]: The index into the data table.
9278 DECL_ACCESSORS(index, Object)
9280 // [kind]: The kind of iteration this is. One of the [Kind] enum values.
9281 DECL_ACCESSORS(kind, Object)
9284 void OrderedHashTableIteratorPrint(std::ostream& os); // NOLINT
9287 static const int kTableOffset = JSObject::kHeaderSize;
9288 static const int kIndexOffset = kTableOffset + kPointerSize;
9289 static const int kKindOffset = kIndexOffset + kPointerSize;
9290 static const int kSize = kKindOffset + kPointerSize;
9298 // Whether the iterator has more elements. This needs to be called before
9299 // calling |CurrentKey| and/or |CurrentValue|.
9302 // Move the index forward one.
9304 set_index(Smi::FromInt(Smi::cast(index())->value() + 1));
9307 // Populates the array with the next key and value and then moves the iterator
9309 // This returns the |kind| or 0 if the iterator is already at the end.
9310 Smi* Next(JSArray* value_array);
9312 // Returns the current key of the iterator. This should only be called when
9313 // |HasMore| returns true.
9314 inline Object* CurrentKey();
9317 // Transitions the iterator to the non obsolete backing store. This is a NOP
9318 // if the [table] is not obsolete.
9321 DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
9325 class JSSetIterator: public OrderedHashTableIterator<JSSetIterator,
9328 // Dispatched behavior.
9329 DECLARE_PRINTER(JSSetIterator)
9330 DECLARE_VERIFIER(JSSetIterator)
9332 DECLARE_CAST(JSSetIterator)
9334 // Called by |Next| to populate the array. This allows the subclasses to
9335 // populate the array differently.
9336 inline void PopulateValueArray(FixedArray* array);
9339 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSetIterator);
9343 class JSMapIterator: public OrderedHashTableIterator<JSMapIterator,
9346 // Dispatched behavior.
9347 DECLARE_PRINTER(JSMapIterator)
9348 DECLARE_VERIFIER(JSMapIterator)
9350 DECLARE_CAST(JSMapIterator)
9352 // Called by |Next| to populate the array. This allows the subclasses to
9353 // populate the array differently.
9354 inline void PopulateValueArray(FixedArray* array);
9357 // Returns the current value of the iterator. This should only be called when
9358 // |HasMore| returns true.
9359 inline Object* CurrentValue();
9361 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMapIterator);
9365 // Base class for both JSWeakMap and JSWeakSet
9366 class JSWeakCollection: public JSObject {
9368 // [table]: the backing hash table mapping keys to values.
9369 DECL_ACCESSORS(table, Object)
9371 // [next]: linked list of encountered weak maps during GC.
9372 DECL_ACCESSORS(next, Object)
9374 static const int kTableOffset = JSObject::kHeaderSize;
9375 static const int kNextOffset = kTableOffset + kPointerSize;
9376 static const int kSize = kNextOffset + kPointerSize;
9379 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
9383 // The JSWeakMap describes EcmaScript Harmony weak maps
9384 class JSWeakMap: public JSWeakCollection {
9386 DECLARE_CAST(JSWeakMap)
9388 // Dispatched behavior.
9389 DECLARE_PRINTER(JSWeakMap)
9390 DECLARE_VERIFIER(JSWeakMap)
9393 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
9397 // The JSWeakSet describes EcmaScript Harmony weak sets
9398 class JSWeakSet: public JSWeakCollection {
9400 DECLARE_CAST(JSWeakSet)
9402 // Dispatched behavior.
9403 DECLARE_PRINTER(JSWeakSet)
9404 DECLARE_VERIFIER(JSWeakSet)
9407 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
9411 // Whether a JSArrayBuffer is a SharedArrayBuffer or not.
9412 enum class SharedFlag { kNotShared, kShared };
9415 class JSArrayBuffer: public JSObject {
9417 // [backing_store]: backing memory for this array
9418 DECL_ACCESSORS(backing_store, void)
9420 // [byte_length]: length in bytes
9421 DECL_ACCESSORS(byte_length, Object)
9423 inline uint32_t bit_field() const;
9424 inline void set_bit_field(uint32_t bits);
9426 inline bool is_external();
9427 inline void set_is_external(bool value);
9429 inline bool is_neuterable();
9430 inline void set_is_neuterable(bool value);
9432 inline bool was_neutered();
9433 inline void set_was_neutered(bool value);
9435 inline bool is_shared();
9436 inline void set_is_shared(bool value);
9438 DECLARE_CAST(JSArrayBuffer)
9442 // Dispatched behavior.
9443 DECLARE_PRINTER(JSArrayBuffer)
9444 DECLARE_VERIFIER(JSArrayBuffer)
9446 static const int kBackingStoreOffset = JSObject::kHeaderSize;
9447 static const int kByteLengthOffset = kBackingStoreOffset + kPointerSize;
9448 static const int kBitFieldSlot = kByteLengthOffset + kPointerSize;
9449 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
9450 static const int kBitFieldOffset = kBitFieldSlot;
9452 static const int kBitFieldOffset = kBitFieldSlot + kIntSize;
9454 static const int kSize = kBitFieldSlot + kPointerSize;
9456 static const int kSizeWithInternalFields =
9457 kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
9459 class IsExternal : public BitField<bool, 1, 1> {};
9460 class IsNeuterable : public BitField<bool, 2, 1> {};
9461 class WasNeutered : public BitField<bool, 3, 1> {};
9462 class IsShared : public BitField<bool, 4, 1> {};
9465 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
9469 class JSArrayBufferView: public JSObject {
9471 // [buffer]: ArrayBuffer that this typed array views.
9472 DECL_ACCESSORS(buffer, Object)
9474 // [byte_offset]: offset of typed array in bytes.
9475 DECL_ACCESSORS(byte_offset, Object)
9477 // [byte_length]: length of typed array in bytes.
9478 DECL_ACCESSORS(byte_length, Object)
9480 DECLARE_CAST(JSArrayBufferView)
9482 DECLARE_VERIFIER(JSArrayBufferView)
9484 inline bool WasNeutered() const;
9486 static const int kBufferOffset = JSObject::kHeaderSize;
9487 static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
9488 static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
9489 static const int kViewSize = kByteLengthOffset + kPointerSize;
9493 DECL_ACCESSORS(raw_byte_offset, Object)
9494 DECL_ACCESSORS(raw_byte_length, Object)
9497 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
9501 class JSTypedArray: public JSArrayBufferView {
9503 // [length]: length of typed array in elements.
9504 DECL_ACCESSORS(length, Object)
9505 inline uint32_t length_value() const;
9507 DECLARE_CAST(JSTypedArray)
9509 ExternalArrayType type();
9510 size_t element_size();
9512 Handle<JSArrayBuffer> GetBuffer();
9514 // Dispatched behavior.
9515 DECLARE_PRINTER(JSTypedArray)
9516 DECLARE_VERIFIER(JSTypedArray)
9518 static const int kLengthOffset = kViewSize + kPointerSize;
9519 static const int kSize = kLengthOffset + kPointerSize;
9521 static const int kSizeWithInternalFields =
9522 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9525 static Handle<JSArrayBuffer> MaterializeArrayBuffer(
9526 Handle<JSTypedArray> typed_array);
9528 DECL_ACCESSORS(raw_length, Object)
9531 DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
9535 class JSDataView: public JSArrayBufferView {
9537 DECLARE_CAST(JSDataView)
9539 // Dispatched behavior.
9540 DECLARE_PRINTER(JSDataView)
9541 DECLARE_VERIFIER(JSDataView)
9543 static const int kSize = kViewSize;
9545 static const int kSizeWithInternalFields =
9546 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9549 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
9553 // Foreign describes objects pointing from JavaScript to C structures.
9554 class Foreign: public HeapObject {
9556 // [address]: field containing the address.
9557 inline Address foreign_address();
9558 inline void set_foreign_address(Address value);
9560 DECLARE_CAST(Foreign)
9562 // Dispatched behavior.
9563 inline void ForeignIterateBody(ObjectVisitor* v);
9565 template<typename StaticVisitor>
9566 inline void ForeignIterateBody();
9568 // Dispatched behavior.
9569 DECLARE_PRINTER(Foreign)
9570 DECLARE_VERIFIER(Foreign)
9572 // Layout description.
9574 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
9575 static const int kSize = kForeignAddressOffset + kPointerSize;
9577 STATIC_ASSERT(kForeignAddressOffset == Internals::kForeignAddressOffset);
9580 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
9584 // The JSArray describes JavaScript Arrays
9585 // Such an array can be in one of two modes:
9586 // - fast, backing storage is a FixedArray and length <= elements.length();
9587 // Please note: push and pop can be used to grow and shrink the array.
9588 // - slow, backing storage is a HashTable with numbers as keys.
9589 class JSArray: public JSObject {
9591 // [length]: The length property.
9592 DECL_ACCESSORS(length, Object)
9594 // Overload the length setter to skip write barrier when the length
9595 // is set to a smi. This matches the set function on FixedArray.
9596 inline void set_length(Smi* length);
9598 static bool HasReadOnlyLength(Handle<JSArray> array);
9599 static bool WouldChangeReadOnlyLength(Handle<JSArray> array, uint32_t index);
9600 static MaybeHandle<Object> ReadOnlyLengthError(Handle<JSArray> array);
9602 // Initialize the array with the given capacity. The function may
9603 // fail due to out-of-memory situations, but only if the requested
9604 // capacity is non-zero.
9605 static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
9607 // If the JSArray has fast elements, and new_length would result in
9608 // normalization, returns true.
9609 bool SetLengthWouldNormalize(uint32_t new_length);
9610 static inline bool SetLengthWouldNormalize(Heap* heap, uint32_t new_length);
9612 // Initializes the array to a certain length.
9613 inline bool AllowsSetLength();
9615 static void SetLength(Handle<JSArray> array, uint32_t length);
9616 // Same as above but will also queue splice records if |array| is observed.
9617 static MaybeHandle<Object> ObservableSetLength(Handle<JSArray> array,
9620 // Set the content of the array to the content of storage.
9621 static inline void SetContent(Handle<JSArray> array,
9622 Handle<FixedArrayBase> storage);
9624 DECLARE_CAST(JSArray)
9626 // Dispatched behavior.
9627 DECLARE_PRINTER(JSArray)
9628 DECLARE_VERIFIER(JSArray)
9630 // Number of element slots to pre-allocate for an empty array.
9631 static const int kPreallocatedArrayElements = 4;
9633 // Layout description.
9634 static const int kLengthOffset = JSObject::kHeaderSize;
9635 static const int kSize = kLengthOffset + kPointerSize;
9638 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
9642 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
9643 Handle<Map> initial_map);
9646 // JSRegExpResult is just a JSArray with a specific initial map.
9647 // This initial map adds in-object properties for "index" and "input"
9648 // properties, as assigned by RegExp.prototype.exec, which allows
9649 // faster creation of RegExp exec results.
9650 // This class just holds constants used when creating the result.
9651 // After creation the result must be treated as a JSArray in all regards.
9652 class JSRegExpResult: public JSArray {
9654 // Offsets of object fields.
9655 static const int kIndexOffset = JSArray::kSize;
9656 static const int kInputOffset = kIndexOffset + kPointerSize;
9657 static const int kSize = kInputOffset + kPointerSize;
9658 // Indices of in-object properties.
9659 static const int kIndexIndex = 0;
9660 static const int kInputIndex = 1;
9662 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
9666 class AccessorInfo: public Struct {
9668 DECL_ACCESSORS(name, Object)
9669 DECL_ACCESSORS(flag, Smi)
9670 DECL_ACCESSORS(expected_receiver_type, Object)
9672 inline bool all_can_read();
9673 inline void set_all_can_read(bool value);
9675 inline bool all_can_write();
9676 inline void set_all_can_write(bool value);
9678 inline bool is_special_data_property();
9679 inline void set_is_special_data_property(bool value);
9681 inline PropertyAttributes property_attributes();
9682 inline void set_property_attributes(PropertyAttributes attributes);
9684 // Checks whether the given receiver is compatible with this accessor.
9685 static bool IsCompatibleReceiverMap(Isolate* isolate,
9686 Handle<AccessorInfo> info,
9688 inline bool IsCompatibleReceiver(Object* receiver);
9690 DECLARE_CAST(AccessorInfo)
9692 // Dispatched behavior.
9693 DECLARE_VERIFIER(AccessorInfo)
9695 // Append all descriptors to the array that are not already there.
9696 // Return number added.
9697 static int AppendUnique(Handle<Object> descriptors,
9698 Handle<FixedArray> array,
9699 int valid_descriptors);
9701 static const int kNameOffset = HeapObject::kHeaderSize;
9702 static const int kFlagOffset = kNameOffset + kPointerSize;
9703 static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
9704 static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
9707 inline bool HasExpectedReceiverType();
9709 // Bit positions in flag.
9710 static const int kAllCanReadBit = 0;
9711 static const int kAllCanWriteBit = 1;
9712 static const int kSpecialDataProperty = 2;
9713 class AttributesField : public BitField<PropertyAttributes, 3, 3> {};
9715 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
9719 // An accessor must have a getter, but can have no setter.
9721 // When setting a property, V8 searches accessors in prototypes.
9722 // If an accessor was found and it does not have a setter,
9723 // the request is ignored.
9725 // If the accessor in the prototype has the READ_ONLY property attribute, then
9726 // a new value is added to the derived object when the property is set.
9727 // This shadows the accessor in the prototype.
9728 class ExecutableAccessorInfo: public AccessorInfo {
9730 DECL_ACCESSORS(getter, Object)
9731 DECL_ACCESSORS(setter, Object)
9732 DECL_ACCESSORS(data, Object)
9734 DECLARE_CAST(ExecutableAccessorInfo)
9736 // Dispatched behavior.
9737 DECLARE_PRINTER(ExecutableAccessorInfo)
9738 DECLARE_VERIFIER(ExecutableAccessorInfo)
9740 static const int kGetterOffset = AccessorInfo::kSize;
9741 static const int kSetterOffset = kGetterOffset + kPointerSize;
9742 static const int kDataOffset = kSetterOffset + kPointerSize;
9743 static const int kSize = kDataOffset + kPointerSize;
9745 static void ClearSetter(Handle<ExecutableAccessorInfo> info);
9748 DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
9752 // Support for JavaScript accessors: A pair of a getter and a setter. Each
9753 // accessor can either be
9754 // * a pointer to a JavaScript function or proxy: a real accessor
9755 // * undefined: considered an accessor by the spec, too, strangely enough
9756 // * the hole: an accessor which has not been set
9757 // * a pointer to a map: a transition used to ensure map sharing
9758 class AccessorPair: public Struct {
9760 DECL_ACCESSORS(getter, Object)
9761 DECL_ACCESSORS(setter, Object)
9763 DECLARE_CAST(AccessorPair)
9765 static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
9767 inline Object* get(AccessorComponent component);
9768 inline void set(AccessorComponent component, Object* value);
9770 // Note: Returns undefined instead in case of a hole.
9771 Object* GetComponent(AccessorComponent component);
9773 // Set both components, skipping arguments which are a JavaScript null.
9774 inline void SetComponents(Object* getter, Object* setter);
9776 inline bool Equals(AccessorPair* pair);
9777 inline bool Equals(Object* getter_value, Object* setter_value);
9779 inline bool ContainsAccessor();
9781 // Dispatched behavior.
9782 DECLARE_PRINTER(AccessorPair)
9783 DECLARE_VERIFIER(AccessorPair)
9785 static const int kGetterOffset = HeapObject::kHeaderSize;
9786 static const int kSetterOffset = kGetterOffset + kPointerSize;
9787 static const int kSize = kSetterOffset + kPointerSize;
9790 // Strangely enough, in addition to functions and harmony proxies, the spec
9791 // requires us to consider undefined as a kind of accessor, too:
9793 // Object.defineProperty(obj, "foo", {get: undefined});
9794 // assertTrue("foo" in obj);
9795 inline bool IsJSAccessor(Object* obj);
9797 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
9801 class AccessCheckInfo: public Struct {
9803 DECL_ACCESSORS(named_callback, Object)
9804 DECL_ACCESSORS(indexed_callback, Object)
9805 DECL_ACCESSORS(data, Object)
9807 DECLARE_CAST(AccessCheckInfo)
9809 // Dispatched behavior.
9810 DECLARE_PRINTER(AccessCheckInfo)
9811 DECLARE_VERIFIER(AccessCheckInfo)
9813 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
9814 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
9815 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
9816 static const int kSize = kDataOffset + kPointerSize;
9819 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
9823 class InterceptorInfo: public Struct {
9825 DECL_ACCESSORS(getter, Object)
9826 DECL_ACCESSORS(setter, Object)
9827 DECL_ACCESSORS(query, Object)
9828 DECL_ACCESSORS(deleter, Object)
9829 DECL_ACCESSORS(enumerator, Object)
9830 DECL_ACCESSORS(data, Object)
9831 DECL_BOOLEAN_ACCESSORS(can_intercept_symbols)
9832 DECL_BOOLEAN_ACCESSORS(all_can_read)
9833 DECL_BOOLEAN_ACCESSORS(non_masking)
9835 inline int flags() const;
9836 inline void set_flags(int flags);
9838 DECLARE_CAST(InterceptorInfo)
9840 // Dispatched behavior.
9841 DECLARE_PRINTER(InterceptorInfo)
9842 DECLARE_VERIFIER(InterceptorInfo)
9844 static const int kGetterOffset = HeapObject::kHeaderSize;
9845 static const int kSetterOffset = kGetterOffset + kPointerSize;
9846 static const int kQueryOffset = kSetterOffset + kPointerSize;
9847 static const int kDeleterOffset = kQueryOffset + kPointerSize;
9848 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
9849 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
9850 static const int kFlagsOffset = kDataOffset + kPointerSize;
9851 static const int kSize = kFlagsOffset + kPointerSize;
9853 static const int kCanInterceptSymbolsBit = 0;
9854 static const int kAllCanReadBit = 1;
9855 static const int kNonMasking = 2;
9858 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
9862 class CallHandlerInfo: public Struct {
9864 DECL_ACCESSORS(callback, Object)
9865 DECL_ACCESSORS(data, Object)
9867 DECLARE_CAST(CallHandlerInfo)
9869 // Dispatched behavior.
9870 DECLARE_PRINTER(CallHandlerInfo)
9871 DECLARE_VERIFIER(CallHandlerInfo)
9873 static const int kCallbackOffset = HeapObject::kHeaderSize;
9874 static const int kDataOffset = kCallbackOffset + kPointerSize;
9875 static const int kSize = kDataOffset + kPointerSize;
9878 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
9882 class TemplateInfo: public Struct {
9884 DECL_ACCESSORS(tag, Object)
9885 inline int number_of_properties() const;
9886 inline void set_number_of_properties(int value);
9887 DECL_ACCESSORS(property_list, Object)
9888 DECL_ACCESSORS(property_accessors, Object)
9890 DECLARE_VERIFIER(TemplateInfo)
9892 static const int kTagOffset = HeapObject::kHeaderSize;
9893 static const int kNumberOfProperties = kTagOffset + kPointerSize;
9894 static const int kPropertyListOffset = kNumberOfProperties + kPointerSize;
9895 static const int kPropertyAccessorsOffset =
9896 kPropertyListOffset + kPointerSize;
9897 static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
9900 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
9904 class FunctionTemplateInfo: public TemplateInfo {
9906 DECL_ACCESSORS(serial_number, Object)
9907 DECL_ACCESSORS(call_code, Object)
9908 DECL_ACCESSORS(prototype_template, Object)
9909 DECL_ACCESSORS(parent_template, Object)
9910 DECL_ACCESSORS(named_property_handler, Object)
9911 DECL_ACCESSORS(indexed_property_handler, Object)
9912 DECL_ACCESSORS(instance_template, Object)
9913 DECL_ACCESSORS(class_name, Object)
9914 DECL_ACCESSORS(signature, Object)
9915 DECL_ACCESSORS(instance_call_handler, Object)
9916 DECL_ACCESSORS(access_check_info, Object)
9917 DECL_ACCESSORS(flag, Smi)
9919 inline int length() const;
9920 inline void set_length(int value);
9922 // Following properties use flag bits.
9923 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
9924 DECL_BOOLEAN_ACCESSORS(undetectable)
9925 // If the bit is set, object instances created by this function
9926 // requires access check.
9927 DECL_BOOLEAN_ACCESSORS(needs_access_check)
9928 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
9929 DECL_BOOLEAN_ACCESSORS(remove_prototype)
9930 DECL_BOOLEAN_ACCESSORS(do_not_cache)
9931 DECL_BOOLEAN_ACCESSORS(instantiated)
9932 DECL_BOOLEAN_ACCESSORS(accept_any_receiver)
9934 DECLARE_CAST(FunctionTemplateInfo)
9936 // Dispatched behavior.
9937 DECLARE_PRINTER(FunctionTemplateInfo)
9938 DECLARE_VERIFIER(FunctionTemplateInfo)
9940 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
9941 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
9942 static const int kPrototypeTemplateOffset =
9943 kCallCodeOffset + kPointerSize;
9944 static const int kParentTemplateOffset =
9945 kPrototypeTemplateOffset + kPointerSize;
9946 static const int kNamedPropertyHandlerOffset =
9947 kParentTemplateOffset + kPointerSize;
9948 static const int kIndexedPropertyHandlerOffset =
9949 kNamedPropertyHandlerOffset + kPointerSize;
9950 static const int kInstanceTemplateOffset =
9951 kIndexedPropertyHandlerOffset + kPointerSize;
9952 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
9953 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
9954 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
9955 static const int kAccessCheckInfoOffset =
9956 kInstanceCallHandlerOffset + kPointerSize;
9957 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
9958 static const int kLengthOffset = kFlagOffset + kPointerSize;
9959 static const int kSize = kLengthOffset + kPointerSize;
9961 // Returns true if |object| is an instance of this function template.
9962 bool IsTemplateFor(Object* object);
9963 bool IsTemplateFor(Map* map);
9965 // Returns the holder JSObject if the function can legally be called with this
9966 // receiver. Returns Heap::null_value() if the call is illegal.
9967 Object* GetCompatibleReceiver(Isolate* isolate, Object* receiver);
9970 // Bit position in the flag, from least significant bit position.
9971 static const int kHiddenPrototypeBit = 0;
9972 static const int kUndetectableBit = 1;
9973 static const int kNeedsAccessCheckBit = 2;
9974 static const int kReadOnlyPrototypeBit = 3;
9975 static const int kRemovePrototypeBit = 4;
9976 static const int kDoNotCacheBit = 5;
9977 static const int kInstantiatedBit = 6;
9978 static const int kAcceptAnyReceiver = 7;
9980 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
9984 class ObjectTemplateInfo: public TemplateInfo {
9986 DECL_ACCESSORS(constructor, Object)
9987 DECL_ACCESSORS(internal_field_count, Object)
9989 DECLARE_CAST(ObjectTemplateInfo)
9991 // Dispatched behavior.
9992 DECLARE_PRINTER(ObjectTemplateInfo)
9993 DECLARE_VERIFIER(ObjectTemplateInfo)
9995 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
9996 static const int kInternalFieldCountOffset =
9997 kConstructorOffset + kPointerSize;
9998 static const int kSize = kInternalFieldCountOffset + kPointerSize;
10002 class TypeSwitchInfo: public Struct {
10004 DECL_ACCESSORS(types, Object)
10006 DECLARE_CAST(TypeSwitchInfo)
10008 // Dispatched behavior.
10009 DECLARE_PRINTER(TypeSwitchInfo)
10010 DECLARE_VERIFIER(TypeSwitchInfo)
10012 static const int kTypesOffset = Struct::kHeaderSize;
10013 static const int kSize = kTypesOffset + kPointerSize;
10017 // The DebugInfo class holds additional information for a function being
10019 class DebugInfo: public Struct {
10021 // The shared function info for the source being debugged.
10022 DECL_ACCESSORS(shared, SharedFunctionInfo)
10023 // Code object for the patched code. This code object is the code object
10024 // currently active for the function.
10025 DECL_ACCESSORS(code, Code)
10026 // Fixed array holding status information for each active break point.
10027 DECL_ACCESSORS(break_points, FixedArray)
10029 // Check if there is a break point at a code position.
10030 bool HasBreakPoint(int code_position);
10031 // Get the break point info object for a code position.
10032 Object* GetBreakPointInfo(int code_position);
10033 // Clear a break point.
10034 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
10036 Handle<Object> break_point_object);
10037 // Set a break point.
10038 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
10039 int source_position, int statement_position,
10040 Handle<Object> break_point_object);
10041 // Get the break point objects for a code position.
10042 Handle<Object> GetBreakPointObjects(int code_position);
10043 // Find the break point info holding this break point object.
10044 static Handle<Object> FindBreakPointInfo(Handle<DebugInfo> debug_info,
10045 Handle<Object> break_point_object);
10046 // Get the number of break points for this function.
10047 int GetBreakPointCount();
10049 DECLARE_CAST(DebugInfo)
10051 // Dispatched behavior.
10052 DECLARE_PRINTER(DebugInfo)
10053 DECLARE_VERIFIER(DebugInfo)
10055 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
10056 static const int kCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
10057 static const int kBreakPointsStateIndex = kCodeIndex + kPointerSize;
10058 static const int kSize = kBreakPointsStateIndex + kPointerSize;
10060 static const int kEstimatedNofBreakPointsInFunction = 16;
10063 static const int kNoBreakPointInfo = -1;
10065 // Lookup the index in the break_points array for a code position.
10066 int GetBreakPointInfoIndex(int code_position);
10068 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
10072 // The BreakPointInfo class holds information for break points set in a
10073 // function. The DebugInfo object holds a BreakPointInfo object for each code
10074 // position with one or more break points.
10075 class BreakPointInfo: public Struct {
10077 // The position in the code for the break point.
10078 DECL_ACCESSORS(code_position, Smi)
10079 // The position in the source for the break position.
10080 DECL_ACCESSORS(source_position, Smi)
10081 // The position in the source for the last statement before this break
10083 DECL_ACCESSORS(statement_position, Smi)
10084 // List of related JavaScript break points.
10085 DECL_ACCESSORS(break_point_objects, Object)
10087 // Removes a break point.
10088 static void ClearBreakPoint(Handle<BreakPointInfo> info,
10089 Handle<Object> break_point_object);
10090 // Set a break point.
10091 static void SetBreakPoint(Handle<BreakPointInfo> info,
10092 Handle<Object> break_point_object);
10093 // Check if break point info has this break point object.
10094 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
10095 Handle<Object> break_point_object);
10096 // Get the number of break points for this code position.
10097 int GetBreakPointCount();
10099 DECLARE_CAST(BreakPointInfo)
10101 // Dispatched behavior.
10102 DECLARE_PRINTER(BreakPointInfo)
10103 DECLARE_VERIFIER(BreakPointInfo)
10105 static const int kCodePositionIndex = Struct::kHeaderSize;
10106 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
10107 static const int kStatementPositionIndex =
10108 kSourcePositionIndex + kPointerSize;
10109 static const int kBreakPointObjectsIndex =
10110 kStatementPositionIndex + kPointerSize;
10111 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
10114 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
10118 #undef DECL_BOOLEAN_ACCESSORS
10119 #undef DECL_ACCESSORS
10120 #undef DECLARE_CAST
10121 #undef DECLARE_VERIFIER
10123 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
10124 V(kStringTable, "string_table", "(Internalized strings)") \
10125 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
10126 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
10127 V(kSmiRootList, "smi_root_list", "(Smi roots)") \
10128 V(kInternalizedString, "internalized_string", "(Internal string)") \
10129 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
10130 V(kTop, "top", "(Isolate)") \
10131 V(kRelocatable, "relocatable", "(Relocatable)") \
10132 V(kDebug, "debug", "(Debugger)") \
10133 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
10134 V(kHandleScope, "handlescope", "(Handle scope)") \
10135 V(kBuiltins, "builtins", "(Builtins)") \
10136 V(kGlobalHandles, "globalhandles", "(Global handles)") \
10137 V(kEternalHandles, "eternalhandles", "(Eternal handles)") \
10138 V(kThreadManager, "threadmanager", "(Thread manager)") \
10139 V(kStrongRoots, "strong roots", "(Strong roots)") \
10140 V(kExtensions, "Extensions", "(Extensions)")
10142 class VisitorSynchronization : public AllStatic {
10144 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
10146 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
10149 #undef DECLARE_ENUM
10151 static const char* const kTags[kNumberOfSyncTags];
10152 static const char* const kTagNames[kNumberOfSyncTags];
10155 // Abstract base class for visiting, and optionally modifying, the
10156 // pointers contained in Objects. Used in GC and serialization/deserialization.
10157 class ObjectVisitor BASE_EMBEDDED {
10159 virtual ~ObjectVisitor() {}
10161 // Visits a contiguous arrays of pointers in the half-open range
10162 // [start, end). Any or all of the values may be modified on return.
10163 virtual void VisitPointers(Object** start, Object** end) = 0;
10165 // Handy shorthand for visiting a single pointer.
10166 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
10168 // Visit weak next_code_link in Code object.
10169 virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
10171 // To allow lazy clearing of inline caches the visitor has
10172 // a rich interface for iterating over Code objects..
10174 // Visits a code target in the instruction stream.
10175 virtual void VisitCodeTarget(RelocInfo* rinfo);
10177 // Visits a code entry in a JS function.
10178 virtual void VisitCodeEntry(Address entry_address);
10180 // Visits a global property cell reference in the instruction stream.
10181 virtual void VisitCell(RelocInfo* rinfo);
10183 // Visits a runtime entry in the instruction stream.
10184 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
10186 // Visits the resource of an one-byte or two-byte string.
10187 virtual void VisitExternalOneByteString(
10188 v8::String::ExternalOneByteStringResource** resource) {}
10189 virtual void VisitExternalTwoByteString(
10190 v8::String::ExternalStringResource** resource) {}
10192 // Visits a debug call target in the instruction stream.
10193 virtual void VisitDebugTarget(RelocInfo* rinfo);
10195 // Visits the byte sequence in a function's prologue that contains information
10196 // about the code's age.
10197 virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
10199 // Visit pointer embedded into a code object.
10200 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
10202 // Visits an external reference embedded into a code object.
10203 virtual void VisitExternalReference(RelocInfo* rinfo);
10205 // Visits an external reference.
10206 virtual void VisitExternalReference(Address* p) {}
10208 // Visits an (encoded) internal reference.
10209 virtual void VisitInternalReference(RelocInfo* rinfo) {}
10211 // Visits a handle that has an embedder-assigned class ID.
10212 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
10214 // Intended for serialization/deserialization checking: insert, or
10215 // check for the presence of, a tag at this position in the stream.
10216 // Also used for marking up GC roots in heap snapshots.
10217 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
10221 class StructBodyDescriptor : public
10222 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
10224 static inline int SizeOf(Map* map, HeapObject* object);
10228 // BooleanBit is a helper class for setting and getting a bit in an
10230 class BooleanBit : public AllStatic {
10232 static inline bool get(Smi* smi, int bit_position) {
10233 return get(smi->value(), bit_position);
10236 static inline bool get(int value, int bit_position) {
10237 return (value & (1 << bit_position)) != 0;
10240 static inline Smi* set(Smi* smi, int bit_position, bool v) {
10241 return Smi::FromInt(set(smi->value(), bit_position, v));
10244 static inline int set(int value, int bit_position, bool v) {
10246 value |= (1 << bit_position);
10248 value &= ~(1 << bit_position);
10254 } } // namespace v8::internal
10256 #endif // V8_OBJECTS_H_