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() {
1063 if (!FLAG_track_fields) return Representation::Tagged();
1065 return Representation::Smi();
1066 } else if (FLAG_track_double_fields && IsHeapNumber()) {
1067 return Representation::Double();
1068 } else if (FLAG_track_computed_fields && IsUninitialized()) {
1069 return Representation::None();
1070 } else if (FLAG_track_heap_object_fields) {
1071 DCHECK(IsHeapObject());
1072 return Representation::HeapObject();
1074 return Representation::Tagged();
1078 inline ElementsKind OptimalElementsKind() {
1079 if (IsSmi()) return FAST_SMI_ELEMENTS;
1080 if (IsNumber()) return FAST_DOUBLE_ELEMENTS;
1081 return FAST_ELEMENTS;
1084 inline bool FitsRepresentation(Representation representation) {
1085 if (FLAG_track_fields && representation.IsNone()) {
1087 } else if (FLAG_track_fields && representation.IsSmi()) {
1089 } else if (FLAG_track_double_fields && representation.IsDouble()) {
1090 return IsMutableHeapNumber() || IsNumber();
1091 } else if (FLAG_track_heap_object_fields && representation.IsHeapObject()) {
1092 return IsHeapObject();
1097 // Checks whether two valid primitive encodings of a property name resolve to
1098 // the same logical property. E.g., the smi 1, the string "1" and the double
1099 // 1 all refer to the same property, so this helper will return true.
1100 inline bool KeyEquals(Object* other);
1102 Handle<HeapType> OptimalType(Isolate* isolate, Representation representation);
1104 inline static Handle<Object> NewStorageFor(Isolate* isolate,
1105 Handle<Object> object,
1106 Representation representation);
1108 inline static Handle<Object> WrapForRead(Isolate* isolate,
1109 Handle<Object> object,
1110 Representation representation);
1112 // Returns true if the object is of the correct type to be used as a
1113 // implementation of a JSObject's elements.
1114 inline bool HasValidElements();
1116 inline bool HasSpecificClassOf(String* name);
1118 bool BooleanValue(); // ECMA-262 9.2.
1120 // Convert to a JSObject if needed.
1121 // native_context is used when creating wrapper object.
1122 static inline MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1123 Handle<Object> object);
1124 static MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1125 Handle<Object> object,
1126 Handle<Context> context);
1128 MUST_USE_RESULT static MaybeHandle<Object> GetProperty(
1129 LookupIterator* it, LanguageMode language_mode = SLOPPY);
1131 // Implementation of [[Put]], ECMA-262 5th edition, section 8.12.5.
1132 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1133 Handle<Object> object, Handle<Name> name, Handle<Object> value,
1134 LanguageMode language_mode,
1135 StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
1137 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1138 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1139 StoreFromKeyed store_mode);
1141 MUST_USE_RESULT static MaybeHandle<Object> SetSuperProperty(
1142 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1143 StoreFromKeyed store_mode);
1145 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1146 LookupIterator* it, LanguageMode language_mode);
1147 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1148 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1149 LanguageMode language_mode);
1150 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1151 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1152 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1153 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1154 Handle<Object> value, LanguageMode language_mode);
1155 MUST_USE_RESULT static MaybeHandle<Object> RedefineNonconfigurableProperty(
1156 Isolate* isolate, Handle<Object> name, Handle<Object> value,
1157 LanguageMode language_mode);
1158 MUST_USE_RESULT static MaybeHandle<Object> SetDataProperty(
1159 LookupIterator* it, Handle<Object> value);
1160 MUST_USE_RESULT static MaybeHandle<Object> AddDataProperty(
1161 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1162 LanguageMode language_mode, StoreFromKeyed store_mode);
1163 MUST_USE_RESULT static inline MaybeHandle<Object> GetPropertyOrElement(
1164 Handle<Object> object, Handle<Name> name,
1165 LanguageMode language_mode = SLOPPY);
1166 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1167 Isolate* isolate, Handle<Object> object, const char* key,
1168 LanguageMode language_mode = SLOPPY);
1169 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1170 Handle<Object> object, Handle<Name> name,
1171 LanguageMode language_mode = SLOPPY);
1173 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithAccessor(
1174 LookupIterator* it, LanguageMode language_mode);
1175 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithAccessor(
1176 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1178 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithDefinedGetter(
1179 Handle<Object> receiver,
1180 Handle<JSReceiver> getter);
1181 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithDefinedSetter(
1182 Handle<Object> receiver,
1183 Handle<JSReceiver> setter,
1184 Handle<Object> value);
1186 MUST_USE_RESULT static inline MaybeHandle<Object> GetElement(
1187 Isolate* isolate, Handle<Object> object, uint32_t index,
1188 LanguageMode language_mode = SLOPPY);
1190 MUST_USE_RESULT static inline MaybeHandle<Object> SetElement(
1191 Isolate* isolate, Handle<Object> object, uint32_t index,
1192 Handle<Object> value, LanguageMode language_mode);
1194 static inline Handle<Object> GetPrototypeSkipHiddenPrototypes(
1195 Isolate* isolate, Handle<Object> receiver);
1197 // Returns the permanent hash code associated with this object. May return
1198 // undefined if not yet created.
1201 // Returns undefined for JSObjects, but returns the hash code for simple
1202 // objects. This avoids a double lookup in the cases where we know we will
1203 // add the hash to the JSObject if it does not already exist.
1204 Object* GetSimpleHash();
1206 // Returns the permanent hash code associated with this object depending on
1207 // the actual object type. May create and store a hash code if needed and none
1209 static Handle<Smi> GetOrCreateHash(Isolate* isolate, Handle<Object> object);
1211 // Checks whether this object has the same value as the given one. This
1212 // function is implemented according to ES5, section 9.12 and can be used
1213 // to implement the Harmony "egal" function.
1214 bool SameValue(Object* other);
1216 // Checks whether this object has the same value as the given one.
1217 // +0 and -0 are treated equal. Everything else is the same as SameValue.
1218 // This function is implemented according to ES6, section 7.2.4 and is used
1219 // by ES6 Map and Set.
1220 bool SameValueZero(Object* other);
1222 // Tries to convert an object to an array length. Returns true and sets the
1223 // output parameter if it succeeds.
1224 inline bool ToArrayLength(uint32_t* index);
1226 // Tries to convert an object to an array index. Returns true and sets the
1227 // output parameter if it succeeds. Equivalent to ToArrayLength, but does not
1228 // allow kMaxUInt32.
1229 inline bool ToArrayIndex(uint32_t* index);
1231 // Returns true if this is a JSValue containing a string and the index is
1232 // < the length of the string. Used to implement [] on strings.
1233 inline bool IsStringObjectWithCharacterAt(uint32_t index);
1235 DECLARE_VERIFIER(Object)
1237 // Verify a pointer is a valid object pointer.
1238 static void VerifyPointer(Object* p);
1241 inline void VerifyApiCallResultType();
1243 // Prints this object without details.
1244 void ShortPrint(FILE* out = stdout);
1246 // Prints this object without details to a message accumulator.
1247 void ShortPrint(StringStream* accumulator);
1249 void ShortPrint(std::ostream& os); // NOLINT
1251 DECLARE_CAST(Object)
1253 // Layout description.
1254 static const int kHeaderSize = 0; // Object does not take up any space.
1257 // For our gdb macros, we should perhaps change these in the future.
1260 // Prints this object with details.
1261 void Print(std::ostream& os); // NOLINT
1263 void Print() { ShortPrint(); }
1264 void Print(std::ostream& os) { ShortPrint(os); } // NOLINT
1268 friend class LookupIterator;
1269 friend class PrototypeIterator;
1271 // Return the map of the root of object's prototype chain.
1272 Map* GetRootMap(Isolate* isolate);
1274 // Helper for SetProperty and SetSuperProperty.
1275 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyInternal(
1276 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1277 StoreFromKeyed store_mode, bool* found);
1279 DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
1284 explicit Brief(const Object* const v) : value(v) {}
1285 const Object* value;
1289 std::ostream& operator<<(std::ostream& os, const Brief& v);
1292 // Smi represents integer Numbers that can be stored in 31 bits.
1293 // Smis are immediate which means they are NOT allocated in the heap.
1294 // The this pointer has the following format: [31 bit signed int] 0
1295 // For long smis it has the following format:
1296 // [32 bit signed int] [31 bits zero padding] 0
1297 // Smi stands for small integer.
1298 class Smi: public Object {
1300 // Returns the integer value.
1301 inline int value() const;
1303 // Convert a value to a Smi object.
1304 static inline Smi* FromInt(int value);
1306 static inline Smi* FromIntptr(intptr_t value);
1308 // Returns whether value can be represented in a Smi.
1309 static inline bool IsValid(intptr_t value);
1313 // Dispatched behavior.
1314 void SmiPrint(std::ostream& os) const; // NOLINT
1315 DECLARE_VERIFIER(Smi)
1317 static const int kMinValue =
1318 (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1319 static const int kMaxValue = -(kMinValue + 1);
1322 DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1326 // Heap objects typically have a map pointer in their first word. However,
1327 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1328 // encoded in the first word. The class MapWord is an abstraction of the
1329 // value in a heap object's first word.
1330 class MapWord BASE_EMBEDDED {
1332 // Normal state: the map word contains a map pointer.
1334 // Create a map word from a map pointer.
1335 static inline MapWord FromMap(const Map* map);
1337 // View this map word as a map pointer.
1338 inline Map* ToMap();
1341 // Scavenge collection: the map word of live objects in the from space
1342 // contains a forwarding address (a heap object pointer in the to space).
1344 // True if this map word is a forwarding address for a scavenge
1345 // collection. Only valid during a scavenge collection (specifically,
1346 // when all map words are heap object pointers, i.e. not during a full GC).
1347 inline bool IsForwardingAddress();
1349 // Create a map word from a forwarding address.
1350 static inline MapWord FromForwardingAddress(HeapObject* object);
1352 // View this map word as a forwarding address.
1353 inline HeapObject* ToForwardingAddress();
1355 static inline MapWord FromRawValue(uintptr_t value) {
1356 return MapWord(value);
1359 inline uintptr_t ToRawValue() {
1364 // HeapObject calls the private constructor and directly reads the value.
1365 friend class HeapObject;
1367 explicit MapWord(uintptr_t value) : value_(value) {}
1373 // The content of an heap object (except for the map pointer). kTaggedValues
1374 // objects can contain both heap pointers and Smis, kMixedValues can contain
1375 // heap pointers, Smis, and raw values (e.g. doubles or strings), and kRawValues
1376 // objects can contain raw values and Smis.
1377 enum class HeapObjectContents { kTaggedValues, kMixedValues, kRawValues };
1380 // HeapObject is the superclass for all classes describing heap allocated
1382 class HeapObject: public Object {
1384 // [map]: Contains a map which contains the object's reflective
1386 inline Map* map() const;
1387 inline void set_map(Map* value);
1388 // The no-write-barrier version. This is OK if the object is white and in
1389 // new space, or if the value is an immortal immutable object, like the maps
1390 // of primitive (non-JS) objects like strings, heap numbers etc.
1391 inline void set_map_no_write_barrier(Map* value);
1393 // Get the map using acquire load.
1394 inline Map* synchronized_map();
1395 inline MapWord synchronized_map_word() const;
1397 // Set the map using release store
1398 inline void synchronized_set_map(Map* value);
1399 inline void synchronized_set_map_no_write_barrier(Map* value);
1400 inline void synchronized_set_map_word(MapWord map_word);
1402 // During garbage collection, the map word of a heap object does not
1403 // necessarily contain a map pointer.
1404 inline MapWord map_word() const;
1405 inline void set_map_word(MapWord map_word);
1407 // The Heap the object was allocated in. Used also to access Isolate.
1408 inline Heap* GetHeap() const;
1410 // Convenience method to get current isolate.
1411 inline Isolate* GetIsolate() const;
1413 // Converts an address to a HeapObject pointer.
1414 static inline HeapObject* FromAddress(Address address);
1416 // Returns the address of this HeapObject.
1417 inline Address address();
1419 // Iterates over pointers contained in the object (including the Map)
1420 void Iterate(ObjectVisitor* v);
1422 // Iterates over all pointers contained in the object except the
1423 // first map pointer. The object type is given in the first
1424 // parameter. This function does not access the map pointer in the
1425 // object, and so is safe to call while the map pointer is modified.
1426 void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1428 // Returns the heap object's size in bytes
1431 // Indicates what type of values this heap object may contain.
1432 inline HeapObjectContents ContentType();
1434 // Given a heap object's map pointer, returns the heap size in bytes
1435 // Useful when the map pointer field is used for other purposes.
1437 inline int SizeFromMap(Map* map);
1439 // Returns the field at offset in obj, as a read/write Object* reference.
1440 // Does no checking, and is safe to use during GC, while maps are invalid.
1441 // Does not invoke write barrier, so should only be assigned to
1442 // during marking GC.
1443 static inline Object** RawField(HeapObject* obj, int offset);
1445 // Adds the |code| object related to |name| to the code cache of this map. If
1446 // this map is a dictionary map that is shared, the map copied and installed
1448 static void UpdateMapCodeCache(Handle<HeapObject> object,
1452 DECLARE_CAST(HeapObject)
1454 // Return the write barrier mode for this. Callers of this function
1455 // must be able to present a reference to an DisallowHeapAllocation
1456 // object as a sign that they are not going to use this function
1457 // from code that allocates and thus invalidates the returned write
1459 inline WriteBarrierMode GetWriteBarrierMode(
1460 const DisallowHeapAllocation& promise);
1462 // Dispatched behavior.
1463 void HeapObjectShortPrint(std::ostream& os); // NOLINT
1465 void PrintHeader(std::ostream& os, const char* id); // NOLINT
1467 DECLARE_PRINTER(HeapObject)
1468 DECLARE_VERIFIER(HeapObject)
1470 inline void VerifyObjectField(int offset);
1471 inline void VerifySmiField(int offset);
1473 // Verify a pointer is a valid HeapObject pointer that points to object
1474 // areas in the heap.
1475 static void VerifyHeapPointer(Object* p);
1478 inline AllocationAlignment RequiredAlignment();
1480 // Layout description.
1481 // First field in a heap object is map.
1482 static const int kMapOffset = Object::kHeaderSize;
1483 static const int kHeaderSize = kMapOffset + kPointerSize;
1485 STATIC_ASSERT(kMapOffset == Internals::kHeapObjectMapOffset);
1488 // helpers for calling an ObjectVisitor to iterate over pointers in the
1489 // half-open range [start, end) specified as integer offsets
1490 inline void IteratePointers(ObjectVisitor* v, int start, int end);
1491 // as above, for the single element at "offset"
1492 inline void IteratePointer(ObjectVisitor* v, int offset);
1493 // as above, for the next code link of a code object.
1494 inline void IterateNextCodeLink(ObjectVisitor* v, int offset);
1497 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1501 // This class describes a body of an object of a fixed size
1502 // in which all pointer fields are located in the [start_offset, end_offset)
1504 template<int start_offset, int end_offset, int size>
1505 class FixedBodyDescriptor {
1507 static const int kStartOffset = start_offset;
1508 static const int kEndOffset = end_offset;
1509 static const int kSize = size;
1511 static inline void IterateBody(HeapObject* obj, ObjectVisitor* v);
1513 template<typename StaticVisitor>
1514 static inline void IterateBody(HeapObject* obj) {
1515 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1516 HeapObject::RawField(obj, end_offset));
1521 // This class describes a body of an object of a variable size
1522 // in which all pointer fields are located in the [start_offset, object_size)
1524 template<int start_offset>
1525 class FlexibleBodyDescriptor {
1527 static const int kStartOffset = start_offset;
1529 static inline void IterateBody(HeapObject* obj,
1533 template<typename StaticVisitor>
1534 static inline void IterateBody(HeapObject* obj, int object_size) {
1535 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1536 HeapObject::RawField(obj, object_size));
1541 // The HeapNumber class describes heap allocated numbers that cannot be
1542 // represented in a Smi (small integer)
1543 class HeapNumber: public HeapObject {
1545 // [value]: number value.
1546 inline double value() const;
1547 inline void set_value(double value);
1549 DECLARE_CAST(HeapNumber)
1551 // Dispatched behavior.
1552 bool HeapNumberBooleanValue();
1554 void HeapNumberPrint(std::ostream& os); // NOLINT
1555 DECLARE_VERIFIER(HeapNumber)
1557 inline int get_exponent();
1558 inline int get_sign();
1560 // Layout description.
1561 static const int kValueOffset = HeapObject::kHeaderSize;
1562 // IEEE doubles are two 32 bit words. The first is just mantissa, the second
1563 // is a mixture of sign, exponent and mantissa. The offsets of two 32 bit
1564 // words within double numbers are endian dependent and they are set
1566 #if defined(V8_TARGET_LITTLE_ENDIAN)
1567 static const int kMantissaOffset = kValueOffset;
1568 static const int kExponentOffset = kValueOffset + 4;
1569 #elif defined(V8_TARGET_BIG_ENDIAN)
1570 static const int kMantissaOffset = kValueOffset + 4;
1571 static const int kExponentOffset = kValueOffset;
1573 #error Unknown byte ordering
1576 static const int kSize = kValueOffset + kDoubleSize;
1577 static const uint32_t kSignMask = 0x80000000u;
1578 static const uint32_t kExponentMask = 0x7ff00000u;
1579 static const uint32_t kMantissaMask = 0xfffffu;
1580 static const int kMantissaBits = 52;
1581 static const int kExponentBits = 11;
1582 static const int kExponentBias = 1023;
1583 static const int kExponentShift = 20;
1584 static const int kInfinityOrNanExponent =
1585 (kExponentMask >> kExponentShift) - kExponentBias;
1586 static const int kMantissaBitsInTopWord = 20;
1587 static const int kNonMantissaBitsInTopWord = 12;
1590 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
1594 // The Simd128Value class describes heap allocated 128 bit SIMD values.
1595 class Simd128Value : public HeapObject {
1597 DECLARE_CAST(Simd128Value)
1599 DECLARE_PRINTER(Simd128Value)
1600 DECLARE_VERIFIER(Simd128Value)
1602 // Checks that another instance is bit-wise equal.
1603 bool BitwiseEquals(const Simd128Value* other) const;
1604 // Computes a hash from the 128 bit value, viewed as 4 32-bit integers.
1605 uint32_t Hash() const;
1606 // Copies the 16 bytes of SIMD data to the destination address.
1607 void CopyBits(void* destination) const;
1609 // Layout description.
1610 static const int kValueOffset = HeapObject::kHeaderSize;
1611 static const int kSize = kValueOffset + kSimd128Size;
1614 DISALLOW_IMPLICIT_CONSTRUCTORS(Simd128Value);
1618 // V has parameters (TYPE, Type, type, lane count, lane type)
1619 #define SIMD128_TYPES(V) \
1620 V(FLOAT32X4, Float32x4, float32x4, 4, float) \
1621 V(INT32X4, Int32x4, int32x4, 4, int32_t) \
1622 V(BOOL32X4, Bool32x4, bool32x4, 4, bool) \
1623 V(INT16X8, Int16x8, int16x8, 8, int16_t) \
1624 V(BOOL16X8, Bool16x8, bool16x8, 8, bool) \
1625 V(INT8X16, Int8x16, int8x16, 16, int8_t) \
1626 V(BOOL8X16, Bool8x16, bool8x16, 16, bool)
1628 #define SIMD128_VALUE_CLASS(TYPE, Type, type, lane_count, lane_type) \
1629 class Type final : public Simd128Value { \
1631 inline lane_type get_lane(int lane) const; \
1632 inline void set_lane(int lane, lane_type value); \
1634 DECLARE_CAST(Type) \
1636 DECLARE_PRINTER(Type) \
1639 DISALLOW_IMPLICIT_CONSTRUCTORS(Type); \
1641 SIMD128_TYPES(SIMD128_VALUE_CLASS)
1642 #undef SIMD128_VALUE_CLASS
1645 enum EnsureElementsMode {
1646 DONT_ALLOW_DOUBLE_ELEMENTS,
1647 ALLOW_COPIED_DOUBLE_ELEMENTS,
1648 ALLOW_CONVERTED_DOUBLE_ELEMENTS
1652 // Indicator for one component of an AccessorPair.
1653 enum AccessorComponent {
1659 // JSReceiver includes types on which properties can be defined, i.e.,
1660 // JSObject and JSProxy.
1661 class JSReceiver: public HeapObject {
1663 DECLARE_CAST(JSReceiver)
1665 // Implementation of [[HasProperty]], ECMA-262 5th edition, section 8.12.6.
1666 MUST_USE_RESULT static inline Maybe<bool> HasProperty(
1667 Handle<JSReceiver> object, Handle<Name> name);
1668 MUST_USE_RESULT static inline Maybe<bool> HasOwnProperty(Handle<JSReceiver>,
1670 MUST_USE_RESULT static inline Maybe<bool> HasElement(
1671 Handle<JSReceiver> object, uint32_t index);
1672 MUST_USE_RESULT static inline Maybe<bool> HasOwnElement(
1673 Handle<JSReceiver> object, uint32_t index);
1675 // Implementation of [[Delete]], ECMA-262 5th edition, section 8.12.7.
1676 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyOrElement(
1677 Handle<JSReceiver> object, Handle<Name> name,
1678 LanguageMode language_mode = SLOPPY);
1679 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1680 Handle<JSReceiver> object, Handle<Name> name,
1681 LanguageMode language_mode = SLOPPY);
1682 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1683 LookupIterator* it, LanguageMode language_mode);
1684 MUST_USE_RESULT static MaybeHandle<Object> DeleteElement(
1685 Handle<JSReceiver> object, uint32_t index,
1686 LanguageMode language_mode = SLOPPY);
1688 // Tests for the fast common case for property enumeration.
1689 bool IsSimpleEnum();
1691 // Returns the class name ([[Class]] property in the specification).
1692 String* class_name();
1694 // Returns the constructor name (the name (possibly, inferred name) of the
1695 // function that was used to instantiate the object).
1696 String* constructor_name();
1698 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetPropertyAttributes(
1699 Handle<JSReceiver> object, Handle<Name> name);
1700 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1701 GetOwnPropertyAttributes(Handle<JSReceiver> object, Handle<Name> name);
1703 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetElementAttributes(
1704 Handle<JSReceiver> object, uint32_t index);
1705 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1706 GetOwnElementAttributes(Handle<JSReceiver> object, uint32_t index);
1708 MUST_USE_RESULT static Maybe<PropertyAttributes> GetPropertyAttributes(
1709 LookupIterator* it);
1712 static Handle<Object> GetDataProperty(Handle<JSReceiver> object,
1714 static Handle<Object> GetDataProperty(LookupIterator* it);
1717 // Retrieves a permanent object identity hash code. The undefined value might
1718 // be returned in case no hash was created yet.
1719 inline Object* GetIdentityHash();
1721 // Retrieves a permanent object identity hash code. May create and store a
1722 // hash code if needed and none exists.
1723 inline static Handle<Smi> GetOrCreateIdentityHash(
1724 Handle<JSReceiver> object);
1726 enum KeyCollectionType { OWN_ONLY, INCLUDE_PROTOS };
1728 // Computes the enumerable keys for a JSObject. Used for implementing
1729 // "for (n in object) { }".
1730 MUST_USE_RESULT static MaybeHandle<FixedArray> GetKeys(
1731 Handle<JSReceiver> object,
1732 KeyCollectionType type);
1735 DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
1739 // The JSObject describes real heap allocated JavaScript objects with
1741 // Note that the map of JSObject changes during execution to enable inline
1743 class JSObject: public JSReceiver {
1745 // [properties]: Backing storage for properties.
1746 // properties is a FixedArray in the fast case and a Dictionary in the
1748 DECL_ACCESSORS(properties, FixedArray) // Get and set fast properties.
1749 inline void initialize_properties();
1750 inline bool HasFastProperties();
1751 // Gets slow properties for non-global objects.
1752 inline NameDictionary* property_dictionary();
1753 // Gets global object properties.
1754 inline GlobalDictionary* global_dictionary();
1756 // [elements]: The elements (properties with names that are integers).
1758 // Elements can be in two general modes: fast and slow. Each mode
1759 // corrensponds to a set of object representations of elements that
1760 // have something in common.
1762 // In the fast mode elements is a FixedArray and so each element can
1763 // be quickly accessed. This fact is used in the generated code. The
1764 // elements array can have one of three maps in this mode:
1765 // fixed_array_map, sloppy_arguments_elements_map or
1766 // fixed_cow_array_map (for copy-on-write arrays). In the latter case
1767 // the elements array may be shared by a few objects and so before
1768 // writing to any element the array must be copied. Use
1769 // EnsureWritableFastElements in this case.
1771 // In the slow mode the elements is either a NumberDictionary, a
1772 // FixedArray parameter map for a (sloppy) arguments object.
1773 DECL_ACCESSORS(elements, FixedArrayBase)
1774 inline void initialize_elements();
1775 static void ResetElements(Handle<JSObject> object);
1776 static inline void SetMapAndElements(Handle<JSObject> object,
1778 Handle<FixedArrayBase> elements);
1779 inline ElementsKind GetElementsKind();
1780 ElementsAccessor* GetElementsAccessor();
1781 // Returns true if an object has elements of FAST_SMI_ELEMENTS ElementsKind.
1782 inline bool HasFastSmiElements();
1783 // Returns true if an object has elements of FAST_ELEMENTS ElementsKind.
1784 inline bool HasFastObjectElements();
1785 // Returns true if an object has elements of FAST_ELEMENTS or
1786 // FAST_SMI_ONLY_ELEMENTS.
1787 inline bool HasFastSmiOrObjectElements();
1788 // Returns true if an object has any of the fast elements kinds.
1789 inline bool HasFastElements();
1790 // Returns true if an object has elements of FAST_DOUBLE_ELEMENTS
1792 inline bool HasFastDoubleElements();
1793 // Returns true if an object has elements of FAST_HOLEY_*_ELEMENTS
1795 inline bool HasFastHoleyElements();
1796 inline bool HasSloppyArgumentsElements();
1797 inline bool HasDictionaryElements();
1799 inline bool HasFixedTypedArrayElements();
1801 inline bool HasFixedUint8ClampedElements();
1802 inline bool HasFixedArrayElements();
1803 inline bool HasFixedInt8Elements();
1804 inline bool HasFixedUint8Elements();
1805 inline bool HasFixedInt16Elements();
1806 inline bool HasFixedUint16Elements();
1807 inline bool HasFixedInt32Elements();
1808 inline bool HasFixedUint32Elements();
1809 inline bool HasFixedFloat32Elements();
1810 inline bool HasFixedFloat64Elements();
1812 inline bool HasFastArgumentsElements();
1813 inline bool HasSlowArgumentsElements();
1814 inline SeededNumberDictionary* element_dictionary(); // Gets slow elements.
1816 // Requires: HasFastElements().
1817 static Handle<FixedArray> EnsureWritableFastElements(
1818 Handle<JSObject> object);
1820 // Collects elements starting at index 0.
1821 // Undefined values are placed after non-undefined values.
1822 // Returns the number of non-undefined values.
1823 static Handle<Object> PrepareElementsForSort(Handle<JSObject> object,
1825 // As PrepareElementsForSort, but only on objects where elements is
1826 // a dictionary, and it will stay a dictionary. Collates undefined and
1827 // unexisting elements below limit from position zero of the elements.
1828 static Handle<Object> PrepareSlowElementsForSort(Handle<JSObject> object,
1831 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithInterceptor(
1832 LookupIterator* it, Handle<Object> value);
1834 // SetLocalPropertyIgnoreAttributes converts callbacks to fields. We need to
1835 // grant an exemption to ExecutableAccessor callbacks in some cases.
1836 enum ExecutableAccessorInfoHandling { DEFAULT_HANDLING, DONT_FORCE_FIELD };
1838 MUST_USE_RESULT static MaybeHandle<Object> DefineOwnPropertyIgnoreAttributes(
1839 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1840 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1842 MUST_USE_RESULT static MaybeHandle<Object> SetOwnPropertyIgnoreAttributes(
1843 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1844 PropertyAttributes attributes,
1845 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1847 MUST_USE_RESULT static MaybeHandle<Object> SetOwnElementIgnoreAttributes(
1848 Handle<JSObject> object, uint32_t index, Handle<Object> value,
1849 PropertyAttributes attributes,
1850 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1852 // Equivalent to one of the above depending on whether |name| can be converted
1853 // to an array index.
1854 MUST_USE_RESULT static MaybeHandle<Object>
1855 DefinePropertyOrElementIgnoreAttributes(
1856 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1857 PropertyAttributes attributes = NONE,
1858 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1860 // Adds or reconfigures a property to attributes NONE. It will fail when it
1862 MUST_USE_RESULT static Maybe<bool> CreateDataProperty(LookupIterator* it,
1863 Handle<Object> value);
1865 static void AddProperty(Handle<JSObject> object, Handle<Name> name,
1866 Handle<Object> value, PropertyAttributes attributes);
1868 MUST_USE_RESULT static MaybeHandle<Object> AddDataElement(
1869 Handle<JSObject> receiver, uint32_t index, Handle<Object> value,
1870 PropertyAttributes attributes);
1872 // Extend the receiver with a single fast property appeared first in the
1873 // passed map. This also extends the property backing store if necessary.
1874 static void AllocateStorageForMap(Handle<JSObject> object, Handle<Map> map);
1876 // Migrates the given object to a map whose field representations are the
1877 // lowest upper bound of all known representations for that field.
1878 static void MigrateInstance(Handle<JSObject> instance);
1880 // Migrates the given object only if the target map is already available,
1881 // or returns false if such a map is not yet available.
1882 static bool TryMigrateInstance(Handle<JSObject> instance);
1884 // Sets the property value in a normalized object given (key, value, details).
1885 // Handles the special representation of JS global objects.
1886 static void SetNormalizedProperty(Handle<JSObject> object, Handle<Name> name,
1887 Handle<Object> value,
1888 PropertyDetails details);
1889 static void SetDictionaryElement(Handle<JSObject> object, uint32_t index,
1890 Handle<Object> value,
1891 PropertyAttributes attributes);
1892 static void SetDictionaryArgumentsElement(Handle<JSObject> object,
1894 Handle<Object> value,
1895 PropertyAttributes attributes);
1897 static void OptimizeAsPrototype(Handle<JSObject> object,
1898 PrototypeOptimizationMode mode);
1899 static void ReoptimizeIfPrototype(Handle<JSObject> object);
1900 static void LazyRegisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1901 static bool UnregisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1902 static void InvalidatePrototypeChains(Map* map);
1904 // Alternative implementation of WeakFixedArray::NullCallback.
1905 class PrototypeRegistryCompactionCallback {
1907 static void Callback(Object* value, int old_index, int new_index);
1910 // Retrieve interceptors.
1911 InterceptorInfo* GetNamedInterceptor();
1912 InterceptorInfo* GetIndexedInterceptor();
1914 // Used from JSReceiver.
1915 MUST_USE_RESULT static Maybe<PropertyAttributes>
1916 GetPropertyAttributesWithInterceptor(LookupIterator* it);
1917 MUST_USE_RESULT static Maybe<PropertyAttributes>
1918 GetPropertyAttributesWithFailedAccessCheck(LookupIterator* it);
1920 // Retrieves an AccessorPair property from the given object. Might return
1921 // undefined if the property doesn't exist or is of a different kind.
1922 MUST_USE_RESULT static MaybeHandle<Object> GetAccessor(
1923 Handle<JSObject> object,
1925 AccessorComponent component);
1927 // Defines an AccessorPair property on the given object.
1928 // TODO(mstarzinger): Rename to SetAccessor().
1929 static MaybeHandle<Object> DefineAccessor(Handle<JSObject> object,
1931 Handle<Object> getter,
1932 Handle<Object> setter,
1933 PropertyAttributes attributes);
1935 // Defines an AccessorInfo property on the given object.
1936 MUST_USE_RESULT static MaybeHandle<Object> SetAccessor(
1937 Handle<JSObject> object,
1938 Handle<AccessorInfo> info);
1940 // The result must be checked first for exceptions. If there's no exception,
1941 // the output parameter |done| indicates whether the interceptor has a result
1943 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithInterceptor(
1944 LookupIterator* it, bool* done);
1946 // Accessors for hidden properties object.
1948 // Hidden properties are not own properties of the object itself.
1949 // Instead they are stored in an auxiliary structure kept as an own
1950 // property with a special name Heap::hidden_string(). But if the
1951 // receiver is a JSGlobalProxy then the auxiliary object is a property
1952 // of its prototype, and if it's a detached proxy, then you can't have
1953 // hidden properties.
1955 // Sets a hidden property on this object. Returns this object if successful,
1956 // undefined if called on a detached proxy.
1957 static Handle<Object> SetHiddenProperty(Handle<JSObject> object,
1959 Handle<Object> value);
1960 // Gets the value of a hidden property with the given key. Returns the hole
1961 // if the property doesn't exist (or if called on a detached proxy),
1962 // otherwise returns the value set for the key.
1963 Object* GetHiddenProperty(Handle<Name> key);
1964 // Deletes a hidden property. Deleting a non-existing property is
1965 // considered successful.
1966 static void DeleteHiddenProperty(Handle<JSObject> object,
1968 // Returns true if the object has a property with the hidden string as name.
1969 static bool HasHiddenProperties(Handle<JSObject> object);
1971 static void SetIdentityHash(Handle<JSObject> object, Handle<Smi> hash);
1973 static void ValidateElements(Handle<JSObject> object);
1975 // Makes sure that this object can contain HeapObject as elements.
1976 static inline void EnsureCanContainHeapObjectElements(Handle<JSObject> obj);
1978 // Makes sure that this object can contain the specified elements.
1979 static inline void EnsureCanContainElements(
1980 Handle<JSObject> object,
1983 EnsureElementsMode mode);
1984 static inline void EnsureCanContainElements(
1985 Handle<JSObject> object,
1986 Handle<FixedArrayBase> elements,
1988 EnsureElementsMode mode);
1989 static void EnsureCanContainElements(
1990 Handle<JSObject> object,
1991 Arguments* arguments,
1994 EnsureElementsMode mode);
1996 // Would we convert a fast elements array to dictionary mode given
1997 // an access at key?
1998 bool WouldConvertToSlowElements(uint32_t index);
2000 // Computes the new capacity when expanding the elements of a JSObject.
2001 static uint32_t NewElementsCapacity(uint32_t old_capacity) {
2002 // (old_capacity + 50%) + 16
2003 return old_capacity + (old_capacity >> 1) + 16;
2006 // These methods do not perform access checks!
2007 static void UpdateAllocationSite(Handle<JSObject> object,
2008 ElementsKind to_kind);
2010 // Lookup interceptors are used for handling properties controlled by host
2012 inline bool HasNamedInterceptor();
2013 inline bool HasIndexedInterceptor();
2015 // Computes the enumerable keys from interceptors. Used for debug mirrors and
2016 // by JSReceiver::GetKeys.
2017 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForNamedInterceptor(
2018 Handle<JSObject> object,
2019 Handle<JSReceiver> receiver);
2020 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForIndexedInterceptor(
2021 Handle<JSObject> object,
2022 Handle<JSReceiver> receiver);
2024 // Support functions for v8 api (needed for correct interceptor behavior).
2025 MUST_USE_RESULT static Maybe<bool> HasRealNamedProperty(
2026 Handle<JSObject> object, Handle<Name> name);
2027 MUST_USE_RESULT static Maybe<bool> HasRealElementProperty(
2028 Handle<JSObject> object, uint32_t index);
2029 MUST_USE_RESULT static Maybe<bool> HasRealNamedCallbackProperty(
2030 Handle<JSObject> object, Handle<Name> name);
2032 // Get the header size for a JSObject. Used to compute the index of
2033 // internal fields as well as the number of internal fields.
2034 inline int GetHeaderSize();
2036 inline int GetInternalFieldCount();
2037 inline int GetInternalFieldOffset(int index);
2038 inline Object* GetInternalField(int index);
2039 inline void SetInternalField(int index, Object* value);
2040 inline void SetInternalField(int index, Smi* value);
2042 // Returns the number of properties on this object filtering out properties
2043 // with the specified attributes (ignoring interceptors).
2044 int NumberOfOwnProperties(PropertyAttributes filter = NONE);
2045 // Fill in details for properties into storage starting at the specified
2046 // index. Returns the number of properties added.
2047 int GetOwnPropertyNames(FixedArray* storage, int index,
2048 PropertyAttributes filter = NONE);
2050 // Returns the number of properties on this object filtering out properties
2051 // with the specified attributes (ignoring interceptors).
2052 int NumberOfOwnElements(PropertyAttributes filter);
2053 // Returns the number of enumerable elements (ignoring interceptors).
2054 int NumberOfEnumElements();
2055 // Returns the number of elements on this object filtering out elements
2056 // with the specified attributes (ignoring interceptors).
2057 int GetOwnElementKeys(FixedArray* storage, PropertyAttributes filter);
2058 // Count and fill in the enumerable elements into storage.
2059 // (storage->length() == NumberOfEnumElements()).
2060 // If storage is NULL, will count the elements without adding
2061 // them to any storage.
2062 // Returns the number of enumerable elements.
2063 int GetEnumElementKeys(FixedArray* storage);
2065 static Handle<FixedArray> GetEnumPropertyKeys(Handle<JSObject> object,
2068 // Returns a new map with all transitions dropped from the object's current
2069 // map and the ElementsKind set.
2070 static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
2071 ElementsKind to_kind);
2072 static void TransitionElementsKind(Handle<JSObject> object,
2073 ElementsKind to_kind);
2075 // Always use this to migrate an object to a new map.
2076 // |expected_additional_properties| is only used for fast-to-slow transitions
2077 // and ignored otherwise.
2078 static void MigrateToMap(Handle<JSObject> object, Handle<Map> new_map,
2079 int expected_additional_properties = 0);
2081 // Convert the object to use the canonical dictionary
2082 // representation. If the object is expected to have additional properties
2083 // added this number can be indicated to have the backing store allocated to
2084 // an initial capacity for holding these properties.
2085 static void NormalizeProperties(Handle<JSObject> object,
2086 PropertyNormalizationMode mode,
2087 int expected_additional_properties,
2088 const char* reason);
2090 // Convert and update the elements backing store to be a
2091 // SeededNumberDictionary dictionary. Returns the backing after conversion.
2092 static Handle<SeededNumberDictionary> NormalizeElements(
2093 Handle<JSObject> object);
2095 void RequireSlowElements(SeededNumberDictionary* dictionary);
2097 // Transform slow named properties to fast variants.
2098 static void MigrateSlowToFast(Handle<JSObject> object,
2099 int unused_property_fields, const char* reason);
2101 inline bool IsUnboxedDoubleField(FieldIndex index);
2103 // Access fast-case object properties at index.
2104 static Handle<Object> FastPropertyAt(Handle<JSObject> object,
2105 Representation representation,
2107 inline Object* RawFastPropertyAt(FieldIndex index);
2108 inline double RawFastDoublePropertyAt(FieldIndex index);
2110 inline void FastPropertyAtPut(FieldIndex index, Object* value);
2111 inline void RawFastPropertyAtPut(FieldIndex index, Object* value);
2112 inline void RawFastDoublePropertyAtPut(FieldIndex index, double value);
2113 inline void WriteToField(int descriptor, Object* value);
2115 // Access to in object properties.
2116 inline int GetInObjectPropertyOffset(int index);
2117 inline Object* InObjectPropertyAt(int index);
2118 inline Object* InObjectPropertyAtPut(int index,
2120 WriteBarrierMode mode
2121 = UPDATE_WRITE_BARRIER);
2123 // Set the object's prototype (only JSReceiver and null are allowed values).
2124 MUST_USE_RESULT static MaybeHandle<Object> SetPrototype(
2125 Handle<JSObject> object, Handle<Object> value, bool from_javascript);
2127 // Initializes the body after properties slot, properties slot is
2128 // initialized by set_properties. Fill the pre-allocated fields with
2129 // pre_allocated_value and the rest with filler_value.
2130 // Note: this call does not update write barrier, the caller is responsible
2131 // to ensure that |filler_value| can be collected without WB here.
2132 inline void InitializeBody(Map* map,
2133 Object* pre_allocated_value,
2134 Object* filler_value);
2136 // Check whether this object references another object
2137 bool ReferencesObject(Object* obj);
2139 // Disalow further properties to be added to the oject.
2140 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensions(
2141 Handle<JSObject> object);
2143 bool IsExtensible();
2146 MUST_USE_RESULT static MaybeHandle<Object> Seal(Handle<JSObject> object);
2148 // ES5 Object.freeze
2149 MUST_USE_RESULT static MaybeHandle<Object> Freeze(Handle<JSObject> object);
2151 // Called the first time an object is observed with ES7 Object.observe.
2152 static void SetObserved(Handle<JSObject> object);
2155 enum DeepCopyHints { kNoHints = 0, kObjectIsShallow = 1 };
2157 MUST_USE_RESULT static MaybeHandle<JSObject> DeepCopy(
2158 Handle<JSObject> object,
2159 AllocationSiteUsageContext* site_context,
2160 DeepCopyHints hints = kNoHints);
2161 MUST_USE_RESULT static MaybeHandle<JSObject> DeepWalk(
2162 Handle<JSObject> object,
2163 AllocationSiteCreationContext* site_context);
2165 DECLARE_CAST(JSObject)
2167 // Dispatched behavior.
2168 void JSObjectShortPrint(StringStream* accumulator);
2169 DECLARE_PRINTER(JSObject)
2170 DECLARE_VERIFIER(JSObject)
2172 void PrintProperties(std::ostream& os); // NOLINT
2173 void PrintElements(std::ostream& os); // NOLINT
2175 #if defined(DEBUG) || defined(OBJECT_PRINT)
2176 void PrintTransitions(std::ostream& os); // NOLINT
2179 static void PrintElementsTransition(
2180 FILE* file, Handle<JSObject> object,
2181 ElementsKind from_kind, Handle<FixedArrayBase> from_elements,
2182 ElementsKind to_kind, Handle<FixedArrayBase> to_elements);
2184 void PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map);
2187 // Structure for collecting spill information about JSObjects.
2188 class SpillInformation {
2192 int number_of_objects_;
2193 int number_of_objects_with_fast_properties_;
2194 int number_of_objects_with_fast_elements_;
2195 int number_of_fast_used_fields_;
2196 int number_of_fast_unused_fields_;
2197 int number_of_slow_used_properties_;
2198 int number_of_slow_unused_properties_;
2199 int number_of_fast_used_elements_;
2200 int number_of_fast_unused_elements_;
2201 int number_of_slow_used_elements_;
2202 int number_of_slow_unused_elements_;
2205 void IncrementSpillStatistics(SpillInformation* info);
2209 // If a GC was caused while constructing this object, the elements pointer
2210 // may point to a one pointer filler map. The object won't be rooted, but
2211 // our heap verification code could stumble across it.
2212 bool ElementsAreSafeToExamine();
2215 Object* SlowReverseLookup(Object* value);
2217 // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2218 // Also maximal value of JSArray's length property.
2219 static const uint32_t kMaxElementCount = 0xffffffffu;
2221 // Constants for heuristics controlling conversion of fast elements
2222 // to slow elements.
2224 // Maximal gap that can be introduced by adding an element beyond
2225 // the current elements length.
2226 static const uint32_t kMaxGap = 1024;
2228 // Maximal length of fast elements array that won't be checked for
2229 // being dense enough on expansion.
2230 static const int kMaxUncheckedFastElementsLength = 5000;
2232 // Same as above but for old arrays. This limit is more strict. We
2233 // don't want to be wasteful with long lived objects.
2234 static const int kMaxUncheckedOldFastElementsLength = 500;
2236 // Note that Page::kMaxRegularHeapObjectSize puts a limit on
2237 // permissible values (see the DCHECK in heap.cc).
2238 static const int kInitialMaxFastElementArray = 100000;
2240 // This constant applies only to the initial map of "global.Object" and
2241 // not to arbitrary other JSObject maps.
2242 static const int kInitialGlobalObjectUnusedPropertiesCount = 4;
2244 static const int kMaxInstanceSize = 255 * kPointerSize;
2245 // When extending the backing storage for property values, we increase
2246 // its size by more than the 1 entry necessary, so sequentially adding fields
2247 // to the same object requires fewer allocations and copies.
2248 static const int kFieldsAdded = 3;
2250 // Layout description.
2251 static const int kPropertiesOffset = HeapObject::kHeaderSize;
2252 static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2253 static const int kHeaderSize = kElementsOffset + kPointerSize;
2255 STATIC_ASSERT(kHeaderSize == Internals::kJSObjectHeaderSize);
2257 class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2259 static inline int SizeOf(Map* map, HeapObject* object);
2262 Context* GetCreationContext();
2264 // Enqueue change record for Object.observe. May cause GC.
2265 MUST_USE_RESULT static MaybeHandle<Object> EnqueueChangeRecord(
2266 Handle<JSObject> object, const char* type, Handle<Name> name,
2267 Handle<Object> old_value);
2269 // Gets the number of currently used elements.
2270 int GetFastElementsUsage();
2272 // Deletes an existing named property in a normalized object.
2273 static void DeleteNormalizedProperty(Handle<JSObject> object,
2274 Handle<Name> name, int entry);
2276 static bool AllCanRead(LookupIterator* it);
2277 static bool AllCanWrite(LookupIterator* it);
2280 friend class JSReceiver;
2281 friend class Object;
2283 static void MigrateFastToFast(Handle<JSObject> object, Handle<Map> new_map);
2284 static void MigrateFastToSlow(Handle<JSObject> object,
2285 Handle<Map> new_map,
2286 int expected_additional_properties);
2288 // Used from Object::GetProperty().
2289 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithFailedAccessCheck(
2290 LookupIterator* it);
2292 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithFailedAccessCheck(
2293 LookupIterator* it, Handle<Object> value);
2295 // Add a property to a slow-case object.
2296 static void AddSlowProperty(Handle<JSObject> object,
2298 Handle<Object> value,
2299 PropertyAttributes attributes);
2301 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithInterceptor(
2302 LookupIterator* it);
2304 bool ReferencesObjectFromElements(FixedArray* elements,
2308 // Return the hash table backing store or the inline stored identity hash,
2309 // whatever is found.
2310 MUST_USE_RESULT Object* GetHiddenPropertiesHashTable();
2312 // Return the hash table backing store for hidden properties. If there is no
2313 // backing store, allocate one.
2314 static Handle<ObjectHashTable> GetOrCreateHiddenPropertiesHashtable(
2315 Handle<JSObject> object);
2317 // Set the hidden property backing store to either a hash table or
2318 // the inline-stored identity hash.
2319 static Handle<Object> SetHiddenPropertiesHashTable(
2320 Handle<JSObject> object,
2321 Handle<Object> value);
2323 MUST_USE_RESULT Object* GetIdentityHash();
2325 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSObject> object);
2327 static Handle<SeededNumberDictionary> GetNormalizedElementDictionary(
2328 Handle<JSObject> object, Handle<FixedArrayBase> elements);
2330 // Helper for fast versions of preventExtensions, seal, and freeze.
2331 // attrs is one of NONE, SEALED, or FROZEN (depending on the operation).
2332 template <PropertyAttributes attrs>
2333 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensionsWithTransition(
2334 Handle<JSObject> object);
2336 DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
2340 // Common superclass for FixedArrays that allow implementations to share
2341 // common accessors and some code paths.
2342 class FixedArrayBase: public HeapObject {
2344 // [length]: length of the array.
2345 inline int length() const;
2346 inline void set_length(int value);
2348 // Get and set the length using acquire loads and release stores.
2349 inline int synchronized_length() const;
2350 inline void synchronized_set_length(int value);
2352 DECLARE_CAST(FixedArrayBase)
2354 // Layout description.
2355 // Length is smi tagged when it is stored.
2356 static const int kLengthOffset = HeapObject::kHeaderSize;
2357 static const int kHeaderSize = kLengthOffset + kPointerSize;
2361 class FixedDoubleArray;
2362 class IncrementalMarking;
2365 // FixedArray describes fixed-sized arrays with element type Object*.
2366 class FixedArray: public FixedArrayBase {
2368 // Setter and getter for elements.
2369 inline Object* get(int index) const;
2370 void SetValue(uint32_t index, Object* value);
2371 static inline Handle<Object> get(Handle<FixedArray> array, int index);
2372 // Setter that uses write barrier.
2373 inline void set(int index, Object* value);
2374 inline bool is_the_hole(int index);
2376 // Setter that doesn't need write barrier.
2377 inline void set(int index, Smi* value);
2378 // Setter with explicit barrier mode.
2379 inline void set(int index, Object* value, WriteBarrierMode mode);
2381 // Setters for frequently used oddballs located in old space.
2382 inline void set_undefined(int index);
2383 inline void set_null(int index);
2384 inline void set_the_hole(int index);
2386 inline Object** GetFirstElementAddress();
2387 inline bool ContainsOnlySmisOrHoles();
2389 // Gives access to raw memory which stores the array's data.
2390 inline Object** data_start();
2392 inline void FillWithHoles(int from, int to);
2394 // Shrink length and insert filler objects.
2395 void Shrink(int length);
2397 enum KeyFilter { ALL_KEYS, NON_SYMBOL_KEYS };
2399 // Add the elements of a JSArray to this FixedArray.
2400 MUST_USE_RESULT static MaybeHandle<FixedArray> AddKeysFromArrayLike(
2401 Handle<FixedArray> content, Handle<JSObject> array,
2402 KeyFilter filter = ALL_KEYS);
2404 // Computes the union of keys and return the result.
2405 // Used for implementing "for (n in object) { }"
2406 MUST_USE_RESULT static MaybeHandle<FixedArray> UnionOfKeys(
2407 Handle<FixedArray> first,
2408 Handle<FixedArray> second);
2410 // Copy a sub array from the receiver to dest.
2411 void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
2413 // Garbage collection support.
2414 static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
2416 // Code Generation support.
2417 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2419 // Garbage collection support.
2420 Object** RawFieldOfElementAt(int index) {
2421 return HeapObject::RawField(this, OffsetOfElementAt(index));
2424 DECLARE_CAST(FixedArray)
2426 // Maximal allowed size, in bytes, of a single FixedArray.
2427 // Prevents overflowing size computations, as well as extreme memory
2429 static const int kMaxSize = 128 * MB * kPointerSize;
2430 // Maximally allowed length of a FixedArray.
2431 static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
2433 // Dispatched behavior.
2434 DECLARE_PRINTER(FixedArray)
2435 DECLARE_VERIFIER(FixedArray)
2437 // Checks if two FixedArrays have identical contents.
2438 bool IsEqualTo(FixedArray* other);
2441 // Swap two elements in a pair of arrays. If this array and the
2442 // numbers array are the same object, the elements are only swapped
2444 void SwapPairs(FixedArray* numbers, int i, int j);
2446 // Sort prefix of this array and the numbers array as pairs wrt. the
2447 // numbers. If the numbers array and the this array are the same
2448 // object, the prefix of this array is sorted.
2449 void SortPairs(FixedArray* numbers, uint32_t len);
2451 class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
2453 static inline int SizeOf(Map* map, HeapObject* object) {
2455 reinterpret_cast<FixedArray*>(object)->synchronized_length());
2460 // Set operation on FixedArray without using write barriers. Can
2461 // only be used for storing old space objects or smis.
2462 static inline void NoWriteBarrierSet(FixedArray* array,
2466 // Set operation on FixedArray without incremental write barrier. Can
2467 // only be used if the object is guaranteed to be white (whiteness witness
2469 static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
2474 STATIC_ASSERT(kHeaderSize == Internals::kFixedArrayHeaderSize);
2476 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
2480 // FixedDoubleArray describes fixed-sized arrays with element type double.
2481 class FixedDoubleArray: public FixedArrayBase {
2483 // Setter and getter for elements.
2484 inline double get_scalar(int index);
2485 inline uint64_t get_representation(int index);
2486 static inline Handle<Object> get(Handle<FixedDoubleArray> array, int index);
2487 // This accessor has to get a Number as |value|.
2488 void SetValue(uint32_t index, Object* value);
2489 inline void set(int index, double value);
2490 inline void set_the_hole(int index);
2492 // Checking for the hole.
2493 inline bool is_the_hole(int index);
2495 // Garbage collection support.
2496 inline static int SizeFor(int length) {
2497 return kHeaderSize + length * kDoubleSize;
2500 // Gives access to raw memory which stores the array's data.
2501 inline double* data_start();
2503 inline void FillWithHoles(int from, int to);
2505 // Code Generation support.
2506 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2508 DECLARE_CAST(FixedDoubleArray)
2510 // Maximal allowed size, in bytes, of a single FixedDoubleArray.
2511 // Prevents overflowing size computations, as well as extreme memory
2513 static const int kMaxSize = 512 * MB;
2514 // Maximally allowed length of a FixedArray.
2515 static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
2517 // Dispatched behavior.
2518 DECLARE_PRINTER(FixedDoubleArray)
2519 DECLARE_VERIFIER(FixedDoubleArray)
2522 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
2526 class WeakFixedArray : public FixedArray {
2528 // If |maybe_array| is not a WeakFixedArray, a fresh one will be allocated.
2529 // This function does not check if the value exists already, callers must
2530 // ensure this themselves if necessary.
2531 static Handle<WeakFixedArray> Add(Handle<Object> maybe_array,
2532 Handle<HeapObject> value,
2533 int* assigned_index = NULL);
2535 // Returns true if an entry was found and removed.
2536 bool Remove(Handle<HeapObject> value);
2538 class NullCallback {
2540 static void Callback(Object* value, int old_index, int new_index) {}
2543 template <class CompactionCallback>
2546 inline Object* Get(int index) const;
2547 inline void Clear(int index);
2548 inline int Length() const;
2550 inline bool IsEmptySlot(int index) const;
2551 static Object* Empty() { return Smi::FromInt(0); }
2553 DECLARE_CAST(WeakFixedArray)
2556 static const int kLastUsedIndexIndex = 0;
2557 static const int kFirstIndex = 1;
2559 static Handle<WeakFixedArray> Allocate(
2560 Isolate* isolate, int size, Handle<WeakFixedArray> initialize_from);
2562 static void Set(Handle<WeakFixedArray> array, int index,
2563 Handle<HeapObject> value);
2564 inline void clear(int index);
2566 inline int last_used_index() const;
2567 inline void set_last_used_index(int index);
2569 // Disallow inherited setters.
2570 void set(int index, Smi* value);
2571 void set(int index, Object* value);
2572 void set(int index, Object* value, WriteBarrierMode mode);
2573 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakFixedArray);
2577 // Generic array grows dynamically with O(1) amortized insertion.
2578 class ArrayList : public FixedArray {
2582 // Use this if GC can delete elements from the array.
2583 kReloadLengthAfterAllocation,
2585 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj,
2586 AddMode mode = kNone);
2587 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj1,
2588 Handle<Object> obj2, AddMode = kNone);
2589 inline int Length();
2590 inline void SetLength(int length);
2591 inline Object* Get(int index);
2592 inline Object** Slot(int index);
2593 inline void Set(int index, Object* obj);
2594 inline void Clear(int index, Object* undefined);
2595 DECLARE_CAST(ArrayList)
2598 static Handle<ArrayList> EnsureSpace(Handle<ArrayList> array, int length);
2599 static const int kLengthIndex = 0;
2600 static const int kFirstIndex = 1;
2601 DISALLOW_IMPLICIT_CONSTRUCTORS(ArrayList);
2605 // DescriptorArrays are fixed arrays used to hold instance descriptors.
2606 // The format of the these objects is:
2607 // [0]: Number of descriptors
2608 // [1]: Either Smi(0) if uninitialized, or a pointer to small fixed array:
2609 // [0]: pointer to fixed array with enum cache
2610 // [1]: either Smi(0) or pointer to fixed array with indices
2612 // [2 + number of descriptors * kDescriptorSize]: start of slack
2613 class DescriptorArray: public FixedArray {
2615 // Returns true for both shared empty_descriptor_array and for smis, which the
2616 // map uses to encode additional bit fields when the descriptor array is not
2618 inline bool IsEmpty();
2620 // Returns the number of descriptors in the array.
2621 int number_of_descriptors() {
2622 DCHECK(length() >= kFirstIndex || IsEmpty());
2624 return len == 0 ? 0 : Smi::cast(get(kDescriptorLengthIndex))->value();
2627 int number_of_descriptors_storage() {
2629 return len == 0 ? 0 : (len - kFirstIndex) / kDescriptorSize;
2632 int NumberOfSlackDescriptors() {
2633 return number_of_descriptors_storage() - number_of_descriptors();
2636 inline void SetNumberOfDescriptors(int number_of_descriptors);
2637 inline int number_of_entries() { return number_of_descriptors(); }
2639 bool HasEnumCache() {
2640 return !IsEmpty() && !get(kEnumCacheIndex)->IsSmi();
2643 void CopyEnumCacheFrom(DescriptorArray* array) {
2644 set(kEnumCacheIndex, array->get(kEnumCacheIndex));
2647 FixedArray* GetEnumCache() {
2648 DCHECK(HasEnumCache());
2649 FixedArray* bridge = FixedArray::cast(get(kEnumCacheIndex));
2650 return FixedArray::cast(bridge->get(kEnumCacheBridgeCacheIndex));
2653 bool HasEnumIndicesCache() {
2654 if (IsEmpty()) return false;
2655 Object* object = get(kEnumCacheIndex);
2656 if (object->IsSmi()) return false;
2657 FixedArray* bridge = FixedArray::cast(object);
2658 return !bridge->get(kEnumCacheBridgeIndicesCacheIndex)->IsSmi();
2661 FixedArray* GetEnumIndicesCache() {
2662 DCHECK(HasEnumIndicesCache());
2663 FixedArray* bridge = FixedArray::cast(get(kEnumCacheIndex));
2664 return FixedArray::cast(bridge->get(kEnumCacheBridgeIndicesCacheIndex));
2667 Object** GetEnumCacheSlot() {
2668 DCHECK(HasEnumCache());
2669 return HeapObject::RawField(reinterpret_cast<HeapObject*>(this),
2673 void ClearEnumCache();
2675 // Initialize or change the enum cache,
2676 // using the supplied storage for the small "bridge".
2677 void SetEnumCache(FixedArray* bridge_storage,
2678 FixedArray* new_cache,
2679 Object* new_index_cache);
2681 bool CanHoldValue(int descriptor, Object* value);
2683 // Accessors for fetching instance descriptor at descriptor number.
2684 inline Name* GetKey(int descriptor_number);
2685 inline Object** GetKeySlot(int descriptor_number);
2686 inline Object* GetValue(int descriptor_number);
2687 inline void SetValue(int descriptor_number, Object* value);
2688 inline Object** GetValueSlot(int descriptor_number);
2689 static inline int GetValueOffset(int descriptor_number);
2690 inline Object** GetDescriptorStartSlot(int descriptor_number);
2691 inline Object** GetDescriptorEndSlot(int descriptor_number);
2692 inline PropertyDetails GetDetails(int descriptor_number);
2693 inline PropertyType GetType(int descriptor_number);
2694 inline int GetFieldIndex(int descriptor_number);
2695 inline HeapType* GetFieldType(int descriptor_number);
2696 inline Object* GetConstant(int descriptor_number);
2697 inline Object* GetCallbacksObject(int descriptor_number);
2698 inline AccessorDescriptor* GetCallbacks(int descriptor_number);
2700 inline Name* GetSortedKey(int descriptor_number);
2701 inline int GetSortedKeyIndex(int descriptor_number);
2702 inline void SetSortedKey(int pointer, int descriptor_number);
2703 inline void SetRepresentation(int descriptor_number,
2704 Representation representation);
2706 // Accessor for complete descriptor.
2707 inline void Get(int descriptor_number, Descriptor* desc);
2708 inline void Set(int descriptor_number, Descriptor* desc);
2709 void Replace(int descriptor_number, Descriptor* descriptor);
2711 // Append automatically sets the enumeration index. This should only be used
2712 // to add descriptors in bulk at the end, followed by sorting the descriptor
2714 inline void Append(Descriptor* desc);
2716 static Handle<DescriptorArray> CopyUpTo(Handle<DescriptorArray> desc,
2717 int enumeration_index,
2720 static Handle<DescriptorArray> CopyUpToAddAttributes(
2721 Handle<DescriptorArray> desc,
2722 int enumeration_index,
2723 PropertyAttributes attributes,
2726 // Sort the instance descriptors by the hash codes of their keys.
2729 // Search the instance descriptors for given name.
2730 INLINE(int Search(Name* name, int number_of_own_descriptors));
2732 // As the above, but uses DescriptorLookupCache and updates it when
2734 INLINE(int SearchWithCache(Name* name, Map* map));
2736 // Allocates a DescriptorArray, but returns the singleton
2737 // empty descriptor array object if number_of_descriptors is 0.
2738 static Handle<DescriptorArray> Allocate(Isolate* isolate,
2739 int number_of_descriptors,
2742 DECLARE_CAST(DescriptorArray)
2744 // Constant for denoting key was not found.
2745 static const int kNotFound = -1;
2747 static const int kDescriptorLengthIndex = 0;
2748 static const int kEnumCacheIndex = 1;
2749 static const int kFirstIndex = 2;
2751 // The length of the "bridge" to the enum cache.
2752 static const int kEnumCacheBridgeLength = 2;
2753 static const int kEnumCacheBridgeCacheIndex = 0;
2754 static const int kEnumCacheBridgeIndicesCacheIndex = 1;
2756 // Layout description.
2757 static const int kDescriptorLengthOffset = FixedArray::kHeaderSize;
2758 static const int kEnumCacheOffset = kDescriptorLengthOffset + kPointerSize;
2759 static const int kFirstOffset = kEnumCacheOffset + kPointerSize;
2761 // Layout description for the bridge array.
2762 static const int kEnumCacheBridgeCacheOffset = FixedArray::kHeaderSize;
2764 // Layout of descriptor.
2765 static const int kDescriptorKey = 0;
2766 static const int kDescriptorDetails = 1;
2767 static const int kDescriptorValue = 2;
2768 static const int kDescriptorSize = 3;
2770 #if defined(DEBUG) || defined(OBJECT_PRINT)
2771 // For our gdb macros, we should perhaps change these in the future.
2774 // Print all the descriptors.
2775 void PrintDescriptors(std::ostream& os); // NOLINT
2779 // Is the descriptor array sorted and without duplicates?
2780 bool IsSortedNoDuplicates(int valid_descriptors = -1);
2782 // Is the descriptor array consistent with the back pointers in targets?
2783 bool IsConsistentWithBackPointers(Map* current_map);
2785 // Are two DescriptorArrays equal?
2786 bool IsEqualTo(DescriptorArray* other);
2789 // Returns the fixed array length required to hold number_of_descriptors
2791 static int LengthFor(int number_of_descriptors) {
2792 return ToKeyIndex(number_of_descriptors);
2796 // WhitenessWitness is used to prove that a descriptor array is white
2797 // (unmarked), so incremental write barriers can be skipped because the
2798 // marking invariant cannot be broken and slots pointing into evacuation
2799 // candidates will be discovered when the object is scanned. A witness is
2800 // always stack-allocated right after creating an array. By allocating a
2801 // witness, incremental marking is globally disabled. The witness is then
2802 // passed along wherever needed to statically prove that the array is known to
2804 class WhitenessWitness {
2806 inline explicit WhitenessWitness(DescriptorArray* array);
2807 inline ~WhitenessWitness();
2810 IncrementalMarking* marking_;
2813 // An entry in a DescriptorArray, represented as an (array, index) pair.
2816 inline explicit Entry(DescriptorArray* descs, int index) :
2817 descs_(descs), index_(index) { }
2819 inline PropertyType type() { return descs_->GetType(index_); }
2820 inline Object* GetCallbackObject() { return descs_->GetValue(index_); }
2823 DescriptorArray* descs_;
2827 // Conversion from descriptor number to array indices.
2828 static int ToKeyIndex(int descriptor_number) {
2829 return kFirstIndex +
2830 (descriptor_number * kDescriptorSize) +
2834 static int ToDetailsIndex(int descriptor_number) {
2835 return kFirstIndex +
2836 (descriptor_number * kDescriptorSize) +
2840 static int ToValueIndex(int descriptor_number) {
2841 return kFirstIndex +
2842 (descriptor_number * kDescriptorSize) +
2846 // Transfer a complete descriptor from the src descriptor array to this
2847 // descriptor array.
2848 void CopyFrom(int index, DescriptorArray* src, const WhitenessWitness&);
2850 inline void Set(int descriptor_number,
2852 const WhitenessWitness&);
2854 // Swap first and second descriptor.
2855 inline void SwapSortedKeys(int first, int second);
2857 DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
2861 enum SearchMode { ALL_ENTRIES, VALID_ENTRIES };
2863 template <SearchMode search_mode, typename T>
2864 inline int Search(T* array, Name* name, int valid_entries = 0,
2865 int* out_insertion_index = NULL);
2868 // HashTable is a subclass of FixedArray that implements a hash table
2869 // that uses open addressing and quadratic probing.
2871 // In order for the quadratic probing to work, elements that have not
2872 // yet been used and elements that have been deleted are
2873 // distinguished. Probing continues when deleted elements are
2874 // encountered and stops when unused elements are encountered.
2876 // - Elements with key == undefined have not been used yet.
2877 // - Elements with key == the_hole have been deleted.
2879 // The hash table class is parameterized with a Shape and a Key.
2880 // Shape must be a class with the following interface:
2881 // class ExampleShape {
2883 // // Tells whether key matches other.
2884 // static bool IsMatch(Key key, Object* other);
2885 // // Returns the hash value for key.
2886 // static uint32_t Hash(Key key);
2887 // // Returns the hash value for object.
2888 // static uint32_t HashForObject(Key key, Object* object);
2889 // // Convert key to an object.
2890 // static inline Handle<Object> AsHandle(Isolate* isolate, Key key);
2891 // // The prefix size indicates number of elements in the beginning
2892 // // of the backing storage.
2893 // static const int kPrefixSize = ..;
2894 // // The Element size indicates number of elements per entry.
2895 // static const int kEntrySize = ..;
2897 // The prefix size indicates an amount of memory in the
2898 // beginning of the backing storage that can be used for non-element
2899 // information by subclasses.
2901 template<typename Key>
2904 static const bool UsesSeed = false;
2905 static uint32_t Hash(Key key) { return 0; }
2906 static uint32_t SeededHash(Key key, uint32_t seed) {
2910 static uint32_t HashForObject(Key key, Object* object) { return 0; }
2911 static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
2913 return HashForObject(key, object);
2918 class HashTableBase : public FixedArray {
2920 // Returns the number of elements in the hash table.
2921 int NumberOfElements() {
2922 return Smi::cast(get(kNumberOfElementsIndex))->value();
2925 // Returns the number of deleted elements in the hash table.
2926 int NumberOfDeletedElements() {
2927 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
2930 // Returns the capacity of the hash table.
2932 return Smi::cast(get(kCapacityIndex))->value();
2935 // ElementAdded should be called whenever an element is added to a
2937 void ElementAdded() { SetNumberOfElements(NumberOfElements() + 1); }
2939 // ElementRemoved should be called whenever an element is removed from
2941 void ElementRemoved() {
2942 SetNumberOfElements(NumberOfElements() - 1);
2943 SetNumberOfDeletedElements(NumberOfDeletedElements() + 1);
2945 void ElementsRemoved(int n) {
2946 SetNumberOfElements(NumberOfElements() - n);
2947 SetNumberOfDeletedElements(NumberOfDeletedElements() + n);
2950 // Computes the required capacity for a table holding the given
2951 // number of elements. May be more than HashTable::kMaxCapacity.
2952 static inline int ComputeCapacity(int at_least_space_for);
2954 // Tells whether k is a real key. The hole and undefined are not allowed
2955 // as keys and can be used to indicate missing or deleted elements.
2956 bool IsKey(Object* k) {
2957 return !k->IsTheHole() && !k->IsUndefined();
2960 // Compute the probe offset (quadratic probing).
2961 INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
2962 return (n + n * n) >> 1;
2965 static const int kNumberOfElementsIndex = 0;
2966 static const int kNumberOfDeletedElementsIndex = 1;
2967 static const int kCapacityIndex = 2;
2968 static const int kPrefixStartIndex = 3;
2970 // Constant used for denoting a absent entry.
2971 static const int kNotFound = -1;
2974 // Update the number of elements in the hash table.
2975 void SetNumberOfElements(int nof) {
2976 set(kNumberOfElementsIndex, Smi::FromInt(nof));
2979 // Update the number of deleted elements in the hash table.
2980 void SetNumberOfDeletedElements(int nod) {
2981 set(kNumberOfDeletedElementsIndex, Smi::FromInt(nod));
2984 // Returns probe entry.
2985 static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
2986 DCHECK(base::bits::IsPowerOfTwo32(size));
2987 return (hash + GetProbeOffset(number)) & (size - 1);
2990 inline static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
2991 return hash & (size - 1);
2994 inline static uint32_t NextProbe(
2995 uint32_t last, uint32_t number, uint32_t size) {
2996 return (last + number) & (size - 1);
3001 template <typename Derived, typename Shape, typename Key>
3002 class HashTable : public HashTableBase {
3005 inline uint32_t Hash(Key key) {
3006 if (Shape::UsesSeed) {
3007 return Shape::SeededHash(key, GetHeap()->HashSeed());
3009 return Shape::Hash(key);
3013 inline uint32_t HashForObject(Key key, Object* object) {
3014 if (Shape::UsesSeed) {
3015 return Shape::SeededHashForObject(key, GetHeap()->HashSeed(), object);
3017 return Shape::HashForObject(key, object);
3021 // Returns a new HashTable object.
3022 MUST_USE_RESULT static Handle<Derived> New(
3023 Isolate* isolate, int at_least_space_for,
3024 MinimumCapacity capacity_option = USE_DEFAULT_MINIMUM_CAPACITY,
3025 PretenureFlag pretenure = NOT_TENURED);
3027 DECLARE_CAST(HashTable)
3029 // Garbage collection support.
3030 void IteratePrefix(ObjectVisitor* visitor);
3031 void IterateElements(ObjectVisitor* visitor);
3033 // Find entry for key otherwise return kNotFound.
3034 inline int FindEntry(Key key);
3035 inline int FindEntry(Isolate* isolate, Key key, int32_t hash);
3036 int FindEntry(Isolate* isolate, Key key);
3038 // Rehashes the table in-place.
3039 void Rehash(Key key);
3041 // Returns the key at entry.
3042 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3044 static const int kElementsStartIndex = kPrefixStartIndex + Shape::kPrefixSize;
3045 static const int kEntrySize = Shape::kEntrySize;
3046 static const int kElementsStartOffset =
3047 kHeaderSize + kElementsStartIndex * kPointerSize;
3048 static const int kCapacityOffset =
3049 kHeaderSize + kCapacityIndex * kPointerSize;
3051 // Returns the index for an entry (of the key)
3052 static inline int EntryToIndex(int entry) {
3053 return (entry * kEntrySize) + kElementsStartIndex;
3057 friend class ObjectHashTable;
3059 // Find the entry at which to insert element with the given key that
3060 // has the given hash value.
3061 uint32_t FindInsertionEntry(uint32_t hash);
3063 // Attempt to shrink hash table after removal of key.
3064 MUST_USE_RESULT static Handle<Derived> Shrink(Handle<Derived> table, Key key);
3066 // Ensure enough space for n additional elements.
3067 MUST_USE_RESULT static Handle<Derived> EnsureCapacity(
3068 Handle<Derived> table,
3071 PretenureFlag pretenure = NOT_TENURED);
3073 // Sets the capacity of the hash table.
3074 void SetCapacity(int capacity) {
3075 // To scale a computed hash code to fit within the hash table, we
3076 // use bit-wise AND with a mask, so the capacity must be positive
3078 DCHECK(capacity > 0);
3079 DCHECK(capacity <= kMaxCapacity);
3080 set(kCapacityIndex, Smi::FromInt(capacity));
3083 // Maximal capacity of HashTable. Based on maximal length of underlying
3084 // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
3086 static const int kMaxCapacity =
3087 (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
3090 // Returns _expected_ if one of entries given by the first _probe_ probes is
3091 // equal to _expected_. Otherwise, returns the entry given by the probe
3093 uint32_t EntryForProbe(Key key, Object* k, int probe, uint32_t expected);
3095 void Swap(uint32_t entry1, uint32_t entry2, WriteBarrierMode mode);
3097 // Rehashes this hash-table into the new table.
3098 void Rehash(Handle<Derived> new_table, Key key);
3102 // HashTableKey is an abstract superclass for virtual key behavior.
3103 class HashTableKey {
3105 // Returns whether the other object matches this key.
3106 virtual bool IsMatch(Object* other) = 0;
3107 // Returns the hash value for this key.
3108 virtual uint32_t Hash() = 0;
3109 // Returns the hash value for object.
3110 virtual uint32_t HashForObject(Object* key) = 0;
3111 // Returns the key object for storing into the hash table.
3112 MUST_USE_RESULT virtual Handle<Object> AsHandle(Isolate* isolate) = 0;
3114 virtual ~HashTableKey() {}
3118 class StringTableShape : public BaseShape<HashTableKey*> {
3120 static inline bool IsMatch(HashTableKey* key, Object* value) {
3121 return key->IsMatch(value);
3124 static inline uint32_t Hash(HashTableKey* key) {
3128 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3129 return key->HashForObject(object);
3132 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3134 static const int kPrefixSize = 0;
3135 static const int kEntrySize = 1;
3138 class SeqOneByteString;
3142 // No special elements in the prefix and the element size is 1
3143 // because only the string itself (the key) needs to be stored.
3144 class StringTable: public HashTable<StringTable,
3148 // Find string in the string table. If it is not there yet, it is
3149 // added. The return value is the string found.
3150 static Handle<String> LookupString(Isolate* isolate, Handle<String> key);
3151 static Handle<String> LookupKey(Isolate* isolate, HashTableKey* key);
3152 static String* LookupKeyIfExists(Isolate* isolate, HashTableKey* key);
3154 // Tries to internalize given string and returns string handle on success
3155 // or an empty handle otherwise.
3156 MUST_USE_RESULT static MaybeHandle<String> InternalizeStringIfExists(
3158 Handle<String> string);
3160 // Looks up a string that is equal to the given string and returns
3161 // string handle if it is found, or an empty handle otherwise.
3162 MUST_USE_RESULT static MaybeHandle<String> LookupStringIfExists(
3164 Handle<String> str);
3165 MUST_USE_RESULT static MaybeHandle<String> LookupTwoCharsStringIfExists(
3170 static void EnsureCapacityForDeserialization(Isolate* isolate, int expected);
3172 DECLARE_CAST(StringTable)
3175 template <bool seq_one_byte>
3176 friend class JsonParser;
3178 DISALLOW_IMPLICIT_CONSTRUCTORS(StringTable);
3182 template <typename Derived, typename Shape, typename Key>
3183 class Dictionary: public HashTable<Derived, Shape, Key> {
3184 typedef HashTable<Derived, Shape, Key> DerivedHashTable;
3187 // Returns the value at entry.
3188 Object* ValueAt(int entry) {
3189 return this->get(Derived::EntryToIndex(entry) + 1);
3192 // Set the value for entry.
3193 void ValueAtPut(int entry, Object* value) {
3194 this->set(Derived::EntryToIndex(entry) + 1, value);
3197 // Returns the property details for the property at entry.
3198 PropertyDetails DetailsAt(int entry) {
3199 return Shape::DetailsAt(static_cast<Derived*>(this), entry);
3202 // Set the details for entry.
3203 void DetailsAtPut(int entry, PropertyDetails value) {
3204 Shape::DetailsAtPut(static_cast<Derived*>(this), entry, value);
3207 // Returns true if property at given entry is deleted.
3208 bool IsDeleted(int entry) {
3209 return Shape::IsDeleted(static_cast<Derived*>(this), entry);
3212 // Delete a property from the dictionary.
3213 static Handle<Object> DeleteProperty(Handle<Derived> dictionary, int entry);
3215 // Attempt to shrink the dictionary after deletion of key.
3216 MUST_USE_RESULT static inline Handle<Derived> Shrink(
3217 Handle<Derived> dictionary,
3219 return DerivedHashTable::Shrink(dictionary, key);
3223 // TODO(dcarney): templatize or move to SeededNumberDictionary
3224 void CopyValuesTo(FixedArray* elements);
3226 // Returns the number of elements in the dictionary filtering out properties
3227 // with the specified attributes.
3228 int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3230 // Returns the number of enumerable elements in the dictionary.
3231 int NumberOfEnumElements() {
3232 return NumberOfElementsFilterAttributes(
3233 static_cast<PropertyAttributes>(DONT_ENUM | SYMBOLIC));
3236 // Returns true if the dictionary contains any elements that are non-writable,
3237 // non-configurable, non-enumerable, or have getters/setters.
3238 bool HasComplexElements();
3240 enum SortMode { UNSORTED, SORTED };
3242 // Fill in details for properties into storage.
3243 // Returns the number of properties added.
3244 int CopyKeysTo(FixedArray* storage, int index, PropertyAttributes filter,
3245 SortMode sort_mode);
3247 // Copies enumerable keys to preallocated fixed array.
3248 void CopyEnumKeysTo(FixedArray* storage);
3250 // Accessors for next enumeration index.
3251 void SetNextEnumerationIndex(int index) {
3253 this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
3256 int NextEnumerationIndex() {
3257 return Smi::cast(this->get(kNextEnumerationIndexIndex))->value();
3260 // Creates a new dictionary.
3261 MUST_USE_RESULT static Handle<Derived> New(
3263 int at_least_space_for,
3264 PretenureFlag pretenure = NOT_TENURED);
3266 // Ensure enough space for n additional elements.
3267 static Handle<Derived> EnsureCapacity(Handle<Derived> obj, int n, Key key);
3270 void Print(std::ostream& os); // NOLINT
3272 // Returns the key (slow).
3273 Object* SlowReverseLookup(Object* value);
3275 // Sets the entry to (key, value) pair.
3276 inline void SetEntry(int entry,
3278 Handle<Object> value);
3279 inline void SetEntry(int entry,
3281 Handle<Object> value,
3282 PropertyDetails details);
3284 MUST_USE_RESULT static Handle<Derived> Add(
3285 Handle<Derived> dictionary,
3287 Handle<Object> value,
3288 PropertyDetails details);
3290 // Returns iteration indices array for the |dictionary|.
3291 // Values are direct indices in the |HashTable| array.
3292 static Handle<FixedArray> BuildIterationIndicesArray(
3293 Handle<Derived> dictionary);
3296 // Generic at put operation.
3297 MUST_USE_RESULT static Handle<Derived> AtPut(
3298 Handle<Derived> dictionary,
3300 Handle<Object> value);
3302 // Add entry to dictionary.
3303 static void AddEntry(
3304 Handle<Derived> dictionary,
3306 Handle<Object> value,
3307 PropertyDetails details,
3310 // Generate new enumeration indices to avoid enumeration index overflow.
3311 // Returns iteration indices array for the |dictionary|.
3312 static Handle<FixedArray> GenerateNewEnumerationIndices(
3313 Handle<Derived> dictionary);
3314 static const int kMaxNumberKeyIndex = DerivedHashTable::kPrefixStartIndex;
3315 static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
3319 template <typename Derived, typename Shape>
3320 class NameDictionaryBase : public Dictionary<Derived, Shape, Handle<Name> > {
3321 typedef Dictionary<Derived, Shape, Handle<Name> > DerivedDictionary;
3324 // Find entry for key, otherwise return kNotFound. Optimized version of
3325 // HashTable::FindEntry.
3326 int FindEntry(Handle<Name> key);
3330 template <typename Key>
3331 class BaseDictionaryShape : public BaseShape<Key> {
3333 template <typename Dictionary>
3334 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry) {
3335 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3336 DCHECK(entry >= 0); // Not found is -1, which is not caught by get().
3337 return PropertyDetails(
3338 Smi::cast(dict->get(Dictionary::EntryToIndex(entry) + 2)));
3341 template <typename Dictionary>
3342 static inline void DetailsAtPut(Dictionary* dict, int entry,
3343 PropertyDetails value) {
3344 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3345 dict->set(Dictionary::EntryToIndex(entry) + 2, value.AsSmi());
3348 template <typename Dictionary>
3349 static bool IsDeleted(Dictionary* dict, int entry) {
3353 template <typename Dictionary>
3354 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3355 Handle<Object> value, PropertyDetails details);
3359 class NameDictionaryShape : public BaseDictionaryShape<Handle<Name> > {
3361 static inline bool IsMatch(Handle<Name> key, Object* other);
3362 static inline uint32_t Hash(Handle<Name> key);
3363 static inline uint32_t HashForObject(Handle<Name> key, Object* object);
3364 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Name> key);
3365 static const int kPrefixSize = 2;
3366 static const int kEntrySize = 3;
3367 static const bool kIsEnumerable = true;
3371 class NameDictionary
3372 : public NameDictionaryBase<NameDictionary, NameDictionaryShape> {
3373 typedef NameDictionaryBase<NameDictionary, NameDictionaryShape>
3377 DECLARE_CAST(NameDictionary)
3379 inline static Handle<FixedArray> DoGenerateNewEnumerationIndices(
3380 Handle<NameDictionary> dictionary);
3384 class GlobalDictionaryShape : public NameDictionaryShape {
3386 static const int kEntrySize = 2; // Overrides NameDictionaryShape::kEntrySize
3388 template <typename Dictionary>
3389 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry);
3391 template <typename Dictionary>
3392 static inline void DetailsAtPut(Dictionary* dict, int entry,
3393 PropertyDetails value);
3395 template <typename Dictionary>
3396 static bool IsDeleted(Dictionary* dict, int entry);
3398 template <typename Dictionary>
3399 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3400 Handle<Object> value, PropertyDetails details);
3404 class GlobalDictionary
3405 : public NameDictionaryBase<GlobalDictionary, GlobalDictionaryShape> {
3407 DECLARE_CAST(GlobalDictionary)
3411 class NumberDictionaryShape : public BaseDictionaryShape<uint32_t> {
3413 static inline bool IsMatch(uint32_t key, Object* other);
3414 static inline Handle<Object> AsHandle(Isolate* isolate, uint32_t key);
3415 static const int kEntrySize = 3;
3416 static const bool kIsEnumerable = false;
3420 class SeededNumberDictionaryShape : public NumberDictionaryShape {
3422 static const bool UsesSeed = true;
3423 static const int kPrefixSize = 2;
3425 static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
3426 static inline uint32_t SeededHashForObject(uint32_t key,
3432 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
3434 static const int kPrefixSize = 0;
3436 static inline uint32_t Hash(uint32_t key);
3437 static inline uint32_t HashForObject(uint32_t key, Object* object);
3441 class SeededNumberDictionary
3442 : public Dictionary<SeededNumberDictionary,
3443 SeededNumberDictionaryShape,
3446 DECLARE_CAST(SeededNumberDictionary)
3448 // Type specific at put (default NONE attributes is used when adding).
3449 MUST_USE_RESULT static Handle<SeededNumberDictionary> AtNumberPut(
3450 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3451 Handle<Object> value, bool used_as_prototype);
3452 MUST_USE_RESULT static Handle<SeededNumberDictionary> AddNumberEntry(
3453 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3454 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3456 // Set an existing entry or add a new one if needed.
3457 // Return the updated dictionary.
3458 MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
3459 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3460 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3462 void UpdateMaxNumberKey(uint32_t key, bool used_as_prototype);
3464 // If slow elements are required we will never go back to fast-case
3465 // for the elements kept in this dictionary. We require slow
3466 // elements if an element has been added at an index larger than
3467 // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
3468 // when defining a getter or setter with a number key.
3469 inline bool requires_slow_elements();
3470 inline void set_requires_slow_elements();
3472 // Get the value of the max number key that has been added to this
3473 // dictionary. max_number_key can only be called if
3474 // requires_slow_elements returns false.
3475 inline uint32_t max_number_key();
3478 static const int kRequiresSlowElementsMask = 1;
3479 static const int kRequiresSlowElementsTagSize = 1;
3480 static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
3484 class UnseededNumberDictionary
3485 : public Dictionary<UnseededNumberDictionary,
3486 UnseededNumberDictionaryShape,
3489 DECLARE_CAST(UnseededNumberDictionary)
3491 // Type specific at put (default NONE attributes is used when adding).
3492 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AtNumberPut(
3493 Handle<UnseededNumberDictionary> dictionary,
3495 Handle<Object> value);
3496 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AddNumberEntry(
3497 Handle<UnseededNumberDictionary> dictionary,
3499 Handle<Object> value);
3501 // Set an existing entry or add a new one if needed.
3502 // Return the updated dictionary.
3503 MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
3504 Handle<UnseededNumberDictionary> dictionary,
3506 Handle<Object> value);
3510 class ObjectHashTableShape : public BaseShape<Handle<Object> > {
3512 static inline bool IsMatch(Handle<Object> key, Object* other);
3513 static inline uint32_t Hash(Handle<Object> key);
3514 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3515 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3516 static const int kPrefixSize = 0;
3517 static const int kEntrySize = 2;
3521 // ObjectHashTable maps keys that are arbitrary objects to object values by
3522 // using the identity hash of the key for hashing purposes.
3523 class ObjectHashTable: public HashTable<ObjectHashTable,
3524 ObjectHashTableShape,
3527 ObjectHashTable, ObjectHashTableShape, Handle<Object> > DerivedHashTable;
3529 DECLARE_CAST(ObjectHashTable)
3531 // Attempt to shrink hash table after removal of key.
3532 MUST_USE_RESULT static inline Handle<ObjectHashTable> Shrink(
3533 Handle<ObjectHashTable> table,
3534 Handle<Object> key);
3536 // Looks up the value associated with the given key. The hole value is
3537 // returned in case the key is not present.
3538 Object* Lookup(Handle<Object> key);
3539 Object* Lookup(Handle<Object> key, int32_t hash);
3540 Object* Lookup(Isolate* isolate, Handle<Object> key, int32_t hash);
3542 // Adds (or overwrites) the value associated with the given key.
3543 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3545 Handle<Object> value);
3546 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3547 Handle<Object> key, Handle<Object> value,
3550 // Returns an ObjectHashTable (possibly |table|) where |key| has been removed.
3551 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3554 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3555 Handle<Object> key, bool* was_present,
3559 friend class MarkCompactCollector;
3561 void AddEntry(int entry, Object* key, Object* value);
3562 void RemoveEntry(int entry);
3564 // Returns the index to the value of an entry.
3565 static inline int EntryToValueIndex(int entry) {
3566 return EntryToIndex(entry) + 1;
3571 // OrderedHashTable is a HashTable with Object keys that preserves
3572 // insertion order. There are Map and Set interfaces (OrderedHashMap
3573 // and OrderedHashTable, below). It is meant to be used by JSMap/JSSet.
3575 // Only Object* keys are supported, with Object::SameValueZero() used as the
3576 // equality operator and Object::GetHash() for the hash function.
3578 // Based on the "Deterministic Hash Table" as described by Jason Orendorff at
3579 // https://wiki.mozilla.org/User:Jorend/Deterministic_hash_tables
3580 // Originally attributed to Tyler Close.
3583 // [0]: bucket count
3584 // [1]: element count
3585 // [2]: deleted element count
3586 // [3..(3 + NumberOfBuckets() - 1)]: "hash table", where each item is an
3587 // offset into the data table (see below) where the
3588 // first item in this bucket is stored.
3589 // [3 + NumberOfBuckets()..length]: "data table", an array of length
3590 // Capacity() * kEntrySize, where the first entrysize
3591 // items are handled by the derived class and the
3592 // item at kChainOffset is another entry into the
3593 // data table indicating the next entry in this hash
3596 // When we transition the table to a new version we obsolete it and reuse parts
3597 // of the memory to store information how to transition an iterator to the new
3600 // Memory layout for obsolete table:
3601 // [0]: bucket count
3602 // [1]: Next newer table
3603 // [2]: Number of removed holes or -1 when the table was cleared.
3604 // [3..(3 + NumberOfRemovedHoles() - 1)]: The indexes of the removed holes.
3605 // [3 + NumberOfRemovedHoles()..length]: Not used
3607 template<class Derived, class Iterator, int entrysize>
3608 class OrderedHashTable: public FixedArray {
3610 // Returns an OrderedHashTable with a capacity of at least |capacity|.
3611 static Handle<Derived> Allocate(
3612 Isolate* isolate, int capacity, PretenureFlag pretenure = NOT_TENURED);
3614 // Returns an OrderedHashTable (possibly |table|) with enough space
3615 // to add at least one new element.
3616 static Handle<Derived> EnsureGrowable(Handle<Derived> table);
3618 // Returns an OrderedHashTable (possibly |table|) that's shrunken
3620 static Handle<Derived> Shrink(Handle<Derived> table);
3622 // Returns a new empty OrderedHashTable and records the clearing so that
3623 // exisiting iterators can be updated.
3624 static Handle<Derived> Clear(Handle<Derived> table);
3626 int NumberOfElements() {
3627 return Smi::cast(get(kNumberOfElementsIndex))->value();
3630 int NumberOfDeletedElements() {
3631 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3634 int UsedCapacity() { return NumberOfElements() + NumberOfDeletedElements(); }
3636 int NumberOfBuckets() {
3637 return Smi::cast(get(kNumberOfBucketsIndex))->value();
3640 // Returns an index into |this| for the given entry.
3641 int EntryToIndex(int entry) {
3642 return kHashTableStartIndex + NumberOfBuckets() + (entry * kEntrySize);
3645 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3648 return !get(kNextTableIndex)->IsSmi();
3651 // The next newer table. This is only valid if the table is obsolete.
3652 Derived* NextTable() {
3653 return Derived::cast(get(kNextTableIndex));
3656 // When the table is obsolete we store the indexes of the removed holes.
3657 int RemovedIndexAt(int index) {
3658 return Smi::cast(get(kRemovedHolesIndex + index))->value();
3661 static const int kNotFound = -1;
3662 static const int kMinCapacity = 4;
3664 static const int kNumberOfBucketsIndex = 0;
3665 static const int kNumberOfElementsIndex = kNumberOfBucketsIndex + 1;
3666 static const int kNumberOfDeletedElementsIndex = kNumberOfElementsIndex + 1;
3667 static const int kHashTableStartIndex = kNumberOfDeletedElementsIndex + 1;
3668 static const int kNextTableIndex = kNumberOfElementsIndex;
3670 static const int kNumberOfBucketsOffset =
3671 kHeaderSize + kNumberOfBucketsIndex * kPointerSize;
3672 static const int kNumberOfElementsOffset =
3673 kHeaderSize + kNumberOfElementsIndex * kPointerSize;
3674 static const int kNumberOfDeletedElementsOffset =
3675 kHeaderSize + kNumberOfDeletedElementsIndex * kPointerSize;
3676 static const int kHashTableStartOffset =
3677 kHeaderSize + kHashTableStartIndex * kPointerSize;
3678 static const int kNextTableOffset =
3679 kHeaderSize + kNextTableIndex * kPointerSize;
3681 static const int kEntrySize = entrysize + 1;
3682 static const int kChainOffset = entrysize;
3684 static const int kLoadFactor = 2;
3686 // NumberOfDeletedElements is set to kClearedTableSentinel when
3687 // the table is cleared, which allows iterator transitions to
3688 // optimize that case.
3689 static const int kClearedTableSentinel = -1;
3692 static Handle<Derived> Rehash(Handle<Derived> table, int new_capacity);
3694 void SetNumberOfBuckets(int num) {
3695 set(kNumberOfBucketsIndex, Smi::FromInt(num));
3698 void SetNumberOfElements(int num) {
3699 set(kNumberOfElementsIndex, Smi::FromInt(num));
3702 void SetNumberOfDeletedElements(int num) {
3703 set(kNumberOfDeletedElementsIndex, Smi::FromInt(num));
3707 return NumberOfBuckets() * kLoadFactor;
3710 void SetNextTable(Derived* next_table) {
3711 set(kNextTableIndex, next_table);
3714 void SetRemovedIndexAt(int index, int removed_index) {
3715 return set(kRemovedHolesIndex + index, Smi::FromInt(removed_index));
3718 static const int kRemovedHolesIndex = kHashTableStartIndex;
3720 static const int kMaxCapacity =
3721 (FixedArray::kMaxLength - kHashTableStartIndex)
3722 / (1 + (kEntrySize * kLoadFactor));
3726 class JSSetIterator;
3729 class OrderedHashSet: public OrderedHashTable<
3730 OrderedHashSet, JSSetIterator, 1> {
3732 DECLARE_CAST(OrderedHashSet)
3736 class JSMapIterator;
3739 class OrderedHashMap
3740 : public OrderedHashTable<OrderedHashMap, JSMapIterator, 2> {
3742 DECLARE_CAST(OrderedHashMap)
3744 Object* ValueAt(int entry) {
3745 return get(EntryToIndex(entry) + kValueOffset);
3748 static const int kValueOffset = 1;
3752 template <int entrysize>
3753 class WeakHashTableShape : public BaseShape<Handle<Object> > {
3755 static inline bool IsMatch(Handle<Object> key, Object* other);
3756 static inline uint32_t Hash(Handle<Object> key);
3757 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3758 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3759 static const int kPrefixSize = 0;
3760 static const int kEntrySize = entrysize;
3764 // WeakHashTable maps keys that are arbitrary heap objects to heap object
3765 // values. The table wraps the keys in weak cells and store values directly.
3766 // Thus it references keys weakly and values strongly.
3767 class WeakHashTable: public HashTable<WeakHashTable,
3768 WeakHashTableShape<2>,
3771 WeakHashTable, WeakHashTableShape<2>, Handle<Object> > DerivedHashTable;
3773 DECLARE_CAST(WeakHashTable)
3775 // Looks up the value associated with the given key. The hole value is
3776 // returned in case the key is not present.
3777 Object* Lookup(Handle<HeapObject> key);
3779 // Adds (or overwrites) the value associated with the given key. Mapping a
3780 // key to the hole value causes removal of the whole entry.
3781 MUST_USE_RESULT static Handle<WeakHashTable> Put(Handle<WeakHashTable> table,
3782 Handle<HeapObject> key,
3783 Handle<HeapObject> value);
3785 static Handle<FixedArray> GetValues(Handle<WeakHashTable> table);
3788 friend class MarkCompactCollector;
3790 void AddEntry(int entry, Handle<WeakCell> key, Handle<HeapObject> value);
3792 // Returns the index to the value of an entry.
3793 static inline int EntryToValueIndex(int entry) {
3794 return EntryToIndex(entry) + 1;
3799 class WeakValueHashTable : public ObjectHashTable {
3801 DECLARE_CAST(WeakValueHashTable)
3804 // Looks up the value associated with the given key. The hole value is
3805 // returned in case the key is not present.
3806 Object* LookupWeak(Handle<Object> key);
3809 // Adds (or overwrites) the value associated with the given key. Mapping a
3810 // key to the hole value causes removal of the whole entry.
3811 MUST_USE_RESULT static Handle<WeakValueHashTable> PutWeak(
3812 Handle<WeakValueHashTable> table, Handle<Object> key,
3813 Handle<HeapObject> value);
3815 static Handle<FixedArray> GetWeakValues(Handle<WeakValueHashTable> table);
3819 // ScopeInfo represents information about different scopes of a source
3820 // program and the allocation of the scope's variables. Scope information
3821 // is stored in a compressed form in ScopeInfo objects and is used
3822 // at runtime (stack dumps, deoptimization, etc.).
3824 // This object provides quick access to scope info details for runtime
3826 class ScopeInfo : public FixedArray {
3828 DECLARE_CAST(ScopeInfo)
3830 // Return the type of this scope.
3831 ScopeType scope_type();
3833 // Does this scope call eval?
3836 // Return the language mode of this scope.
3837 LanguageMode language_mode();
3839 // Does this scope make a sloppy eval call?
3840 bool CallsSloppyEval() { return CallsEval() && is_sloppy(language_mode()); }
3842 // Return the total number of locals allocated on the stack and in the
3843 // context. This includes the parameters that are allocated in the context.
3846 // Return the number of stack slots for code. This number consists of two
3848 // 1. One stack slot per stack allocated local.
3849 // 2. One stack slot for the function name if it is stack allocated.
3850 int StackSlotCount();
3852 // Return the number of context slots for code if a context is allocated. This
3853 // number consists of three parts:
3854 // 1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
3855 // 2. One context slot per context allocated local.
3856 // 3. One context slot for the function name if it is context allocated.
3857 // Parameters allocated in the context count as context allocated locals. If
3858 // no contexts are allocated for this scope ContextLength returns 0.
3859 int ContextLength();
3861 // Does this scope declare a "this" binding?
3864 // Does this scope declare a "this" binding, and the "this" binding is stack-
3865 // or context-allocated?
3866 bool HasAllocatedReceiver();
3868 // Is this scope the scope of a named function expression?
3869 bool HasFunctionName();
3871 // Return if this has context allocated locals.
3872 bool HasHeapAllocatedLocals();
3874 // Return if contexts are allocated for this scope.
3877 // Return if this is a function scope with "use asm".
3878 bool IsAsmModule() { return AsmModuleField::decode(Flags()); }
3880 // Return if this is a nested function within an asm module scope.
3881 bool IsAsmFunction() { return AsmFunctionField::decode(Flags()); }
3883 bool HasSimpleParameters() {
3884 return HasSimpleParametersField::decode(Flags());
3887 // Return the function_name if present.
3888 String* FunctionName();
3890 // Return the name of the given parameter.
3891 String* ParameterName(int var);
3893 // Return the name of the given local.
3894 String* LocalName(int var);
3896 // Return the name of the given stack local.
3897 String* StackLocalName(int var);
3899 // Return the name of the given stack local.
3900 int StackLocalIndex(int var);
3902 // Return the name of the given context local.
3903 String* ContextLocalName(int var);
3905 // Return the mode of the given context local.
3906 VariableMode ContextLocalMode(int var);
3908 // Return the initialization flag of the given context local.
3909 InitializationFlag ContextLocalInitFlag(int var);
3911 // Return the initialization flag of the given context local.
3912 MaybeAssignedFlag ContextLocalMaybeAssignedFlag(int var);
3914 // Return true if this local was introduced by the compiler, and should not be
3915 // exposed to the user in a debugger.
3916 bool LocalIsSynthetic(int var);
3918 String* StrongModeFreeVariableName(int var);
3919 int StrongModeFreeVariableStartPosition(int var);
3920 int StrongModeFreeVariableEndPosition(int var);
3922 // Lookup support for serialized scope info. Returns the
3923 // the stack slot index for a given slot name if the slot is
3924 // present; otherwise returns a value < 0. The name must be an internalized
3926 int StackSlotIndex(String* name);
3928 // Lookup support for serialized scope info. Returns the
3929 // context slot index for a given slot name if the slot is present; otherwise
3930 // returns a value < 0. The name must be an internalized string.
3931 // If the slot is present and mode != NULL, sets *mode to the corresponding
3932 // mode for that variable.
3933 static int ContextSlotIndex(Handle<ScopeInfo> scope_info, Handle<String> name,
3934 VariableMode* mode, VariableLocation* location,
3935 InitializationFlag* init_flag,
3936 MaybeAssignedFlag* maybe_assigned_flag);
3938 // Lookup the name of a certain context slot by its index.
3939 String* ContextSlotName(int slot_index);
3941 // Lookup support for serialized scope info. Returns the
3942 // parameter index for a given parameter name if the parameter is present;
3943 // otherwise returns a value < 0. The name must be an internalized string.
3944 int ParameterIndex(String* name);
3946 // Lookup support for serialized scope info. Returns the function context
3947 // slot index if the function name is present and context-allocated (named
3948 // function expressions, only), otherwise returns a value < 0. The name
3949 // must be an internalized string.
3950 int FunctionContextSlotIndex(String* name, VariableMode* mode);
3952 // Lookup support for serialized scope info. Returns the receiver context
3953 // slot index if scope has a "this" binding, and the binding is
3954 // context-allocated. Otherwise returns a value < 0.
3955 int ReceiverContextSlotIndex();
3957 FunctionKind function_kind();
3959 static Handle<ScopeInfo> Create(Isolate* isolate, Zone* zone, Scope* scope);
3960 static Handle<ScopeInfo> CreateGlobalThisBinding(Isolate* isolate);
3962 // Serializes empty scope info.
3963 static ScopeInfo* Empty(Isolate* isolate);
3969 // The layout of the static part of a ScopeInfo is as follows. Each entry is
3970 // numeric and occupies one array slot.
3971 // 1. A set of properties of the scope
3972 // 2. The number of parameters. This only applies to function scopes. For
3973 // non-function scopes this is 0.
3974 // 3. The number of non-parameter variables allocated on the stack.
3975 // 4. The number of non-parameter and parameter variables allocated in the
3977 #define FOR_EACH_NUMERIC_FIELD(V) \
3980 V(StackLocalCount) \
3981 V(ContextLocalCount) \
3982 V(ContextGlobalCount) \
3983 V(StrongModeFreeVariableCount)
3985 #define FIELD_ACCESSORS(name) \
3986 void Set##name(int value) { \
3987 set(k##name, Smi::FromInt(value)); \
3990 if (length() > 0) { \
3991 return Smi::cast(get(k##name))->value(); \
3996 FOR_EACH_NUMERIC_FIELD(FIELD_ACCESSORS)
3997 #undef FIELD_ACCESSORS
4001 #define DECL_INDEX(name) k##name,
4002 FOR_EACH_NUMERIC_FIELD(DECL_INDEX)
4004 #undef FOR_EACH_NUMERIC_FIELD
4008 // The layout of the variable part of a ScopeInfo is as follows:
4009 // 1. ParameterEntries:
4010 // This part stores the names of the parameters for function scopes. One
4011 // slot is used per parameter, so in total this part occupies
4012 // ParameterCount() slots in the array. For other scopes than function
4013 // scopes ParameterCount() is 0.
4014 // 2. StackLocalFirstSlot:
4015 // Index of a first stack slot for stack local. Stack locals belonging to
4016 // this scope are located on a stack at slots starting from this index.
4017 // 3. StackLocalEntries:
4018 // Contains the names of local variables that are allocated on the stack,
4019 // in increasing order of the stack slot index. First local variable has
4020 // a stack slot index defined in StackLocalFirstSlot (point 2 above).
4021 // One slot is used per stack local, so in total this part occupies
4022 // StackLocalCount() slots in the array.
4023 // 4. ContextLocalNameEntries:
4024 // Contains the names of local variables and parameters that are allocated
4025 // in the context. They are stored in increasing order of the context slot
4026 // index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
4027 // context local, so in total this part occupies ContextLocalCount() slots
4029 // 5. ContextLocalInfoEntries:
4030 // Contains the variable modes and initialization flags corresponding to
4031 // the context locals in ContextLocalNameEntries. One slot is used per
4032 // context local, so in total this part occupies ContextLocalCount()
4033 // slots in the array.
4034 // 6. StrongModeFreeVariableNameEntries:
4035 // Stores the names of strong mode free variables.
4036 // 7. StrongModeFreeVariablePositionEntries:
4037 // Stores the locations (start and end position) of strong mode free
4039 // 8. RecieverEntryIndex:
4040 // If the scope binds a "this" value, one slot is reserved to hold the
4041 // context or stack slot index for the variable.
4042 // 9. FunctionNameEntryIndex:
4043 // If the scope belongs to a named function expression this part contains
4044 // information about the function variable. It always occupies two array
4045 // slots: a. The name of the function variable.
4046 // b. The context or stack slot index for the variable.
4047 int ParameterEntriesIndex();
4048 int StackLocalFirstSlotIndex();
4049 int StackLocalEntriesIndex();
4050 int ContextLocalNameEntriesIndex();
4051 int ContextGlobalNameEntriesIndex();
4052 int ContextLocalInfoEntriesIndex();
4053 int ContextGlobalInfoEntriesIndex();
4054 int StrongModeFreeVariableNameEntriesIndex();
4055 int StrongModeFreeVariablePositionEntriesIndex();
4056 int ReceiverEntryIndex();
4057 int FunctionNameEntryIndex();
4059 int Lookup(Handle<String> name, int start, int end, VariableMode* mode,
4060 VariableLocation* location, InitializationFlag* init_flag,
4061 MaybeAssignedFlag* maybe_assigned_flag);
4063 // Used for the function name variable for named function expressions, and for
4065 enum VariableAllocationInfo { NONE, STACK, CONTEXT, UNUSED };
4067 // Properties of scopes.
4068 class ScopeTypeField : public BitField<ScopeType, 0, 4> {};
4069 class CallsEvalField : public BitField<bool, ScopeTypeField::kNext, 1> {};
4070 STATIC_ASSERT(LANGUAGE_END == 3);
4071 class LanguageModeField
4072 : public BitField<LanguageMode, CallsEvalField::kNext, 2> {};
4073 class ReceiverVariableField
4074 : public BitField<VariableAllocationInfo, LanguageModeField::kNext, 2> {};
4075 class FunctionVariableField
4076 : public BitField<VariableAllocationInfo, ReceiverVariableField::kNext,
4078 class FunctionVariableMode
4079 : public BitField<VariableMode, FunctionVariableField::kNext, 3> {};
4080 class AsmModuleField : public BitField<bool, FunctionVariableMode::kNext, 1> {
4082 class AsmFunctionField : public BitField<bool, AsmModuleField::kNext, 1> {};
4083 class HasSimpleParametersField
4084 : public BitField<bool, AsmFunctionField::kNext, 1> {};
4085 class FunctionKindField
4086 : public BitField<FunctionKind, HasSimpleParametersField::kNext, 8> {};
4088 // BitFields representing the encoded information for context locals in the
4089 // ContextLocalInfoEntries part.
4090 class ContextLocalMode: public BitField<VariableMode, 0, 3> {};
4091 class ContextLocalInitFlag: public BitField<InitializationFlag, 3, 1> {};
4092 class ContextLocalMaybeAssignedFlag
4093 : public BitField<MaybeAssignedFlag, 4, 1> {};
4095 friend class ScopeIterator;
4099 // The cache for maps used by normalized (dictionary mode) objects.
4100 // Such maps do not have property descriptors, so a typical program
4101 // needs very limited number of distinct normalized maps.
4102 class NormalizedMapCache: public FixedArray {
4104 static Handle<NormalizedMapCache> New(Isolate* isolate);
4106 MUST_USE_RESULT MaybeHandle<Map> Get(Handle<Map> fast_map,
4107 PropertyNormalizationMode mode);
4108 void Set(Handle<Map> fast_map, Handle<Map> normalized_map);
4112 DECLARE_CAST(NormalizedMapCache)
4114 static inline bool IsNormalizedMapCache(const Object* obj);
4116 DECLARE_VERIFIER(NormalizedMapCache)
4118 static const int kEntries = 64;
4120 static inline int GetIndex(Handle<Map> map);
4122 // The following declarations hide base class methods.
4123 Object* get(int index);
4124 void set(int index, Object* value);
4128 // ByteArray represents fixed sized byte arrays. Used for the relocation info
4129 // that is attached to code objects.
4130 class ByteArray: public FixedArrayBase {
4132 inline int Size() { return RoundUp(length() + kHeaderSize, kPointerSize); }
4134 // Setter and getter.
4135 inline byte get(int index);
4136 inline void set(int index, byte value);
4138 // Treat contents as an int array.
4139 inline int get_int(int index);
4141 static int SizeFor(int length) {
4142 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4144 // We use byte arrays for free blocks in the heap. Given a desired size in
4145 // bytes that is a multiple of the word size and big enough to hold a byte
4146 // array, this function returns the number of elements a byte array should
4148 static int LengthFor(int size_in_bytes) {
4149 DCHECK(IsAligned(size_in_bytes, kPointerSize));
4150 DCHECK(size_in_bytes >= kHeaderSize);
4151 return size_in_bytes - kHeaderSize;
4154 // Returns data start address.
4155 inline Address GetDataStartAddress();
4157 // Returns a pointer to the ByteArray object for a given data start address.
4158 static inline ByteArray* FromDataStartAddress(Address address);
4160 DECLARE_CAST(ByteArray)
4162 // Dispatched behavior.
4163 inline int ByteArraySize() {
4164 return SizeFor(this->length());
4166 DECLARE_PRINTER(ByteArray)
4167 DECLARE_VERIFIER(ByteArray)
4169 // Layout description.
4170 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4172 // Maximal memory consumption for a single ByteArray.
4173 static const int kMaxSize = 512 * MB;
4174 // Maximal length of a single ByteArray.
4175 static const int kMaxLength = kMaxSize - kHeaderSize;
4178 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4182 // BytecodeArray represents a sequence of interpreter bytecodes.
4183 class BytecodeArray : public FixedArrayBase {
4185 static int SizeFor(int length) {
4186 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4189 // Setter and getter
4190 inline byte get(int index);
4191 inline void set(int index, byte value);
4193 // Returns data start address.
4194 inline Address GetFirstBytecodeAddress();
4196 // Accessors for frame size and the number of locals
4197 inline int frame_size() const;
4198 inline void set_frame_size(int value);
4200 DECLARE_CAST(BytecodeArray)
4202 // Dispatched behavior.
4203 inline int BytecodeArraySize() { return SizeFor(this->length()); }
4205 DECLARE_PRINTER(BytecodeArray)
4206 DECLARE_VERIFIER(BytecodeArray)
4208 void Disassemble(std::ostream& os);
4210 // Layout description.
4211 static const int kFrameSizeOffset = FixedArrayBase::kHeaderSize;
4212 static const int kHeaderSize = kFrameSizeOffset + kIntSize;
4214 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4216 // Maximal memory consumption for a single BytecodeArray.
4217 static const int kMaxSize = 512 * MB;
4218 // Maximal length of a single BytecodeArray.
4219 static const int kMaxLength = kMaxSize - kHeaderSize;
4222 DISALLOW_IMPLICIT_CONSTRUCTORS(BytecodeArray);
4226 // FreeSpace are fixed-size free memory blocks used by the heap and GC.
4227 // They look like heap objects (are heap object tagged and have a map) so that
4228 // the heap remains iterable. They have a size and a next pointer.
4229 // The next pointer is the raw address of the next FreeSpace object (or NULL)
4230 // in the free list.
4231 class FreeSpace: public HeapObject {
4233 // [size]: size of the free space including the header.
4234 inline int size() const;
4235 inline void set_size(int value);
4237 inline int nobarrier_size() const;
4238 inline void nobarrier_set_size(int value);
4240 inline int Size() { return size(); }
4242 // Accessors for the next field.
4243 inline FreeSpace* next();
4244 inline FreeSpace** next_address();
4245 inline void set_next(FreeSpace* next);
4247 inline static FreeSpace* cast(HeapObject* obj);
4249 // Dispatched behavior.
4250 DECLARE_PRINTER(FreeSpace)
4251 DECLARE_VERIFIER(FreeSpace)
4253 // Layout description.
4254 // Size is smi tagged when it is stored.
4255 static const int kSizeOffset = HeapObject::kHeaderSize;
4256 static const int kNextOffset = POINTER_SIZE_ALIGN(kSizeOffset + kPointerSize);
4259 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
4263 // V has parameters (Type, type, TYPE, C type, element_size)
4264 #define TYPED_ARRAYS(V) \
4265 V(Uint8, uint8, UINT8, uint8_t, 1) \
4266 V(Int8, int8, INT8, int8_t, 1) \
4267 V(Uint16, uint16, UINT16, uint16_t, 2) \
4268 V(Int16, int16, INT16, int16_t, 2) \
4269 V(Uint32, uint32, UINT32, uint32_t, 4) \
4270 V(Int32, int32, INT32, int32_t, 4) \
4271 V(Float32, float32, FLOAT32, float, 4) \
4272 V(Float64, float64, FLOAT64, double, 8) \
4273 V(Uint8Clamped, uint8_clamped, UINT8_CLAMPED, uint8_t, 1)
4276 class FixedTypedArrayBase: public FixedArrayBase {
4278 // [base_pointer]: Either points to the FixedTypedArrayBase itself or nullptr.
4279 DECL_ACCESSORS(base_pointer, Object)
4281 // [external_pointer]: Contains the offset between base_pointer and the start
4282 // of the data. If the base_pointer is a nullptr, the external_pointer
4283 // therefore points to the actual backing store.
4284 DECL_ACCESSORS(external_pointer, void)
4286 // Dispatched behavior.
4287 inline void FixedTypedArrayBaseIterateBody(ObjectVisitor* v);
4289 template <typename StaticVisitor>
4290 inline void FixedTypedArrayBaseIterateBody();
4292 DECLARE_CAST(FixedTypedArrayBase)
4294 static const int kBasePointerOffset = FixedArrayBase::kHeaderSize;
4295 static const int kExternalPointerOffset = kBasePointerOffset + kPointerSize;
4296 static const int kHeaderSize =
4297 DOUBLE_POINTER_ALIGN(kExternalPointerOffset + kPointerSize);
4299 static const int kDataOffset = kHeaderSize;
4303 static inline int TypedArraySize(InstanceType type, int length);
4304 inline int TypedArraySize(InstanceType type);
4306 // Use with care: returns raw pointer into heap.
4307 inline void* DataPtr();
4309 inline int DataSize();
4312 static inline int ElementSize(InstanceType type);
4314 inline int DataSize(InstanceType type);
4316 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
4320 template <class Traits>
4321 class FixedTypedArray: public FixedTypedArrayBase {
4323 typedef typename Traits::ElementType ElementType;
4324 static const InstanceType kInstanceType = Traits::kInstanceType;
4326 DECLARE_CAST(FixedTypedArray<Traits>)
4328 inline ElementType get_scalar(int index);
4329 static inline Handle<Object> get(Handle<FixedTypedArray> array, int index);
4330 inline void set(int index, ElementType value);
4332 static inline ElementType from_int(int value);
4333 static inline ElementType from_double(double value);
4335 // This accessor applies the correct conversion from Smi, HeapNumber
4337 void SetValue(uint32_t index, Object* value);
4339 DECLARE_PRINTER(FixedTypedArray)
4340 DECLARE_VERIFIER(FixedTypedArray)
4343 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
4346 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size) \
4347 class Type##ArrayTraits { \
4348 public: /* NOLINT */ \
4349 typedef elementType ElementType; \
4350 static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE; \
4351 static const char* Designator() { return #type " array"; } \
4352 static inline Handle<Object> ToHandle(Isolate* isolate, \
4353 elementType scalar); \
4354 static inline elementType defaultValue(); \
4357 typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
4359 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
4361 #undef FIXED_TYPED_ARRAY_TRAITS
4364 // DeoptimizationInputData is a fixed array used to hold the deoptimization
4365 // data for code generated by the Hydrogen/Lithium compiler. It also
4366 // contains information about functions that were inlined. If N different
4367 // functions were inlined then first N elements of the literal array will
4368 // contain these functions.
4371 class DeoptimizationInputData: public FixedArray {
4373 // Layout description. Indices in the array.
4374 static const int kTranslationByteArrayIndex = 0;
4375 static const int kInlinedFunctionCountIndex = 1;
4376 static const int kLiteralArrayIndex = 2;
4377 static const int kOsrAstIdIndex = 3;
4378 static const int kOsrPcOffsetIndex = 4;
4379 static const int kOptimizationIdIndex = 5;
4380 static const int kSharedFunctionInfoIndex = 6;
4381 static const int kWeakCellCacheIndex = 7;
4382 static const int kFirstDeoptEntryIndex = 8;
4384 // Offsets of deopt entry elements relative to the start of the entry.
4385 static const int kAstIdRawOffset = 0;
4386 static const int kTranslationIndexOffset = 1;
4387 static const int kArgumentsStackHeightOffset = 2;
4388 static const int kPcOffset = 3;
4389 static const int kDeoptEntrySize = 4;
4391 // Simple element accessors.
4392 #define DEFINE_ELEMENT_ACCESSORS(name, type) \
4394 return type::cast(get(k##name##Index)); \
4396 void Set##name(type* value) { \
4397 set(k##name##Index, value); \
4400 DEFINE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
4401 DEFINE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
4402 DEFINE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
4403 DEFINE_ELEMENT_ACCESSORS(OsrAstId, Smi)
4404 DEFINE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
4405 DEFINE_ELEMENT_ACCESSORS(OptimizationId, Smi)
4406 DEFINE_ELEMENT_ACCESSORS(SharedFunctionInfo, Object)
4407 DEFINE_ELEMENT_ACCESSORS(WeakCellCache, Object)
4409 #undef DEFINE_ELEMENT_ACCESSORS
4411 // Accessors for elements of the ith deoptimization entry.
4412 #define DEFINE_ENTRY_ACCESSORS(name, type) \
4413 type* name(int i) { \
4414 return type::cast(get(IndexForEntry(i) + k##name##Offset)); \
4416 void Set##name(int i, type* value) { \
4417 set(IndexForEntry(i) + k##name##Offset, value); \
4420 DEFINE_ENTRY_ACCESSORS(AstIdRaw, Smi)
4421 DEFINE_ENTRY_ACCESSORS(TranslationIndex, Smi)
4422 DEFINE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
4423 DEFINE_ENTRY_ACCESSORS(Pc, Smi)
4425 #undef DEFINE_DEOPT_ENTRY_ACCESSORS
4427 BailoutId AstId(int i) {
4428 return BailoutId(AstIdRaw(i)->value());
4431 void SetAstId(int i, BailoutId value) {
4432 SetAstIdRaw(i, Smi::FromInt(value.ToInt()));
4436 return (length() - kFirstDeoptEntryIndex) / kDeoptEntrySize;
4439 // Allocates a DeoptimizationInputData.
4440 static Handle<DeoptimizationInputData> New(Isolate* isolate,
4441 int deopt_entry_count,
4442 PretenureFlag pretenure);
4444 DECLARE_CAST(DeoptimizationInputData)
4446 #ifdef ENABLE_DISASSEMBLER
4447 void DeoptimizationInputDataPrint(std::ostream& os); // NOLINT
4451 static int IndexForEntry(int i) {
4452 return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
4456 static int LengthFor(int entry_count) { return IndexForEntry(entry_count); }
4460 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
4461 // data for code generated by the full compiler.
4462 // The format of the these objects is
4463 // [i * 2]: Ast ID for ith deoptimization.
4464 // [i * 2 + 1]: PC and state of ith deoptimization
4465 class DeoptimizationOutputData: public FixedArray {
4467 int DeoptPoints() { return length() / 2; }
4469 BailoutId AstId(int index) {
4470 return BailoutId(Smi::cast(get(index * 2))->value());
4473 void SetAstId(int index, BailoutId id) {
4474 set(index * 2, Smi::FromInt(id.ToInt()));
4477 Smi* PcAndState(int index) { return Smi::cast(get(1 + index * 2)); }
4478 void SetPcAndState(int index, Smi* offset) { set(1 + index * 2, offset); }
4480 static int LengthOfFixedArray(int deopt_points) {
4481 return deopt_points * 2;
4484 // Allocates a DeoptimizationOutputData.
4485 static Handle<DeoptimizationOutputData> New(Isolate* isolate,
4486 int number_of_deopt_points,
4487 PretenureFlag pretenure);
4489 DECLARE_CAST(DeoptimizationOutputData)
4491 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4492 void DeoptimizationOutputDataPrint(std::ostream& os); // NOLINT
4497 // HandlerTable is a fixed array containing entries for exception handlers in
4498 // the code object it is associated with. The tables comes in two flavors:
4499 // 1) Based on ranges: Used for unoptimized code. Contains one entry per
4500 // exception handler and a range representing the try-block covered by that
4501 // handler. Layout looks as follows:
4502 // [ range-start , range-end , handler-offset , stack-depth ]
4503 // 2) Based on return addresses: Used for turbofanned code. Contains one entry
4504 // per call-site that could throw an exception. Layout looks as follows:
4505 // [ return-address-offset , handler-offset ]
4506 class HandlerTable : public FixedArray {
4508 // Conservative prediction whether a given handler will locally catch an
4509 // exception or cause a re-throw to outside the code boundary. Since this is
4510 // undecidable it is merely an approximation (e.g. useful for debugger).
4511 enum CatchPrediction { UNCAUGHT, CAUGHT };
4513 // Accessors for handler table based on ranges.
4514 void SetRangeStart(int index, int value) {
4515 set(index * kRangeEntrySize + kRangeStartIndex, Smi::FromInt(value));
4517 void SetRangeEnd(int index, int value) {
4518 set(index * kRangeEntrySize + kRangeEndIndex, Smi::FromInt(value));
4520 void SetRangeHandler(int index, int offset, CatchPrediction prediction) {
4521 int value = HandlerOffsetField::encode(offset) |
4522 HandlerPredictionField::encode(prediction);
4523 set(index * kRangeEntrySize + kRangeHandlerIndex, Smi::FromInt(value));
4525 void SetRangeDepth(int index, int value) {
4526 set(index * kRangeEntrySize + kRangeDepthIndex, Smi::FromInt(value));
4529 // Accessors for handler table based on return addresses.
4530 void SetReturnOffset(int index, int value) {
4531 set(index * kReturnEntrySize + kReturnOffsetIndex, Smi::FromInt(value));
4533 void SetReturnHandler(int index, int offset, CatchPrediction prediction) {
4534 int value = HandlerOffsetField::encode(offset) |
4535 HandlerPredictionField::encode(prediction);
4536 set(index * kReturnEntrySize + kReturnHandlerIndex, Smi::FromInt(value));
4539 // Lookup handler in a table based on ranges.
4540 int LookupRange(int pc_offset, int* stack_depth, CatchPrediction* prediction);
4542 // Lookup handler in a table based on return addresses.
4543 int LookupReturn(int pc_offset, CatchPrediction* prediction);
4545 // Returns the required length of the underlying fixed array.
4546 static int LengthForRange(int entries) { return entries * kRangeEntrySize; }
4547 static int LengthForReturn(int entries) { return entries * kReturnEntrySize; }
4549 DECLARE_CAST(HandlerTable)
4551 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4552 void HandlerTableRangePrint(std::ostream& os); // NOLINT
4553 void HandlerTableReturnPrint(std::ostream& os); // NOLINT
4557 // Layout description for handler table based on ranges.
4558 static const int kRangeStartIndex = 0;
4559 static const int kRangeEndIndex = 1;
4560 static const int kRangeHandlerIndex = 2;
4561 static const int kRangeDepthIndex = 3;
4562 static const int kRangeEntrySize = 4;
4564 // Layout description for handler table based on return addresses.
4565 static const int kReturnOffsetIndex = 0;
4566 static const int kReturnHandlerIndex = 1;
4567 static const int kReturnEntrySize = 2;
4569 // Encoding of the {handler} field.
4570 class HandlerPredictionField : public BitField<CatchPrediction, 0, 1> {};
4571 class HandlerOffsetField : public BitField<int, 1, 30> {};
4575 // Code describes objects with on-the-fly generated machine code.
4576 class Code: public HeapObject {
4578 // Opaque data type for encapsulating code flags like kind, inline
4579 // cache state, and arguments count.
4580 typedef uint32_t Flags;
4582 #define NON_IC_KIND_LIST(V) \
4584 V(OPTIMIZED_FUNCTION) \
4590 #define IC_KIND_LIST(V) \
4601 #define CODE_KIND_LIST(V) \
4602 NON_IC_KIND_LIST(V) \
4606 #define DEFINE_CODE_KIND_ENUM(name) name,
4607 CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
4608 #undef DEFINE_CODE_KIND_ENUM
4612 // No more than 16 kinds. The value is currently encoded in four bits in
4614 STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
4616 static const char* Kind2String(Kind kind);
4624 static const int kPrologueOffsetNotSet = -1;
4626 #ifdef ENABLE_DISASSEMBLER
4628 static const char* ICState2String(InlineCacheState state);
4629 static const char* StubType2String(StubType type);
4630 static void PrintExtraICState(std::ostream& os, // NOLINT
4631 Kind kind, ExtraICState extra);
4632 void Disassemble(const char* name, std::ostream& os); // NOLINT
4633 #endif // ENABLE_DISASSEMBLER
4635 // [instruction_size]: Size of the native instructions
4636 inline int instruction_size() const;
4637 inline void set_instruction_size(int value);
4639 // [relocation_info]: Code relocation information
4640 DECL_ACCESSORS(relocation_info, ByteArray)
4641 void InvalidateRelocation();
4642 void InvalidateEmbeddedObjects();
4644 // [handler_table]: Fixed array containing offsets of exception handlers.
4645 DECL_ACCESSORS(handler_table, FixedArray)
4647 // [deoptimization_data]: Array containing data for deopt.
4648 DECL_ACCESSORS(deoptimization_data, FixedArray)
4650 // [raw_type_feedback_info]: This field stores various things, depending on
4651 // the kind of the code object.
4652 // FUNCTION => type feedback information.
4653 // STUB and ICs => major/minor key as Smi.
4654 DECL_ACCESSORS(raw_type_feedback_info, Object)
4655 inline Object* type_feedback_info();
4656 inline void set_type_feedback_info(
4657 Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
4658 inline uint32_t stub_key();
4659 inline void set_stub_key(uint32_t key);
4661 // [next_code_link]: Link for lists of optimized or deoptimized code.
4662 // Note that storage for this field is overlapped with typefeedback_info.
4663 DECL_ACCESSORS(next_code_link, Object)
4665 // [gc_metadata]: Field used to hold GC related metadata. The contents of this
4666 // field does not have to be traced during garbage collection since
4667 // it is only used by the garbage collector itself.
4668 DECL_ACCESSORS(gc_metadata, Object)
4670 // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
4671 // at the moment when this object was created.
4672 inline void set_ic_age(int count);
4673 inline int ic_age() const;
4675 // [prologue_offset]: Offset of the function prologue, used for aging
4676 // FUNCTIONs and OPTIMIZED_FUNCTIONs.
4677 inline int prologue_offset() const;
4678 inline void set_prologue_offset(int offset);
4680 // [constant_pool offset]: Offset of the constant pool.
4681 // Valid for FLAG_enable_embedded_constant_pool only
4682 inline int constant_pool_offset() const;
4683 inline void set_constant_pool_offset(int offset);
4685 // Unchecked accessors to be used during GC.
4686 inline ByteArray* unchecked_relocation_info();
4688 inline int relocation_size();
4690 // [flags]: Various code flags.
4691 inline Flags flags();
4692 inline void set_flags(Flags flags);
4694 // [flags]: Access to specific code flags.
4696 inline InlineCacheState ic_state(); // Only valid for IC stubs.
4697 inline ExtraICState extra_ic_state(); // Only valid for IC stubs.
4699 inline StubType type(); // Only valid for monomorphic IC stubs.
4701 // Testers for IC stub kinds.
4702 inline bool is_inline_cache_stub();
4703 inline bool is_debug_stub();
4704 inline bool is_handler() { return kind() == HANDLER; }
4705 inline bool is_load_stub() { return kind() == LOAD_IC; }
4706 inline bool is_keyed_load_stub() { return kind() == KEYED_LOAD_IC; }
4707 inline bool is_store_stub() { return kind() == STORE_IC; }
4708 inline bool is_keyed_store_stub() { return kind() == KEYED_STORE_IC; }
4709 inline bool is_call_stub() { return kind() == CALL_IC; }
4710 inline bool is_binary_op_stub() { return kind() == BINARY_OP_IC; }
4711 inline bool is_compare_ic_stub() { return kind() == COMPARE_IC; }
4712 inline bool is_compare_nil_ic_stub() { return kind() == COMPARE_NIL_IC; }
4713 inline bool is_to_boolean_ic_stub() { return kind() == TO_BOOLEAN_IC; }
4714 inline bool is_keyed_stub();
4715 inline bool is_optimized_code() { return kind() == OPTIMIZED_FUNCTION; }
4716 inline bool embeds_maps_weakly() {
4718 return (k == LOAD_IC || k == STORE_IC || k == KEYED_LOAD_IC ||
4719 k == KEYED_STORE_IC || k == COMPARE_NIL_IC) &&
4720 ic_state() == MONOMORPHIC;
4723 inline bool IsCodeStubOrIC();
4725 inline void set_raw_kind_specific_flags1(int value);
4726 inline void set_raw_kind_specific_flags2(int value);
4728 // [is_crankshafted]: For kind STUB or ICs, tells whether or not a code
4729 // object was generated by either the hydrogen or the TurboFan optimizing
4730 // compiler (but it may not be an optimized function).
4731 inline bool is_crankshafted();
4732 inline bool is_hydrogen_stub(); // Crankshafted, but not a function.
4733 inline void set_is_crankshafted(bool value);
4735 // [is_turbofanned]: For kind STUB or OPTIMIZED_FUNCTION, tells whether the
4736 // code object was generated by the TurboFan optimizing compiler.
4737 inline bool is_turbofanned();
4738 inline void set_is_turbofanned(bool value);
4740 // [can_have_weak_objects]: For kind OPTIMIZED_FUNCTION, tells whether the
4741 // embedded objects in code should be treated weakly.
4742 inline bool can_have_weak_objects();
4743 inline void set_can_have_weak_objects(bool value);
4745 // [has_deoptimization_support]: For FUNCTION kind, tells if it has
4746 // deoptimization support.
4747 inline bool has_deoptimization_support();
4748 inline void set_has_deoptimization_support(bool value);
4750 // [has_debug_break_slots]: For FUNCTION kind, tells if it has
4751 // been compiled with debug break slots.
4752 inline bool has_debug_break_slots();
4753 inline void set_has_debug_break_slots(bool value);
4755 // [has_reloc_info_for_serialization]: For FUNCTION kind, tells if its
4756 // reloc info includes runtime and external references to support
4757 // serialization/deserialization.
4758 inline bool has_reloc_info_for_serialization();
4759 inline void set_has_reloc_info_for_serialization(bool value);
4761 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
4762 // how long the function has been marked for OSR and therefore which
4763 // level of loop nesting we are willing to do on-stack replacement
4765 inline void set_allow_osr_at_loop_nesting_level(int level);
4766 inline int allow_osr_at_loop_nesting_level();
4768 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
4769 // the code object was seen on the stack with no IC patching going on.
4770 inline int profiler_ticks();
4771 inline void set_profiler_ticks(int ticks);
4773 // [builtin_index]: For BUILTIN kind, tells which builtin index it has.
4774 // For builtins, tells which builtin index it has.
4775 // Note that builtins can have a code kind other than BUILTIN, which means
4776 // that for arbitrary code objects, this index value may be random garbage.
4777 // To verify in that case, compare the code object to the indexed builtin.
4778 inline int builtin_index();
4779 inline void set_builtin_index(int id);
4781 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
4782 // reserved in the code prologue.
4783 inline unsigned stack_slots();
4784 inline void set_stack_slots(unsigned slots);
4786 // [safepoint_table_start]: For kind OPTIMIZED_FUNCTION, the offset in
4787 // the instruction stream where the safepoint table starts.
4788 inline unsigned safepoint_table_offset();
4789 inline void set_safepoint_table_offset(unsigned offset);
4791 // [back_edge_table_start]: For kind FUNCTION, the offset in the
4792 // instruction stream where the back edge table starts.
4793 inline unsigned back_edge_table_offset();
4794 inline void set_back_edge_table_offset(unsigned offset);
4796 inline bool back_edges_patched_for_osr();
4798 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
4799 inline uint16_t to_boolean_state();
4801 // [has_function_cache]: For kind STUB tells whether there is a function
4802 // cache is passed to the stub.
4803 inline bool has_function_cache();
4804 inline void set_has_function_cache(bool flag);
4807 // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
4808 // the code is going to be deoptimized because of dead embedded maps.
4809 inline bool marked_for_deoptimization();
4810 inline void set_marked_for_deoptimization(bool flag);
4812 // [constant_pool]: The constant pool for this function.
4813 inline Address constant_pool();
4815 // Get the safepoint entry for the given pc.
4816 SafepointEntry GetSafepointEntry(Address pc);
4818 // Find an object in a stub with a specified map
4819 Object* FindNthObject(int n, Map* match_map);
4821 // Find the first allocation site in an IC stub.
4822 AllocationSite* FindFirstAllocationSite();
4824 // Find the first map in an IC stub.
4825 Map* FindFirstMap();
4826 void FindAllMaps(MapHandleList* maps);
4828 // Find the first handler in an IC stub.
4829 Code* FindFirstHandler();
4831 // Find |length| handlers and put them into |code_list|. Returns false if not
4832 // enough handlers can be found.
4833 bool FindHandlers(CodeHandleList* code_list, int length = -1);
4835 // Find the handler for |map|.
4836 MaybeHandle<Code> FindHandlerForMap(Map* map);
4838 // Find the first name in an IC stub.
4839 Name* FindFirstName();
4841 class FindAndReplacePattern;
4842 // For each (map-to-find, object-to-replace) pair in the pattern, this
4843 // function replaces the corresponding placeholder in the code with the
4844 // object-to-replace. The function assumes that pairs in the pattern come in
4845 // the same order as the placeholders in the code.
4846 // If the placeholder is a weak cell, then the value of weak cell is matched
4847 // against the map-to-find.
4848 void FindAndReplace(const FindAndReplacePattern& pattern);
4850 // The entire code object including its header is copied verbatim to the
4851 // snapshot so that it can be written in one, fast, memcpy during
4852 // deserialization. The deserializer will overwrite some pointers, rather
4853 // like a runtime linker, but the random allocation addresses used in the
4854 // mksnapshot process would still be present in the unlinked snapshot data,
4855 // which would make snapshot production non-reproducible. This method wipes
4856 // out the to-be-overwritten header data for reproducible snapshots.
4857 inline void WipeOutHeader();
4859 // Flags operations.
4860 static inline Flags ComputeFlags(
4861 Kind kind, InlineCacheState ic_state = UNINITIALIZED,
4862 ExtraICState extra_ic_state = kNoExtraICState, StubType type = NORMAL,
4863 CacheHolderFlag holder = kCacheOnReceiver);
4865 static inline Flags ComputeMonomorphicFlags(
4866 Kind kind, ExtraICState extra_ic_state = kNoExtraICState,
4867 CacheHolderFlag holder = kCacheOnReceiver, StubType type = NORMAL);
4869 static inline Flags ComputeHandlerFlags(
4870 Kind handler_kind, StubType type = NORMAL,
4871 CacheHolderFlag holder = kCacheOnReceiver);
4873 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
4874 static inline StubType ExtractTypeFromFlags(Flags flags);
4875 static inline CacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
4876 static inline Kind ExtractKindFromFlags(Flags flags);
4877 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
4879 static inline Flags RemoveTypeFromFlags(Flags flags);
4880 static inline Flags RemoveTypeAndHolderFromFlags(Flags flags);
4882 // Convert a target address into a code object.
4883 static inline Code* GetCodeFromTargetAddress(Address address);
4885 // Convert an entry address into an object.
4886 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
4888 // Returns the address of the first instruction.
4889 inline byte* instruction_start();
4891 // Returns the address right after the last instruction.
4892 inline byte* instruction_end();
4894 // Returns the size of the instructions, padding, and relocation information.
4895 inline int body_size();
4897 // Returns the address of the first relocation info (read backwards!).
4898 inline byte* relocation_start();
4900 // Code entry point.
4901 inline byte* entry();
4903 // Returns true if pc is inside this object's instructions.
4904 inline bool contains(byte* pc);
4906 // Relocate the code by delta bytes. Called to signal that this code
4907 // object has been moved by delta bytes.
4908 void Relocate(intptr_t delta);
4910 // Migrate code described by desc.
4911 void CopyFrom(const CodeDesc& desc);
4913 // Returns the object size for a given body (used for allocation).
4914 static int SizeFor(int body_size) {
4915 DCHECK_SIZE_TAG_ALIGNED(body_size);
4916 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
4919 // Calculate the size of the code object to report for log events. This takes
4920 // the layout of the code object into account.
4921 int ExecutableSize() {
4922 // Check that the assumptions about the layout of the code object holds.
4923 DCHECK_EQ(static_cast<int>(instruction_start() - address()),
4925 return instruction_size() + Code::kHeaderSize;
4928 // Locating source position.
4929 int SourcePosition(Address pc);
4930 int SourceStatementPosition(Address pc);
4934 // Dispatched behavior.
4935 int CodeSize() { return SizeFor(body_size()); }
4936 inline void CodeIterateBody(ObjectVisitor* v);
4938 template<typename StaticVisitor>
4939 inline void CodeIterateBody(Heap* heap);
4941 DECLARE_PRINTER(Code)
4942 DECLARE_VERIFIER(Code)
4944 void ClearInlineCaches();
4945 void ClearInlineCaches(Kind kind);
4947 BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
4948 uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
4950 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
4952 kToBeExecutedOnceCodeAge = -3,
4953 kNotExecutedCodeAge = -2,
4954 kExecutedOnceCodeAge = -1,
4956 CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
4958 kFirstCodeAge = kToBeExecutedOnceCodeAge,
4959 kLastCodeAge = kAfterLastCodeAge - 1,
4960 kCodeAgeCount = kAfterLastCodeAge - kFirstCodeAge - 1,
4961 kIsOldCodeAge = kSexagenarianCodeAge,
4962 kPreAgedCodeAge = kIsOldCodeAge - 1
4964 #undef DECLARE_CODE_AGE_ENUM
4966 // Code aging. Indicates how many full GCs this code has survived without
4967 // being entered through the prologue. Used to determine when it is
4968 // relatively safe to flush this code object and replace it with the lazy
4969 // compilation stub.
4970 static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
4971 static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
4972 void MakeYoung(Isolate* isolate);
4973 void MarkToBeExecutedOnce(Isolate* isolate);
4974 void MakeOlder(MarkingParity);
4975 static bool IsYoungSequence(Isolate* isolate, byte* sequence);
4978 static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
4979 return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
4982 void PrintDeoptLocation(FILE* out, Address pc);
4983 bool CanDeoptAt(Address pc);
4986 void VerifyEmbeddedObjectsDependency();
4990 enum VerifyMode { kNoContextSpecificPointers, kNoContextRetainingPointers };
4991 void VerifyEmbeddedObjects(VerifyMode mode = kNoContextRetainingPointers);
4992 static void VerifyRecompiledCode(Code* old_code, Code* new_code);
4995 inline bool CanContainWeakObjects() {
4996 // is_turbofanned() implies !can_have_weak_objects().
4997 DCHECK(!is_optimized_code() || !is_turbofanned() ||
4998 !can_have_weak_objects());
4999 return is_optimized_code() && can_have_weak_objects();
5002 inline bool IsWeakObject(Object* object) {
5003 return (CanContainWeakObjects() && IsWeakObjectInOptimizedCode(object));
5006 static inline bool IsWeakObjectInOptimizedCode(Object* object);
5008 static Handle<WeakCell> WeakCellFor(Handle<Code> code);
5009 WeakCell* CachedWeakCell();
5011 // Max loop nesting marker used to postpose OSR. We don't take loop
5012 // nesting that is deeper than 5 levels into account.
5013 static const int kMaxLoopNestingMarker = 6;
5015 static const int kConstantPoolSize =
5016 FLAG_enable_embedded_constant_pool ? kIntSize : 0;
5018 // Layout description.
5019 static const int kRelocationInfoOffset = HeapObject::kHeaderSize;
5020 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
5021 static const int kDeoptimizationDataOffset =
5022 kHandlerTableOffset + kPointerSize;
5023 // For FUNCTION kind, we store the type feedback info here.
5024 static const int kTypeFeedbackInfoOffset =
5025 kDeoptimizationDataOffset + kPointerSize;
5026 static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
5027 static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
5028 static const int kInstructionSizeOffset = kGCMetadataOffset + kPointerSize;
5029 static const int kICAgeOffset = kInstructionSizeOffset + kIntSize;
5030 static const int kFlagsOffset = kICAgeOffset + kIntSize;
5031 static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
5032 static const int kKindSpecificFlags2Offset =
5033 kKindSpecificFlags1Offset + kIntSize;
5034 // Note: We might be able to squeeze this into the flags above.
5035 static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
5036 static const int kConstantPoolOffset = kPrologueOffset + kIntSize;
5037 static const int kHeaderPaddingStart =
5038 kConstantPoolOffset + kConstantPoolSize;
5040 // Add padding to align the instruction start following right after
5041 // the Code object header.
5042 static const int kHeaderSize =
5043 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
5045 // Byte offsets within kKindSpecificFlags1Offset.
5046 static const int kFullCodeFlags = kKindSpecificFlags1Offset;
5047 class FullCodeFlagsHasDeoptimizationSupportField:
5048 public BitField<bool, 0, 1> {}; // NOLINT
5049 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
5050 class FullCodeFlagsHasRelocInfoForSerialization
5051 : public BitField<bool, 2, 1> {};
5052 // Bit 3 in this bitfield is unused.
5053 class ProfilerTicksField : public BitField<int, 4, 28> {};
5055 // Flags layout. BitField<type, shift, size>.
5056 class ICStateField : public BitField<InlineCacheState, 0, 4> {};
5057 class TypeField : public BitField<StubType, 4, 1> {};
5058 class CacheHolderField : public BitField<CacheHolderFlag, 5, 2> {};
5059 class KindField : public BitField<Kind, 7, 4> {};
5060 class ExtraICStateField: public BitField<ExtraICState, 11,
5061 PlatformSmiTagging::kSmiValueSize - 11 + 1> {}; // NOLINT
5063 // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
5064 static const int kStackSlotsFirstBit = 0;
5065 static const int kStackSlotsBitCount = 24;
5066 static const int kHasFunctionCacheBit =
5067 kStackSlotsFirstBit + kStackSlotsBitCount;
5068 static const int kMarkedForDeoptimizationBit = kHasFunctionCacheBit + 1;
5069 static const int kIsTurbofannedBit = kMarkedForDeoptimizationBit + 1;
5070 static const int kCanHaveWeakObjects = kIsTurbofannedBit + 1;
5072 STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
5073 STATIC_ASSERT(kCanHaveWeakObjects + 1 <= 32);
5075 class StackSlotsField: public BitField<int,
5076 kStackSlotsFirstBit, kStackSlotsBitCount> {}; // NOLINT
5077 class HasFunctionCacheField : public BitField<bool, kHasFunctionCacheBit, 1> {
5079 class MarkedForDeoptimizationField
5080 : public BitField<bool, kMarkedForDeoptimizationBit, 1> {}; // NOLINT
5081 class IsTurbofannedField : public BitField<bool, kIsTurbofannedBit, 1> {
5083 class CanHaveWeakObjectsField
5084 : public BitField<bool, kCanHaveWeakObjects, 1> {}; // NOLINT
5086 // KindSpecificFlags2 layout (ALL)
5087 static const int kIsCrankshaftedBit = 0;
5088 class IsCrankshaftedField: public BitField<bool,
5089 kIsCrankshaftedBit, 1> {}; // NOLINT
5091 // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
5092 static const int kSafepointTableOffsetFirstBit = kIsCrankshaftedBit + 1;
5093 static const int kSafepointTableOffsetBitCount = 30;
5095 STATIC_ASSERT(kSafepointTableOffsetFirstBit +
5096 kSafepointTableOffsetBitCount <= 32);
5097 STATIC_ASSERT(1 + kSafepointTableOffsetBitCount <= 32);
5099 class SafepointTableOffsetField: public BitField<int,
5100 kSafepointTableOffsetFirstBit,
5101 kSafepointTableOffsetBitCount> {}; // NOLINT
5103 // KindSpecificFlags2 layout (FUNCTION)
5104 class BackEdgeTableOffsetField: public BitField<int,
5105 kIsCrankshaftedBit + 1, 27> {}; // NOLINT
5106 class AllowOSRAtLoopNestingLevelField: public BitField<int,
5107 kIsCrankshaftedBit + 1 + 27, 4> {}; // NOLINT
5108 STATIC_ASSERT(AllowOSRAtLoopNestingLevelField::kMax >= kMaxLoopNestingMarker);
5110 static const int kArgumentsBits = 16;
5111 static const int kMaxArguments = (1 << kArgumentsBits) - 1;
5113 // This constant should be encodable in an ARM instruction.
5114 static const int kFlagsNotUsedInLookup =
5115 TypeField::kMask | CacheHolderField::kMask;
5118 friend class RelocIterator;
5119 friend class Deoptimizer; // For FindCodeAgeSequence.
5121 void ClearInlineCaches(Kind* kind);
5124 byte* FindCodeAgeSequence();
5125 static void GetCodeAgeAndParity(Code* code, Age* age,
5126 MarkingParity* parity);
5127 static void GetCodeAgeAndParity(Isolate* isolate, byte* sequence, Age* age,
5128 MarkingParity* parity);
5129 static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
5131 // Code aging -- platform-specific
5132 static void PatchPlatformCodeAge(Isolate* isolate,
5133 byte* sequence, Age age,
5134 MarkingParity parity);
5136 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5140 // This class describes the layout of dependent codes array of a map. The
5141 // array is partitioned into several groups of dependent codes. Each group
5142 // contains codes with the same dependency on the map. The array has the
5143 // following layout for n dependency groups:
5145 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5146 // | C1 | C2 | ... | Cn | group 1 | group 2 | ... | group n | undefined |
5147 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5149 // The first n elements are Smis, each of them specifies the number of codes
5150 // in the corresponding group. The subsequent elements contain grouped code
5151 // objects in weak cells. The suffix of the array can be filled with the
5152 // undefined value if the number of codes is less than the length of the
5153 // array. The order of the code objects within a group is not preserved.
5155 // All code indexes used in the class are counted starting from the first
5156 // code object of the first group. In other words, code index 0 corresponds
5157 // to array index n = kCodesStartIndex.
5159 class DependentCode: public FixedArray {
5161 enum DependencyGroup {
5162 // Group of code that weakly embed this map and depend on being
5163 // deoptimized when the map is garbage collected.
5165 // Group of code that embed a transition to this map, and depend on being
5166 // deoptimized when the transition is replaced by a new version.
5168 // Group of code that omit run-time prototype checks for prototypes
5169 // described by this map. The group is deoptimized whenever an object
5170 // described by this map changes shape (and transitions to a new map),
5171 // possibly invalidating the assumptions embedded in the code.
5172 kPrototypeCheckGroup,
5173 // Group of code that depends on global property values in property cells
5174 // not being changed.
5175 kPropertyCellChangedGroup,
5176 // Group of code that omit run-time type checks for the field(s) introduced
5179 // Group of code that omit run-time type checks for initial maps of
5181 kInitialMapChangedGroup,
5182 // Group of code that depends on tenuring information in AllocationSites
5183 // not being changed.
5184 kAllocationSiteTenuringChangedGroup,
5185 // Group of code that depends on element transition information in
5186 // AllocationSites not being changed.
5187 kAllocationSiteTransitionChangedGroup
5190 static const int kGroupCount = kAllocationSiteTransitionChangedGroup + 1;
5192 // Array for holding the index of the first code object of each group.
5193 // The last element stores the total number of code objects.
5194 class GroupStartIndexes {
5196 explicit GroupStartIndexes(DependentCode* entries);
5197 void Recompute(DependentCode* entries);
5198 int at(int i) { return start_indexes_[i]; }
5199 int number_of_entries() { return start_indexes_[kGroupCount]; }
5201 int start_indexes_[kGroupCount + 1];
5204 bool Contains(DependencyGroup group, WeakCell* code_cell);
5206 static Handle<DependentCode> InsertCompilationDependencies(
5207 Handle<DependentCode> entries, DependencyGroup group,
5208 Handle<Foreign> info);
5210 static Handle<DependentCode> InsertWeakCode(Handle<DependentCode> entries,
5211 DependencyGroup group,
5212 Handle<WeakCell> code_cell);
5214 void UpdateToFinishedCode(DependencyGroup group, Foreign* info,
5215 WeakCell* code_cell);
5217 void RemoveCompilationDependencies(DependentCode::DependencyGroup group,
5220 void DeoptimizeDependentCodeGroup(Isolate* isolate,
5221 DependentCode::DependencyGroup group);
5223 bool MarkCodeForDeoptimization(Isolate* isolate,
5224 DependentCode::DependencyGroup group);
5226 // The following low-level accessors should only be used by this class
5227 // and the mark compact collector.
5228 inline int number_of_entries(DependencyGroup group);
5229 inline void set_number_of_entries(DependencyGroup group, int value);
5230 inline Object* object_at(int i);
5231 inline void set_object_at(int i, Object* object);
5232 inline void clear_at(int i);
5233 inline void copy(int from, int to);
5234 DECLARE_CAST(DependentCode)
5236 static const char* DependencyGroupName(DependencyGroup group);
5237 static void SetMarkedForDeoptimization(Code* code, DependencyGroup group);
5240 static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5241 DependencyGroup group,
5242 Handle<Object> object);
5243 static Handle<DependentCode> EnsureSpace(Handle<DependentCode> entries);
5244 // Make a room at the end of the given group by moving out the first
5245 // code objects of the subsequent groups.
5246 inline void ExtendGroup(DependencyGroup group);
5247 // Compact by removing cleared weak cells and return true if there was
5248 // any cleared weak cell.
5250 static int Grow(int number_of_entries) {
5251 if (number_of_entries < 5) return number_of_entries + 1;
5252 return number_of_entries * 5 / 4;
5254 static const int kCodesStartIndex = kGroupCount;
5258 class PrototypeInfo;
5261 // All heap objects have a Map that describes their structure.
5262 // A Map contains information about:
5263 // - Size information about the object
5264 // - How to iterate over an object (for garbage collection)
5265 class Map: public HeapObject {
5268 // Size in bytes or kVariableSizeSentinel if instances do not have
5270 inline int instance_size();
5271 inline void set_instance_size(int value);
5273 // Only to clear an unused byte, remove once byte is used.
5274 inline void clear_unused();
5276 // [inobject_properties_or_constructor_function_index]: Provides access
5277 // to the inobject properties in case of JSObject maps, or the constructor
5278 // function index in case of primitive maps.
5279 inline int inobject_properties_or_constructor_function_index();
5280 inline void set_inobject_properties_or_constructor_function_index(int value);
5281 // Count of properties allocated in the object (JSObject only).
5282 inline int GetInObjectProperties();
5283 inline void SetInObjectProperties(int value);
5284 // Index of the constructor function in the native context (primitives only),
5285 // or the special sentinel value to indicate that there is no object wrapper
5286 // for the primitive (i.e. in case of null or undefined).
5287 static const int kNoConstructorFunctionIndex = 0;
5288 inline int GetConstructorFunctionIndex();
5289 inline void SetConstructorFunctionIndex(int value);
5292 inline InstanceType instance_type();
5293 inline void set_instance_type(InstanceType value);
5295 // Tells how many unused property fields are available in the
5296 // instance (only used for JSObject in fast mode).
5297 inline int unused_property_fields();
5298 inline void set_unused_property_fields(int value);
5301 inline byte bit_field() const;
5302 inline void set_bit_field(byte value);
5305 inline byte bit_field2() const;
5306 inline void set_bit_field2(byte value);
5309 inline uint32_t bit_field3() const;
5310 inline void set_bit_field3(uint32_t bits);
5312 class EnumLengthBits: public BitField<int,
5313 0, kDescriptorIndexBitCount> {}; // NOLINT
5314 class NumberOfOwnDescriptorsBits: public BitField<int,
5315 kDescriptorIndexBitCount, kDescriptorIndexBitCount> {}; // NOLINT
5316 STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
5317 class DictionaryMap : public BitField<bool, 20, 1> {};
5318 class OwnsDescriptors : public BitField<bool, 21, 1> {};
5319 class HasInstanceCallHandler : public BitField<bool, 22, 1> {};
5320 class Deprecated : public BitField<bool, 23, 1> {};
5321 class IsUnstable : public BitField<bool, 24, 1> {};
5322 class IsMigrationTarget : public BitField<bool, 25, 1> {};
5323 class IsStrong : public BitField<bool, 26, 1> {};
5326 // Keep this bit field at the very end for better code in
5327 // Builtins::kJSConstructStubGeneric stub.
5328 // This counter is used for in-object slack tracking and for map aging.
5329 // The in-object slack tracking is considered enabled when the counter is
5330 // in the range [kSlackTrackingCounterStart, kSlackTrackingCounterEnd].
5331 class Counter : public BitField<int, 28, 4> {};
5332 static const int kSlackTrackingCounterStart = 14;
5333 static const int kSlackTrackingCounterEnd = 8;
5334 static const int kRetainingCounterStart = kSlackTrackingCounterEnd - 1;
5335 static const int kRetainingCounterEnd = 0;
5337 // Tells whether the object in the prototype property will be used
5338 // for instances created from this function. If the prototype
5339 // property is set to a value that is not a JSObject, the prototype
5340 // property will not be used to create instances of the function.
5341 // See ECMA-262, 13.2.2.
5342 inline void set_non_instance_prototype(bool value);
5343 inline bool has_non_instance_prototype();
5345 // Tells whether function has special prototype property. If not, prototype
5346 // property will not be created when accessed (will return undefined),
5347 // and construction from this function will not be allowed.
5348 inline void set_function_with_prototype(bool value);
5349 inline bool function_with_prototype();
5351 // Tells whether the instance with this map should be ignored by the
5352 // Object.getPrototypeOf() function and the __proto__ accessor.
5353 inline void set_is_hidden_prototype() {
5354 set_bit_field(bit_field() | (1 << kIsHiddenPrototype));
5357 inline bool is_hidden_prototype() {
5358 return ((1 << kIsHiddenPrototype) & bit_field()) != 0;
5361 // Records and queries whether the instance has a named interceptor.
5362 inline void set_has_named_interceptor() {
5363 set_bit_field(bit_field() | (1 << kHasNamedInterceptor));
5366 inline bool has_named_interceptor() {
5367 return ((1 << kHasNamedInterceptor) & bit_field()) != 0;
5370 // Records and queries whether the instance has an indexed interceptor.
5371 inline void set_has_indexed_interceptor() {
5372 set_bit_field(bit_field() | (1 << kHasIndexedInterceptor));
5375 inline bool has_indexed_interceptor() {
5376 return ((1 << kHasIndexedInterceptor) & bit_field()) != 0;
5379 // Tells whether the instance is undetectable.
5380 // An undetectable object is a special class of JSObject: 'typeof' operator
5381 // returns undefined, ToBoolean returns false. Otherwise it behaves like
5382 // a normal JS object. It is useful for implementing undetectable
5383 // document.all in Firefox & Safari.
5384 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
5385 inline void set_is_undetectable() {
5386 set_bit_field(bit_field() | (1 << kIsUndetectable));
5389 inline bool is_undetectable() {
5390 return ((1 << kIsUndetectable) & bit_field()) != 0;
5393 // Tells whether the instance has a call-as-function handler.
5394 inline void set_is_observed() {
5395 set_bit_field(bit_field() | (1 << kIsObserved));
5398 inline bool is_observed() {
5399 return ((1 << kIsObserved) & bit_field()) != 0;
5402 inline void set_is_strong();
5403 inline bool is_strong();
5404 inline void set_is_extensible(bool value);
5405 inline bool is_extensible();
5406 inline void set_is_prototype_map(bool value);
5407 inline bool is_prototype_map() const;
5409 inline void set_elements_kind(ElementsKind elements_kind) {
5410 DCHECK(static_cast<int>(elements_kind) < kElementsKindCount);
5411 DCHECK(kElementsKindCount <= (1 << Map::ElementsKindBits::kSize));
5412 set_bit_field2(Map::ElementsKindBits::update(bit_field2(), elements_kind));
5413 DCHECK(this->elements_kind() == elements_kind);
5416 inline ElementsKind elements_kind() {
5417 return Map::ElementsKindBits::decode(bit_field2());
5420 // Tells whether the instance has fast elements that are only Smis.
5421 inline bool has_fast_smi_elements() {
5422 return IsFastSmiElementsKind(elements_kind());
5425 // Tells whether the instance has fast elements.
5426 inline bool has_fast_object_elements() {
5427 return IsFastObjectElementsKind(elements_kind());
5430 inline bool has_fast_smi_or_object_elements() {
5431 return IsFastSmiOrObjectElementsKind(elements_kind());
5434 inline bool has_fast_double_elements() {
5435 return IsFastDoubleElementsKind(elements_kind());
5438 inline bool has_fast_elements() {
5439 return IsFastElementsKind(elements_kind());
5442 inline bool has_sloppy_arguments_elements() {
5443 return IsSloppyArgumentsElements(elements_kind());
5446 inline bool has_fixed_typed_array_elements() {
5447 return IsFixedTypedArrayElementsKind(elements_kind());
5450 inline bool has_dictionary_elements() {
5451 return IsDictionaryElementsKind(elements_kind());
5454 static bool IsValidElementsTransition(ElementsKind from_kind,
5455 ElementsKind to_kind);
5457 // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
5458 // map with DICTIONARY_ELEMENTS was found in the prototype chain.
5459 bool DictionaryElementsInPrototypeChainOnly();
5461 inline Map* ElementsTransitionMap();
5463 inline FixedArrayBase* GetInitialElements();
5465 // [raw_transitions]: Provides access to the transitions storage field.
5466 // Don't call set_raw_transitions() directly to overwrite transitions, use
5467 // the TransitionArray::ReplaceTransitions() wrapper instead!
5468 DECL_ACCESSORS(raw_transitions, Object)
5469 // [prototype_info]: Per-prototype metadata. Aliased with transitions
5470 // (which prototype maps don't have).
5471 DECL_ACCESSORS(prototype_info, Object)
5472 // PrototypeInfo is created lazily using this helper (which installs it on
5473 // the given prototype's map).
5474 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5475 Handle<JSObject> prototype, Isolate* isolate);
5476 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5477 Handle<Map> prototype_map, Isolate* isolate);
5479 // [prototype chain validity cell]: Associated with a prototype object,
5480 // stored in that object's map's PrototypeInfo, indicates that prototype
5481 // chains through this object are currently valid. The cell will be
5482 // invalidated and replaced when the prototype chain changes.
5483 static Handle<Cell> GetOrCreatePrototypeChainValidityCell(Handle<Map> map,
5485 static const int kPrototypeChainValid = 0;
5486 static const int kPrototypeChainInvalid = 1;
5489 Map* FindFieldOwner(int descriptor);
5491 inline int GetInObjectPropertyOffset(int index);
5493 int NumberOfFields();
5495 // TODO(ishell): candidate with JSObject::MigrateToMap().
5496 bool InstancesNeedRewriting(Map* target, int target_number_of_fields,
5497 int target_inobject, int target_unused,
5498 int* old_number_of_fields);
5499 // TODO(ishell): moveit!
5500 static Handle<Map> GeneralizeAllFieldRepresentations(Handle<Map> map);
5501 MUST_USE_RESULT static Handle<HeapType> GeneralizeFieldType(
5502 Handle<HeapType> type1,
5503 Handle<HeapType> type2,
5505 static void GeneralizeFieldType(Handle<Map> map, int modify_index,
5506 Representation new_representation,
5507 Handle<HeapType> new_field_type);
5508 static Handle<Map> ReconfigureProperty(Handle<Map> map, int modify_index,
5509 PropertyKind new_kind,
5510 PropertyAttributes new_attributes,
5511 Representation new_representation,
5512 Handle<HeapType> new_field_type,
5513 StoreMode store_mode);
5514 static Handle<Map> CopyGeneralizeAllRepresentations(
5515 Handle<Map> map, int modify_index, StoreMode store_mode,
5516 PropertyKind kind, PropertyAttributes attributes, const char* reason);
5518 static Handle<Map> PrepareForDataProperty(Handle<Map> old_map,
5519 int descriptor_number,
5520 Handle<Object> value);
5522 static Handle<Map> Normalize(Handle<Map> map, PropertyNormalizationMode mode,
5523 const char* reason);
5525 // Returns the constructor name (the name (possibly, inferred name) of the
5526 // function that was used to instantiate the object).
5527 String* constructor_name();
5529 // Tells whether the map is used for JSObjects in dictionary mode (ie
5530 // normalized objects, ie objects for which HasFastProperties returns false).
5531 // A map can never be used for both dictionary mode and fast mode JSObjects.
5532 // False by default and for HeapObjects that are not JSObjects.
5533 inline void set_dictionary_map(bool value);
5534 inline bool is_dictionary_map();
5536 // Tells whether the instance needs security checks when accessing its
5538 inline void set_is_access_check_needed(bool access_check_needed);
5539 inline bool is_access_check_needed();
5541 // Returns true if map has a non-empty stub code cache.
5542 inline bool has_code_cache();
5544 // [prototype]: implicit prototype object.
5545 DECL_ACCESSORS(prototype, Object)
5546 // TODO(jkummerow): make set_prototype private.
5547 static void SetPrototype(
5548 Handle<Map> map, Handle<Object> prototype,
5549 PrototypeOptimizationMode proto_mode = FAST_PROTOTYPE);
5551 // [constructor]: points back to the function responsible for this map.
5552 // The field overlaps with the back pointer. All maps in a transition tree
5553 // have the same constructor, so maps with back pointers can walk the
5554 // back pointer chain until they find the map holding their constructor.
5555 DECL_ACCESSORS(constructor_or_backpointer, Object)
5556 inline Object* GetConstructor() const;
5557 inline void SetConstructor(Object* constructor,
5558 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5559 // [back pointer]: points back to the parent map from which a transition
5560 // leads to this map. The field overlaps with the constructor (see above).
5561 inline Object* GetBackPointer();
5562 inline void SetBackPointer(Object* value,
5563 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5565 // [instance descriptors]: describes the object.
5566 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
5568 // [layout descriptor]: describes the object layout.
5569 DECL_ACCESSORS(layout_descriptor, LayoutDescriptor)
5570 // |layout descriptor| accessor which can be used from GC.
5571 inline LayoutDescriptor* layout_descriptor_gc_safe();
5572 inline bool HasFastPointerLayout() const;
5574 // |layout descriptor| accessor that is safe to call even when
5575 // FLAG_unbox_double_fields is disabled (in this case Map does not contain
5576 // |layout_descriptor| field at all).
5577 inline LayoutDescriptor* GetLayoutDescriptor();
5579 inline void UpdateDescriptors(DescriptorArray* descriptors,
5580 LayoutDescriptor* layout_descriptor);
5581 inline void InitializeDescriptors(DescriptorArray* descriptors,
5582 LayoutDescriptor* layout_descriptor);
5584 // [stub cache]: contains stubs compiled for this map.
5585 DECL_ACCESSORS(code_cache, Object)
5587 // [dependent code]: list of optimized codes that weakly embed this map.
5588 DECL_ACCESSORS(dependent_code, DependentCode)
5590 // [weak cell cache]: cache that stores a weak cell pointing to this map.
5591 DECL_ACCESSORS(weak_cell_cache, Object)
5593 inline PropertyDetails GetLastDescriptorDetails();
5596 int number_of_own_descriptors = NumberOfOwnDescriptors();
5597 DCHECK(number_of_own_descriptors > 0);
5598 return number_of_own_descriptors - 1;
5601 int NumberOfOwnDescriptors() {
5602 return NumberOfOwnDescriptorsBits::decode(bit_field3());
5605 void SetNumberOfOwnDescriptors(int number) {
5606 DCHECK(number <= instance_descriptors()->number_of_descriptors());
5607 set_bit_field3(NumberOfOwnDescriptorsBits::update(bit_field3(), number));
5610 inline Cell* RetrieveDescriptorsPointer();
5613 return EnumLengthBits::decode(bit_field3());
5616 void SetEnumLength(int length) {
5617 if (length != kInvalidEnumCacheSentinel) {
5618 DCHECK(length >= 0);
5619 DCHECK(length == 0 || instance_descriptors()->HasEnumCache());
5620 DCHECK(length <= NumberOfOwnDescriptors());
5622 set_bit_field3(EnumLengthBits::update(bit_field3(), length));
5625 inline bool owns_descriptors();
5626 inline void set_owns_descriptors(bool owns_descriptors);
5627 inline bool has_instance_call_handler();
5628 inline void set_has_instance_call_handler();
5629 inline void mark_unstable();
5630 inline bool is_stable();
5631 inline void set_migration_target(bool value);
5632 inline bool is_migration_target();
5633 inline void set_counter(int value);
5634 inline int counter();
5635 inline void deprecate();
5636 inline bool is_deprecated();
5637 inline bool CanBeDeprecated();
5638 // Returns a non-deprecated version of the input. If the input was not
5639 // deprecated, it is directly returned. Otherwise, the non-deprecated version
5640 // is found by re-transitioning from the root of the transition tree using the
5641 // descriptor array of the map. Returns MaybeHandle<Map>() if no updated map
5643 static MaybeHandle<Map> TryUpdate(Handle<Map> map) WARN_UNUSED_RESULT;
5645 // Returns a non-deprecated version of the input. This method may deprecate
5646 // existing maps along the way if encodings conflict. Not for use while
5647 // gathering type feedback. Use TryUpdate in those cases instead.
5648 static Handle<Map> Update(Handle<Map> map);
5650 static Handle<Map> CopyDropDescriptors(Handle<Map> map);
5651 static Handle<Map> CopyInsertDescriptor(Handle<Map> map,
5652 Descriptor* descriptor,
5653 TransitionFlag flag);
5655 MUST_USE_RESULT static MaybeHandle<Map> CopyWithField(
5658 Handle<HeapType> type,
5659 PropertyAttributes attributes,
5660 Representation representation,
5661 TransitionFlag flag);
5663 MUST_USE_RESULT static MaybeHandle<Map> CopyWithConstant(
5666 Handle<Object> constant,
5667 PropertyAttributes attributes,
5668 TransitionFlag flag);
5670 // Returns a new map with all transitions dropped from the given map and
5671 // the ElementsKind set.
5672 static Handle<Map> TransitionElementsTo(Handle<Map> map,
5673 ElementsKind to_kind);
5675 static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
5677 static Handle<Map> CopyAsElementsKind(Handle<Map> map,
5679 TransitionFlag flag);
5681 static Handle<Map> CopyForObserved(Handle<Map> map);
5683 static Handle<Map> CopyForPreventExtensions(Handle<Map> map,
5684 PropertyAttributes attrs_to_add,
5685 Handle<Symbol> transition_marker,
5686 const char* reason);
5688 static Handle<Map> FixProxy(Handle<Map> map, InstanceType type, int size);
5691 // Maximal number of fast properties. Used to restrict the number of map
5692 // transitions to avoid an explosion in the number of maps for objects used as
5694 inline bool TooManyFastProperties(StoreFromKeyed store_mode);
5695 static Handle<Map> TransitionToDataProperty(Handle<Map> map,
5697 Handle<Object> value,
5698 PropertyAttributes attributes,
5699 StoreFromKeyed store_mode);
5700 static Handle<Map> TransitionToAccessorProperty(
5701 Handle<Map> map, Handle<Name> name, AccessorComponent component,
5702 Handle<Object> accessor, PropertyAttributes attributes);
5703 static Handle<Map> ReconfigureExistingProperty(Handle<Map> map,
5706 PropertyAttributes attributes);
5708 inline void AppendDescriptor(Descriptor* desc);
5710 // Returns a copy of the map, prepared for inserting into the transition
5711 // tree (if the |map| owns descriptors then the new one will share
5712 // descriptors with |map|).
5713 static Handle<Map> CopyForTransition(Handle<Map> map, const char* reason);
5715 // Returns a copy of the map, with all transitions dropped from the
5716 // instance descriptors.
5717 static Handle<Map> Copy(Handle<Map> map, const char* reason);
5718 static Handle<Map> Create(Isolate* isolate, int inobject_properties);
5720 // Returns the next free property index (only valid for FAST MODE).
5721 int NextFreePropertyIndex();
5723 // Returns the number of properties described in instance_descriptors
5724 // filtering out properties with the specified attributes.
5725 int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
5726 PropertyAttributes filter = NONE);
5730 // Code cache operations.
5732 // Clears the code cache.
5733 inline void ClearCodeCache(Heap* heap);
5735 // Update code cache.
5736 static void UpdateCodeCache(Handle<Map> map,
5740 // Extend the descriptor array of the map with the list of descriptors.
5741 // In case of duplicates, the latest descriptor is used.
5742 static void AppendCallbackDescriptors(Handle<Map> map,
5743 Handle<Object> descriptors);
5745 static inline int SlackForArraySize(int old_size, int size_limit);
5747 static void EnsureDescriptorSlack(Handle<Map> map, int slack);
5749 // Returns the found code or undefined if absent.
5750 Object* FindInCodeCache(Name* name, Code::Flags flags);
5752 // Returns the non-negative index of the code object if it is in the
5753 // cache and -1 otherwise.
5754 int IndexInCodeCache(Object* name, Code* code);
5756 // Removes a code object from the code cache at the given index.
5757 void RemoveFromCodeCache(Name* name, Code* code, int index);
5759 // Computes a hash value for this map, to be used in HashTables and such.
5762 // Returns the map that this map transitions to if its elements_kind
5763 // is changed to |elements_kind|, or NULL if no such map is cached yet.
5764 // |safe_to_add_transitions| is set to false if adding transitions is not
5766 Map* LookupElementsTransitionMap(ElementsKind elements_kind);
5768 // Returns the transitioned map for this map with the most generic
5769 // elements_kind that's found in |candidates|, or null handle if no match is
5771 static Handle<Map> FindTransitionedMap(Handle<Map> map,
5772 MapHandleList* candidates);
5774 bool CanTransition() {
5775 // Only JSObject and subtypes have map transitions and back pointers.
5776 STATIC_ASSERT(LAST_TYPE == LAST_JS_OBJECT_TYPE);
5777 return instance_type() >= FIRST_JS_OBJECT_TYPE;
5780 bool IsPrimitiveMap() {
5781 STATIC_ASSERT(FIRST_PRIMITIVE_TYPE == FIRST_TYPE);
5782 return instance_type() <= LAST_PRIMITIVE_TYPE;
5784 bool IsJSObjectMap() {
5785 STATIC_ASSERT(LAST_JS_OBJECT_TYPE == LAST_TYPE);
5786 return instance_type() >= FIRST_JS_OBJECT_TYPE;
5788 bool IsJSArrayMap() { return instance_type() == JS_ARRAY_TYPE; }
5789 bool IsStringMap() { return instance_type() < FIRST_NONSTRING_TYPE; }
5790 bool IsJSProxyMap() {
5791 InstanceType type = instance_type();
5792 return FIRST_JS_PROXY_TYPE <= type && type <= LAST_JS_PROXY_TYPE;
5794 bool IsJSGlobalProxyMap() {
5795 return instance_type() == JS_GLOBAL_PROXY_TYPE;
5797 bool IsJSGlobalObjectMap() {
5798 return instance_type() == JS_GLOBAL_OBJECT_TYPE;
5800 bool IsGlobalObjectMap() {
5801 const InstanceType type = instance_type();
5802 return type == JS_GLOBAL_OBJECT_TYPE || type == JS_BUILTINS_OBJECT_TYPE;
5805 inline bool CanOmitMapChecks();
5807 static void AddDependentCode(Handle<Map> map,
5808 DependentCode::DependencyGroup group,
5811 bool IsMapInArrayPrototypeChain();
5813 static Handle<WeakCell> WeakCellForMap(Handle<Map> map);
5815 // Dispatched behavior.
5816 DECLARE_PRINTER(Map)
5817 DECLARE_VERIFIER(Map)
5820 void DictionaryMapVerify();
5821 void VerifyOmittedMapChecks();
5824 inline int visitor_id();
5825 inline void set_visitor_id(int visitor_id);
5827 static Handle<Map> TransitionToPrototype(Handle<Map> map,
5828 Handle<Object> prototype,
5829 PrototypeOptimizationMode mode);
5831 static const int kMaxPreAllocatedPropertyFields = 255;
5833 // Layout description.
5834 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
5835 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
5836 static const int kBitField3Offset = kInstanceAttributesOffset + kIntSize;
5837 static const int kPrototypeOffset = kBitField3Offset + kPointerSize;
5838 static const int kConstructorOrBackPointerOffset =
5839 kPrototypeOffset + kPointerSize;
5840 // When there is only one transition, it is stored directly in this field;
5841 // otherwise a transition array is used.
5842 // For prototype maps, this slot is used to store this map's PrototypeInfo
5844 static const int kTransitionsOrPrototypeInfoOffset =
5845 kConstructorOrBackPointerOffset + kPointerSize;
5846 static const int kDescriptorsOffset =
5847 kTransitionsOrPrototypeInfoOffset + kPointerSize;
5848 #if V8_DOUBLE_FIELDS_UNBOXING
5849 static const int kLayoutDecriptorOffset = kDescriptorsOffset + kPointerSize;
5850 static const int kCodeCacheOffset = kLayoutDecriptorOffset + kPointerSize;
5852 static const int kLayoutDecriptorOffset = 1; // Must not be ever accessed.
5853 static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
5855 static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
5856 static const int kWeakCellCacheOffset = kDependentCodeOffset + kPointerSize;
5857 static const int kSize = kWeakCellCacheOffset + kPointerSize;
5859 // Layout of pointer fields. Heap iteration code relies on them
5860 // being continuously allocated.
5861 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
5862 static const int kPointerFieldsEndOffset = kSize;
5864 // Byte offsets within kInstanceSizesOffset.
5865 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
5866 static const int kInObjectPropertiesOrConstructorFunctionIndexByte = 1;
5867 static const int kInObjectPropertiesOrConstructorFunctionIndexOffset =
5868 kInstanceSizesOffset + kInObjectPropertiesOrConstructorFunctionIndexByte;
5869 // Note there is one byte available for use here.
5870 static const int kUnusedByte = 2;
5871 static const int kUnusedOffset = kInstanceSizesOffset + kUnusedByte;
5872 static const int kVisitorIdByte = 3;
5873 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
5875 // Byte offsets within kInstanceAttributesOffset attributes.
5876 #if V8_TARGET_LITTLE_ENDIAN
5877 // Order instance type and bit field together such that they can be loaded
5878 // together as a 16-bit word with instance type in the lower 8 bits regardless
5879 // of endianess. Also provide endian-independent offset to that 16-bit word.
5880 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
5881 static const int kBitFieldOffset = kInstanceAttributesOffset + 1;
5883 static const int kBitFieldOffset = kInstanceAttributesOffset + 0;
5884 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 1;
5886 static const int kInstanceTypeAndBitFieldOffset =
5887 kInstanceAttributesOffset + 0;
5888 static const int kBitField2Offset = kInstanceAttributesOffset + 2;
5889 static const int kUnusedPropertyFieldsByte = 3;
5890 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 3;
5892 STATIC_ASSERT(kInstanceTypeAndBitFieldOffset ==
5893 Internals::kMapInstanceTypeAndBitFieldOffset);
5895 // Bit positions for bit field.
5896 static const int kHasNonInstancePrototype = 0;
5897 static const int kIsHiddenPrototype = 1;
5898 static const int kHasNamedInterceptor = 2;
5899 static const int kHasIndexedInterceptor = 3;
5900 static const int kIsUndetectable = 4;
5901 static const int kIsObserved = 5;
5902 static const int kIsAccessCheckNeeded = 6;
5903 class FunctionWithPrototype: public BitField<bool, 7, 1> {};
5905 // Bit positions for bit field 2
5906 static const int kIsExtensible = 0;
5907 static const int kStringWrapperSafeForDefaultValueOf = 1;
5908 class IsPrototypeMapBits : public BitField<bool, 2, 1> {};
5909 class ElementsKindBits: public BitField<ElementsKind, 3, 5> {};
5911 // Derived values from bit field 2
5912 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
5913 (FAST_ELEMENTS + 1) << Map::ElementsKindBits::kShift) - 1;
5914 static const int8_t kMaximumBitField2FastSmiElementValue =
5915 static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
5916 Map::ElementsKindBits::kShift) - 1;
5917 static const int8_t kMaximumBitField2FastHoleyElementValue =
5918 static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
5919 Map::ElementsKindBits::kShift) - 1;
5920 static const int8_t kMaximumBitField2FastHoleySmiElementValue =
5921 static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
5922 Map::ElementsKindBits::kShift) - 1;
5924 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
5925 kPointerFieldsEndOffset,
5926 kSize> BodyDescriptor;
5928 // Compares this map to another to see if they describe equivalent objects.
5929 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
5930 // it had exactly zero inobject properties.
5931 // The "shared" flags of both this map and |other| are ignored.
5932 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
5934 // Returns true if given field is unboxed double.
5935 inline bool IsUnboxedDoubleField(FieldIndex index);
5938 static void TraceTransition(const char* what, Map* from, Map* to, Name* name);
5939 static void TraceAllTransitions(Map* map);
5942 static inline Handle<Map> CopyInstallDescriptorsForTesting(
5943 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5944 Handle<LayoutDescriptor> layout_descriptor);
5947 static void ConnectTransition(Handle<Map> parent, Handle<Map> child,
5948 Handle<Name> name, SimpleTransitionFlag flag);
5950 bool EquivalentToForTransition(Map* other);
5951 static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
5952 static Handle<Map> ShareDescriptor(Handle<Map> map,
5953 Handle<DescriptorArray> descriptors,
5954 Descriptor* descriptor);
5955 static Handle<Map> CopyInstallDescriptors(
5956 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5957 Handle<LayoutDescriptor> layout_descriptor);
5958 static Handle<Map> CopyAddDescriptor(Handle<Map> map,
5959 Descriptor* descriptor,
5960 TransitionFlag flag);
5961 static Handle<Map> CopyReplaceDescriptors(
5962 Handle<Map> map, Handle<DescriptorArray> descriptors,
5963 Handle<LayoutDescriptor> layout_descriptor, TransitionFlag flag,
5964 MaybeHandle<Name> maybe_name, const char* reason,
5965 SimpleTransitionFlag simple_flag);
5967 static Handle<Map> CopyReplaceDescriptor(Handle<Map> map,
5968 Handle<DescriptorArray> descriptors,
5969 Descriptor* descriptor,
5971 TransitionFlag flag);
5972 static MUST_USE_RESULT MaybeHandle<Map> TryReconfigureExistingProperty(
5973 Handle<Map> map, int descriptor, PropertyKind kind,
5974 PropertyAttributes attributes, const char** reason);
5976 static Handle<Map> CopyNormalized(Handle<Map> map,
5977 PropertyNormalizationMode mode);
5979 // Fires when the layout of an object with a leaf map changes.
5980 // This includes adding transitions to the leaf map or changing
5981 // the descriptor array.
5982 inline void NotifyLeafMapLayoutChange();
5984 void DeprecateTransitionTree();
5985 bool DeprecateTarget(PropertyKind kind, Name* key,
5986 PropertyAttributes attributes,
5987 DescriptorArray* new_descriptors,
5988 LayoutDescriptor* new_layout_descriptor);
5990 Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
5992 // Update field type of the given descriptor to new representation and new
5993 // type. The type must be prepared for storing in descriptor array:
5994 // it must be either a simple type or a map wrapped in a weak cell.
5995 void UpdateFieldType(int descriptor_number, Handle<Name> name,
5996 Representation new_representation,
5997 Handle<Object> new_wrapped_type);
5999 void PrintReconfiguration(FILE* file, int modify_index, PropertyKind kind,
6000 PropertyAttributes attributes);
6001 void PrintGeneralization(FILE* file,
6006 bool constant_to_field,
6007 Representation old_representation,
6008 Representation new_representation,
6009 HeapType* old_field_type,
6010 HeapType* new_field_type);
6012 static const int kFastPropertiesSoftLimit = 12;
6013 static const int kMaxFastProperties = 128;
6015 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
6019 // An abstract superclass, a marker class really, for simple structure classes.
6020 // It doesn't carry much functionality but allows struct classes to be
6021 // identified in the type system.
6022 class Struct: public HeapObject {
6024 inline void InitializeBody(int object_size);
6025 DECLARE_CAST(Struct)
6029 // A simple one-element struct, useful where smis need to be boxed.
6030 class Box : public Struct {
6032 // [value]: the boxed contents.
6033 DECL_ACCESSORS(value, Object)
6037 // Dispatched behavior.
6038 DECLARE_PRINTER(Box)
6039 DECLARE_VERIFIER(Box)
6041 static const int kValueOffset = HeapObject::kHeaderSize;
6042 static const int kSize = kValueOffset + kPointerSize;
6045 DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
6049 // Container for metadata stored on each prototype map.
6050 class PrototypeInfo : public Struct {
6052 static const int UNREGISTERED = -1;
6054 // [prototype_users]: WeakFixedArray containing maps using this prototype,
6055 // or Smi(0) if uninitialized.
6056 DECL_ACCESSORS(prototype_users, Object)
6057 // [registry_slot]: Slot in prototype's user registry where this user
6058 // is stored. Returns UNREGISTERED if this prototype has not been registered.
6059 inline int registry_slot() const;
6060 inline void set_registry_slot(int slot);
6061 // [validity_cell]: Cell containing the validity bit for prototype chains
6062 // going through this object, or Smi(0) if uninitialized.
6063 DECL_ACCESSORS(validity_cell, Object)
6064 // [constructor_name]: User-friendly name of the original constructor.
6065 DECL_ACCESSORS(constructor_name, Object)
6067 DECLARE_CAST(PrototypeInfo)
6069 // Dispatched behavior.
6070 DECLARE_PRINTER(PrototypeInfo)
6071 DECLARE_VERIFIER(PrototypeInfo)
6073 static const int kPrototypeUsersOffset = HeapObject::kHeaderSize;
6074 static const int kRegistrySlotOffset = kPrototypeUsersOffset + kPointerSize;
6075 static const int kValidityCellOffset = kRegistrySlotOffset + kPointerSize;
6076 static const int kConstructorNameOffset = kValidityCellOffset + kPointerSize;
6077 static const int kSize = kConstructorNameOffset + kPointerSize;
6080 DISALLOW_IMPLICIT_CONSTRUCTORS(PrototypeInfo);
6084 // Script describes a script which has been added to the VM.
6085 class Script: public Struct {
6094 // Script compilation types.
6095 enum CompilationType {
6096 COMPILATION_TYPE_HOST = 0,
6097 COMPILATION_TYPE_EVAL = 1
6100 // Script compilation state.
6101 enum CompilationState {
6102 COMPILATION_STATE_INITIAL = 0,
6103 COMPILATION_STATE_COMPILED = 1
6106 // [source]: the script source.
6107 DECL_ACCESSORS(source, Object)
6109 // [name]: the script name.
6110 DECL_ACCESSORS(name, Object)
6112 // [id]: the script id.
6113 DECL_ACCESSORS(id, Smi)
6115 // [line_offset]: script line offset in resource from where it was extracted.
6116 DECL_ACCESSORS(line_offset, Smi)
6118 // [column_offset]: script column offset in resource from where it was
6120 DECL_ACCESSORS(column_offset, Smi)
6122 // [context_data]: context data for the context this script was compiled in.
6123 DECL_ACCESSORS(context_data, Object)
6125 // [wrapper]: the wrapper cache. This is either undefined or a WeakCell.
6126 DECL_ACCESSORS(wrapper, HeapObject)
6128 // [type]: the script type.
6129 DECL_ACCESSORS(type, Smi)
6131 // [line_ends]: FixedArray of line ends positions.
6132 DECL_ACCESSORS(line_ends, Object)
6134 // [eval_from_shared]: for eval scripts the shared funcion info for the
6135 // function from which eval was called.
6136 DECL_ACCESSORS(eval_from_shared, Object)
6138 // [eval_from_instructions_offset]: the instruction offset in the code for the
6139 // function from which eval was called where eval was called.
6140 DECL_ACCESSORS(eval_from_instructions_offset, Smi)
6142 // [shared_function_infos]: weak fixed array containing all shared
6143 // function infos created from this script.
6144 DECL_ACCESSORS(shared_function_infos, Object)
6146 // [flags]: Holds an exciting bitfield.
6147 DECL_ACCESSORS(flags, Smi)
6149 // [source_url]: sourceURL from magic comment
6150 DECL_ACCESSORS(source_url, Object)
6152 // [source_url]: sourceMappingURL magic comment
6153 DECL_ACCESSORS(source_mapping_url, Object)
6155 // [compilation_type]: how the the script was compiled. Encoded in the
6157 inline CompilationType compilation_type();
6158 inline void set_compilation_type(CompilationType type);
6160 // [compilation_state]: determines whether the script has already been
6161 // compiled. Encoded in the 'flags' field.
6162 inline CompilationState compilation_state();
6163 inline void set_compilation_state(CompilationState state);
6165 // [origin_options]: optional attributes set by the embedder via ScriptOrigin,
6166 // and used by the embedder to make decisions about the script. V8 just passes
6167 // this through. Encoded in the 'flags' field.
6168 inline v8::ScriptOriginOptions origin_options();
6169 inline void set_origin_options(ScriptOriginOptions origin_options);
6171 DECLARE_CAST(Script)
6173 // If script source is an external string, check that the underlying
6174 // resource is accessible. Otherwise, always return true.
6175 inline bool HasValidSource();
6177 // Convert code position into column number.
6178 static int GetColumnNumber(Handle<Script> script, int code_pos);
6180 // Convert code position into (zero-based) line number.
6181 // The non-handlified version does not allocate, but may be much slower.
6182 static int GetLineNumber(Handle<Script> script, int code_pos);
6183 int GetLineNumber(int code_pos);
6185 static Handle<Object> GetNameOrSourceURL(Handle<Script> script);
6187 // Init line_ends array with code positions of line ends inside script source.
6188 static void InitLineEnds(Handle<Script> script);
6190 // Get the JS object wrapping the given script; create it if none exists.
6191 static Handle<JSObject> GetWrapper(Handle<Script> script);
6193 // Look through the list of existing shared function infos to find one
6194 // that matches the function literal. Return empty handle if not found.
6195 MaybeHandle<SharedFunctionInfo> FindSharedFunctionInfo(FunctionLiteral* fun);
6197 // Dispatched behavior.
6198 DECLARE_PRINTER(Script)
6199 DECLARE_VERIFIER(Script)
6201 static const int kSourceOffset = HeapObject::kHeaderSize;
6202 static const int kNameOffset = kSourceOffset + kPointerSize;
6203 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
6204 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
6205 static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
6206 static const int kWrapperOffset = kContextOffset + kPointerSize;
6207 static const int kTypeOffset = kWrapperOffset + kPointerSize;
6208 static const int kLineEndsOffset = kTypeOffset + kPointerSize;
6209 static const int kIdOffset = kLineEndsOffset + kPointerSize;
6210 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
6211 static const int kEvalFrominstructionsOffsetOffset =
6212 kEvalFromSharedOffset + kPointerSize;
6213 static const int kSharedFunctionInfosOffset =
6214 kEvalFrominstructionsOffsetOffset + kPointerSize;
6215 static const int kFlagsOffset = kSharedFunctionInfosOffset + kPointerSize;
6216 static const int kSourceUrlOffset = kFlagsOffset + kPointerSize;
6217 static const int kSourceMappingUrlOffset = kSourceUrlOffset + kPointerSize;
6218 static const int kSize = kSourceMappingUrlOffset + kPointerSize;
6221 int GetLineNumberWithArray(int code_pos);
6223 // Bit positions in the flags field.
6224 static const int kCompilationTypeBit = 0;
6225 static const int kCompilationStateBit = 1;
6226 static const int kOriginOptionsShift = 2;
6227 static const int kOriginOptionsSize = 3;
6228 static const int kOriginOptionsMask = ((1 << kOriginOptionsSize) - 1)
6229 << kOriginOptionsShift;
6231 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6235 // List of builtin functions we want to identify to improve code
6238 // Each entry has a name of a global object property holding an object
6239 // optionally followed by ".prototype", a name of a builtin function
6240 // on the object (the one the id is set for), and a label.
6242 // Installation of ids for the selected builtin functions is handled
6243 // by the bootstrapper.
6244 #define FUNCTIONS_WITH_ID_LIST(V) \
6245 V(Array.prototype, indexOf, ArrayIndexOf) \
6246 V(Array.prototype, lastIndexOf, ArrayLastIndexOf) \
6247 V(Array.prototype, push, ArrayPush) \
6248 V(Array.prototype, pop, ArrayPop) \
6249 V(Array.prototype, shift, ArrayShift) \
6250 V(Function.prototype, apply, FunctionApply) \
6251 V(Function.prototype, call, FunctionCall) \
6252 V(String.prototype, charCodeAt, StringCharCodeAt) \
6253 V(String.prototype, charAt, StringCharAt) \
6254 V(String, fromCharCode, StringFromCharCode) \
6255 V(Math, random, MathRandom) \
6256 V(Math, floor, MathFloor) \
6257 V(Math, round, MathRound) \
6258 V(Math, ceil, MathCeil) \
6259 V(Math, abs, MathAbs) \
6260 V(Math, log, MathLog) \
6261 V(Math, exp, MathExp) \
6262 V(Math, sqrt, MathSqrt) \
6263 V(Math, pow, MathPow) \
6264 V(Math, max, MathMax) \
6265 V(Math, min, MathMin) \
6266 V(Math, cos, MathCos) \
6267 V(Math, sin, MathSin) \
6268 V(Math, tan, MathTan) \
6269 V(Math, acos, MathAcos) \
6270 V(Math, asin, MathAsin) \
6271 V(Math, atan, MathAtan) \
6272 V(Math, atan2, MathAtan2) \
6273 V(Math, imul, MathImul) \
6274 V(Math, clz32, MathClz32) \
6275 V(Math, fround, MathFround)
6277 #define ATOMIC_FUNCTIONS_WITH_ID_LIST(V) \
6278 V(Atomics, load, AtomicsLoad) \
6279 V(Atomics, store, AtomicsStore)
6281 enum BuiltinFunctionId {
6283 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
6285 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6286 ATOMIC_FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6287 #undef DECLARE_FUNCTION_ID
6288 // Fake id for a special case of Math.pow. Note, it continues the
6289 // list of math functions.
6294 // Result of searching in an optimized code map of a SharedFunctionInfo. Note
6295 // that both {code} and {literals} can be NULL to pass search result status.
6296 struct CodeAndLiterals {
6297 Code* code; // Cached optimized code.
6298 FixedArray* literals; // Cached literals array.
6302 // SharedFunctionInfo describes the JSFunction information that can be
6303 // shared by multiple instances of the function.
6304 class SharedFunctionInfo: public HeapObject {
6306 // [name]: Function name.
6307 DECL_ACCESSORS(name, Object)
6309 // [code]: Function code.
6310 DECL_ACCESSORS(code, Code)
6311 inline void ReplaceCode(Code* code);
6313 // [optimized_code_map]: Map from native context to optimized code
6314 // and a shared literals array or Smi(0) if none.
6315 DECL_ACCESSORS(optimized_code_map, Object)
6317 // Returns entry from optimized code map for specified context and OSR entry.
6318 // Note that {code == nullptr} indicates no matching entry has been found,
6319 // whereas {literals == nullptr} indicates the code is context-independent.
6320 CodeAndLiterals SearchOptimizedCodeMap(Context* native_context,
6321 BailoutId osr_ast_id);
6323 // Clear optimized code map.
6324 void ClearOptimizedCodeMap();
6326 // Removed a specific optimized code object from the optimized code map.
6327 void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
6329 // Trims the optimized code map after entries have been removed.
6330 void TrimOptimizedCodeMap(int shrink_by);
6332 // Add a new entry to the optimized code map for context-independent code.
6333 static void AddSharedCodeToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6336 // Add a new entry to the optimized code map for context-dependent code.
6337 static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6338 Handle<Context> native_context,
6340 Handle<FixedArray> literals,
6341 BailoutId osr_ast_id);
6343 // Set up the link between shared function info and the script. The shared
6344 // function info is added to the list on the script.
6345 static void SetScript(Handle<SharedFunctionInfo> shared,
6346 Handle<Object> script_object);
6348 // Layout description of the optimized code map.
6349 static const int kNextMapIndex = 0;
6350 static const int kSharedCodeIndex = 1;
6351 static const int kEntriesStart = 2;
6352 static const int kContextOffset = 0;
6353 static const int kCachedCodeOffset = 1;
6354 static const int kLiteralsOffset = 2;
6355 static const int kOsrAstIdOffset = 3;
6356 static const int kEntryLength = 4;
6357 static const int kInitialLength = kEntriesStart + kEntryLength;
6359 // [scope_info]: Scope info.
6360 DECL_ACCESSORS(scope_info, ScopeInfo)
6362 // [construct stub]: Code stub for constructing instances of this function.
6363 DECL_ACCESSORS(construct_stub, Code)
6365 // Returns if this function has been compiled to native code yet.
6366 inline bool is_compiled();
6368 // [length]: The function length - usually the number of declared parameters.
6369 // Use up to 2^30 parameters.
6370 inline int length() const;
6371 inline void set_length(int value);
6373 // [internal formal parameter count]: The declared number of parameters.
6374 // For subclass constructors, also includes new.target.
6375 // The size of function's frame is internal_formal_parameter_count + 1.
6376 inline int internal_formal_parameter_count() const;
6377 inline void set_internal_formal_parameter_count(int value);
6379 // Set the formal parameter count so the function code will be
6380 // called without using argument adaptor frames.
6381 inline void DontAdaptArguments();
6383 // [expected_nof_properties]: Expected number of properties for the function.
6384 inline int expected_nof_properties() const;
6385 inline void set_expected_nof_properties(int value);
6387 // [feedback_vector] - accumulates ast node feedback from full-codegen and
6388 // (increasingly) from crankshafted code where sufficient feedback isn't
6390 DECL_ACCESSORS(feedback_vector, TypeFeedbackVector)
6392 // Unconditionally clear the type feedback vector (including vector ICs).
6393 void ClearTypeFeedbackInfo();
6395 // Clear the type feedback vector with a more subtle policy at GC time.
6396 void ClearTypeFeedbackInfoAtGCTime();
6399 // [unique_id] - For --trace-maps purposes, an identifier that's persistent
6400 // even if the GC moves this SharedFunctionInfo.
6401 inline int unique_id() const;
6402 inline void set_unique_id(int value);
6405 // [instance class name]: class name for instances.
6406 DECL_ACCESSORS(instance_class_name, Object)
6408 // [function data]: This field holds some additional data for function.
6409 // Currently it has one of:
6410 // - a FunctionTemplateInfo to make benefit the API [IsApiFunction()].
6411 // - a Smi identifying a builtin function [HasBuiltinFunctionId()].
6412 // - a BytecodeArray for the interpreter [HasBytecodeArray()].
6413 // In the long run we don't want all functions to have this field but
6414 // we can fix that when we have a better model for storing hidden data
6416 DECL_ACCESSORS(function_data, Object)
6418 inline bool IsApiFunction();
6419 inline FunctionTemplateInfo* get_api_func_data();
6420 inline bool HasBuiltinFunctionId();
6421 inline BuiltinFunctionId builtin_function_id();
6422 inline bool HasBytecodeArray();
6423 inline BytecodeArray* bytecode_array();
6425 // [script info]: Script from which the function originates.
6426 DECL_ACCESSORS(script, Object)
6428 // [num_literals]: Number of literals used by this function.
6429 inline int num_literals() const;
6430 inline void set_num_literals(int value);
6432 // [start_position_and_type]: Field used to store both the source code
6433 // position, whether or not the function is a function expression,
6434 // and whether or not the function is a toplevel function. The two
6435 // least significants bit indicates whether the function is an
6436 // expression and the rest contains the source code position.
6437 inline int start_position_and_type() const;
6438 inline void set_start_position_and_type(int value);
6440 // The function is subject to debugging if a debug info is attached.
6441 inline bool HasDebugInfo();
6442 inline DebugInfo* GetDebugInfo();
6444 // A function has debug code if the compiled code has debug break slots.
6445 inline bool HasDebugCode();
6447 // [debug info]: Debug information.
6448 DECL_ACCESSORS(debug_info, Object)
6450 // [inferred name]: Name inferred from variable or property
6451 // assignment of this function. Used to facilitate debugging and
6452 // profiling of JavaScript code written in OO style, where almost
6453 // all functions are anonymous but are assigned to object
6455 DECL_ACCESSORS(inferred_name, String)
6457 // The function's name if it is non-empty, otherwise the inferred name.
6458 String* DebugName();
6460 // Position of the 'function' token in the script source.
6461 inline int function_token_position() const;
6462 inline void set_function_token_position(int function_token_position);
6464 // Position of this function in the script source.
6465 inline int start_position() const;
6466 inline void set_start_position(int start_position);
6468 // End position of this function in the script source.
6469 inline int end_position() const;
6470 inline void set_end_position(int end_position);
6472 // Is this function a function expression in the source code.
6473 DECL_BOOLEAN_ACCESSORS(is_expression)
6475 // Is this function a top-level function (scripts, evals).
6476 DECL_BOOLEAN_ACCESSORS(is_toplevel)
6478 // Bit field containing various information collected by the compiler to
6479 // drive optimization.
6480 inline int compiler_hints() const;
6481 inline void set_compiler_hints(int value);
6483 inline int ast_node_count() const;
6484 inline void set_ast_node_count(int count);
6486 inline int profiler_ticks() const;
6487 inline void set_profiler_ticks(int ticks);
6489 // Inline cache age is used to infer whether the function survived a context
6490 // disposal or not. In the former case we reset the opt_count.
6491 inline int ic_age();
6492 inline void set_ic_age(int age);
6494 // Indicates if this function can be lazy compiled.
6495 // This is used to determine if we can safely flush code from a function
6496 // when doing GC if we expect that the function will no longer be used.
6497 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
6499 // Indicates if this function can be lazy compiled without a context.
6500 // This is used to determine if we can force compilation without reaching
6501 // the function through program execution but through other means (e.g. heap
6502 // iteration by the debugger).
6503 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
6505 // Indicates whether optimizations have been disabled for this
6506 // shared function info. If a function is repeatedly optimized or if
6507 // we cannot optimize the function we disable optimization to avoid
6508 // spending time attempting to optimize it again.
6509 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
6511 // Indicates the language mode.
6512 inline LanguageMode language_mode();
6513 inline void set_language_mode(LanguageMode language_mode);
6515 // False if the function definitely does not allocate an arguments object.
6516 DECL_BOOLEAN_ACCESSORS(uses_arguments)
6518 // Indicates that this function uses a super property (or an eval that may
6519 // use a super property).
6520 // This is needed to set up the [[HomeObject]] on the function instance.
6521 DECL_BOOLEAN_ACCESSORS(needs_home_object)
6523 // True if the function has any duplicated parameter names.
6524 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
6526 // Indicates whether the function is a native function.
6527 // These needs special treatment in .call and .apply since
6528 // null passed as the receiver should not be translated to the
6530 DECL_BOOLEAN_ACCESSORS(native)
6532 // Indicate that this function should always be inlined in optimized code.
6533 DECL_BOOLEAN_ACCESSORS(force_inline)
6535 // Indicates that the function was created by the Function function.
6536 // Though it's anonymous, toString should treat it as if it had the name
6537 // "anonymous". We don't set the name itself so that the system does not
6538 // see a binding for it.
6539 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
6541 // Indicates whether the function is a bound function created using
6542 // the bind function.
6543 DECL_BOOLEAN_ACCESSORS(bound)
6545 // Indicates that the function is anonymous (the name field can be set
6546 // through the API, which does not change this flag).
6547 DECL_BOOLEAN_ACCESSORS(is_anonymous)
6549 // Is this a function or top-level/eval code.
6550 DECL_BOOLEAN_ACCESSORS(is_function)
6552 // Indicates that code for this function cannot be compiled with Crankshaft.
6553 DECL_BOOLEAN_ACCESSORS(dont_crankshaft)
6555 // Indicates that code for this function cannot be flushed.
6556 DECL_BOOLEAN_ACCESSORS(dont_flush)
6558 // Indicates that this function is a generator.
6559 DECL_BOOLEAN_ACCESSORS(is_generator)
6561 // Indicates that this function is an arrow function.
6562 DECL_BOOLEAN_ACCESSORS(is_arrow)
6564 // Indicates that this function is a concise method.
6565 DECL_BOOLEAN_ACCESSORS(is_concise_method)
6567 // Indicates that this function is an accessor (getter or setter).
6568 DECL_BOOLEAN_ACCESSORS(is_accessor_function)
6570 // Indicates that this function is a default constructor.
6571 DECL_BOOLEAN_ACCESSORS(is_default_constructor)
6573 // Indicates that this function is an asm function.
6574 DECL_BOOLEAN_ACCESSORS(asm_function)
6576 // Indicates that the the shared function info is deserialized from cache.
6577 DECL_BOOLEAN_ACCESSORS(deserialized)
6579 // Indicates that the the shared function info has never been compiled before.
6580 DECL_BOOLEAN_ACCESSORS(never_compiled)
6582 inline FunctionKind kind();
6583 inline void set_kind(FunctionKind kind);
6585 // Indicates whether or not the code in the shared function support
6587 inline bool has_deoptimization_support();
6589 // Enable deoptimization support through recompiled code.
6590 void EnableDeoptimizationSupport(Code* recompiled);
6592 // Disable (further) attempted optimization of all functions sharing this
6593 // shared function info.
6594 void DisableOptimization(BailoutReason reason);
6596 inline BailoutReason disable_optimization_reason();
6598 // Lookup the bailout ID and DCHECK that it exists in the non-optimized
6599 // code, returns whether it asserted (i.e., always true if assertions are
6601 bool VerifyBailoutId(BailoutId id);
6603 // [source code]: Source code for the function.
6604 bool HasSourceCode() const;
6605 Handle<Object> GetSourceCode();
6607 // Number of times the function was optimized.
6608 inline int opt_count();
6609 inline void set_opt_count(int opt_count);
6611 // Number of times the function was deoptimized.
6612 inline void set_deopt_count(int value);
6613 inline int deopt_count();
6614 inline void increment_deopt_count();
6616 // Number of time we tried to re-enable optimization after it
6617 // was disabled due to high number of deoptimizations.
6618 inline void set_opt_reenable_tries(int value);
6619 inline int opt_reenable_tries();
6621 inline void TryReenableOptimization();
6623 // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
6624 inline void set_counters(int value);
6625 inline int counters() const;
6627 // Stores opt_count and bailout_reason as bit-fields.
6628 inline void set_opt_count_and_bailout_reason(int value);
6629 inline int opt_count_and_bailout_reason() const;
6631 void set_disable_optimization_reason(BailoutReason reason) {
6632 set_opt_count_and_bailout_reason(
6633 DisabledOptimizationReasonBits::update(opt_count_and_bailout_reason(),
6637 // Tells whether this function should be subject to debugging.
6638 inline bool IsSubjectToDebugging();
6640 // Check whether or not this function is inlineable.
6641 bool IsInlineable();
6643 // Source size of this function.
6646 // Calculate the instance size.
6647 int CalculateInstanceSize();
6649 // Calculate the number of in-object properties.
6650 int CalculateInObjectProperties();
6652 inline bool has_simple_parameters();
6654 // Initialize a SharedFunctionInfo from a parsed function literal.
6655 static void InitFromFunctionLiteral(Handle<SharedFunctionInfo> shared_info,
6656 FunctionLiteral* lit);
6658 // Dispatched behavior.
6659 DECLARE_PRINTER(SharedFunctionInfo)
6660 DECLARE_VERIFIER(SharedFunctionInfo)
6662 void ResetForNewContext(int new_ic_age);
6664 DECLARE_CAST(SharedFunctionInfo)
6667 static const int kDontAdaptArgumentsSentinel = -1;
6669 // Layout description.
6671 static const int kNameOffset = HeapObject::kHeaderSize;
6672 static const int kCodeOffset = kNameOffset + kPointerSize;
6673 static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
6674 static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
6675 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
6676 static const int kInstanceClassNameOffset =
6677 kConstructStubOffset + kPointerSize;
6678 static const int kFunctionDataOffset =
6679 kInstanceClassNameOffset + kPointerSize;
6680 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
6681 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
6682 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
6683 static const int kFeedbackVectorOffset =
6684 kInferredNameOffset + kPointerSize;
6686 static const int kUniqueIdOffset = kFeedbackVectorOffset + kPointerSize;
6687 static const int kLastPointerFieldOffset = kUniqueIdOffset;
6689 // Just to not break the postmortrem support with conditional offsets
6690 static const int kUniqueIdOffset = kFeedbackVectorOffset;
6691 static const int kLastPointerFieldOffset = kFeedbackVectorOffset;
6694 #if V8_HOST_ARCH_32_BIT
6696 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6697 static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
6698 static const int kExpectedNofPropertiesOffset =
6699 kFormalParameterCountOffset + kPointerSize;
6700 static const int kNumLiteralsOffset =
6701 kExpectedNofPropertiesOffset + kPointerSize;
6702 static const int kStartPositionAndTypeOffset =
6703 kNumLiteralsOffset + kPointerSize;
6704 static const int kEndPositionOffset =
6705 kStartPositionAndTypeOffset + kPointerSize;
6706 static const int kFunctionTokenPositionOffset =
6707 kEndPositionOffset + kPointerSize;
6708 static const int kCompilerHintsOffset =
6709 kFunctionTokenPositionOffset + kPointerSize;
6710 static const int kOptCountAndBailoutReasonOffset =
6711 kCompilerHintsOffset + kPointerSize;
6712 static const int kCountersOffset =
6713 kOptCountAndBailoutReasonOffset + kPointerSize;
6714 static const int kAstNodeCountOffset =
6715 kCountersOffset + kPointerSize;
6716 static const int kProfilerTicksOffset =
6717 kAstNodeCountOffset + kPointerSize;
6720 static const int kSize = kProfilerTicksOffset + kPointerSize;
6722 // The only reason to use smi fields instead of int fields
6723 // is to allow iteration without maps decoding during
6724 // garbage collections.
6725 // To avoid wasting space on 64-bit architectures we use
6726 // the following trick: we group integer fields into pairs
6727 // The least significant integer in each pair is shifted left by 1.
6728 // By doing this we guarantee that LSB of each kPointerSize aligned
6729 // word is not set and thus this word cannot be treated as pointer
6730 // to HeapObject during old space traversal.
6731 #if V8_TARGET_LITTLE_ENDIAN
6732 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6733 static const int kFormalParameterCountOffset =
6734 kLengthOffset + kIntSize;
6736 static const int kExpectedNofPropertiesOffset =
6737 kFormalParameterCountOffset + kIntSize;
6738 static const int kNumLiteralsOffset =
6739 kExpectedNofPropertiesOffset + kIntSize;
6741 static const int kEndPositionOffset =
6742 kNumLiteralsOffset + kIntSize;
6743 static const int kStartPositionAndTypeOffset =
6744 kEndPositionOffset + kIntSize;
6746 static const int kFunctionTokenPositionOffset =
6747 kStartPositionAndTypeOffset + kIntSize;
6748 static const int kCompilerHintsOffset =
6749 kFunctionTokenPositionOffset + kIntSize;
6751 static const int kOptCountAndBailoutReasonOffset =
6752 kCompilerHintsOffset + kIntSize;
6753 static const int kCountersOffset =
6754 kOptCountAndBailoutReasonOffset + kIntSize;
6756 static const int kAstNodeCountOffset =
6757 kCountersOffset + kIntSize;
6758 static const int kProfilerTicksOffset =
6759 kAstNodeCountOffset + kIntSize;
6762 static const int kSize = kProfilerTicksOffset + kIntSize;
6764 #elif V8_TARGET_BIG_ENDIAN
6765 static const int kFormalParameterCountOffset =
6766 kLastPointerFieldOffset + kPointerSize;
6767 static const int kLengthOffset = kFormalParameterCountOffset + kIntSize;
6769 static const int kNumLiteralsOffset = kLengthOffset + kIntSize;
6770 static const int kExpectedNofPropertiesOffset = kNumLiteralsOffset + kIntSize;
6772 static const int kStartPositionAndTypeOffset =
6773 kExpectedNofPropertiesOffset + kIntSize;
6774 static const int kEndPositionOffset = kStartPositionAndTypeOffset + kIntSize;
6776 static const int kCompilerHintsOffset = kEndPositionOffset + kIntSize;
6777 static const int kFunctionTokenPositionOffset =
6778 kCompilerHintsOffset + kIntSize;
6780 static const int kCountersOffset = kFunctionTokenPositionOffset + kIntSize;
6781 static const int kOptCountAndBailoutReasonOffset = kCountersOffset + kIntSize;
6783 static const int kProfilerTicksOffset =
6784 kOptCountAndBailoutReasonOffset + kIntSize;
6785 static const int kAstNodeCountOffset = kProfilerTicksOffset + kIntSize;
6788 static const int kSize = kAstNodeCountOffset + kIntSize;
6791 #error Unknown byte ordering
6792 #endif // Big endian
6796 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
6798 typedef FixedBodyDescriptor<kNameOffset,
6799 kLastPointerFieldOffset + kPointerSize,
6800 kSize> BodyDescriptor;
6802 // Bit positions in start_position_and_type.
6803 // The source code start position is in the 30 most significant bits of
6804 // the start_position_and_type field.
6805 static const int kIsExpressionBit = 0;
6806 static const int kIsTopLevelBit = 1;
6807 static const int kStartPositionShift = 2;
6808 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
6810 // Bit positions in compiler_hints.
6811 enum CompilerHints {
6812 kAllowLazyCompilation,
6813 kAllowLazyCompilationWithoutContext,
6814 kOptimizationDisabled,
6815 kStrictModeFunction,
6816 kStrongModeFunction,
6819 kHasDuplicateParameters,
6824 kNameShouldPrintAsAnonymous,
6831 kIsAccessorFunction,
6832 kIsDefaultConstructor,
6833 kIsSubclassConstructor,
6839 kCompilerHintsCount // Pseudo entry
6841 // Add hints for other modes when they're added.
6842 STATIC_ASSERT(LANGUAGE_END == 3);
6844 class FunctionKindBits : public BitField<FunctionKind, kIsArrow, 8> {};
6846 class DeoptCountBits : public BitField<int, 0, 4> {};
6847 class OptReenableTriesBits : public BitField<int, 4, 18> {};
6848 class ICAgeBits : public BitField<int, 22, 8> {};
6850 class OptCountBits : public BitField<int, 0, 22> {};
6851 class DisabledOptimizationReasonBits : public BitField<int, 22, 8> {};
6854 #if V8_HOST_ARCH_32_BIT
6855 // On 32 bit platforms, compiler hints is a smi.
6856 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
6857 static const int kCompilerHintsSize = kPointerSize;
6859 // On 64 bit platforms, compiler hints is not a smi, see comment above.
6860 static const int kCompilerHintsSmiTagSize = 0;
6861 static const int kCompilerHintsSize = kIntSize;
6864 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
6865 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
6868 // Constants for optimizing codegen for strict mode function and
6870 // Allows to use byte-width instructions.
6871 static const int kStrictModeBitWithinByte =
6872 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6873 static const int kStrongModeBitWithinByte =
6874 (kStrongModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6876 static const int kNativeBitWithinByte =
6877 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
6879 #if defined(V8_TARGET_LITTLE_ENDIAN)
6880 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6881 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6882 static const int kStrongModeByteOffset =
6883 kCompilerHintsOffset +
6884 (kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6885 static const int kNativeByteOffset = kCompilerHintsOffset +
6886 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
6887 #elif defined(V8_TARGET_BIG_ENDIAN)
6888 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6889 (kCompilerHintsSize - 1) -
6890 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6891 static const int kStrongModeByteOffset =
6892 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6893 ((kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6894 static const int kNativeByteOffset = kCompilerHintsOffset +
6895 (kCompilerHintsSize - 1) -
6896 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
6898 #error Unknown byte ordering
6902 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
6906 // Printing support.
6907 struct SourceCodeOf {
6908 explicit SourceCodeOf(SharedFunctionInfo* v, int max = -1)
6909 : value(v), max_length(max) {}
6910 const SharedFunctionInfo* value;
6915 std::ostream& operator<<(std::ostream& os, const SourceCodeOf& v);
6918 class JSGeneratorObject: public JSObject {
6920 // [function]: The function corresponding to this generator object.
6921 DECL_ACCESSORS(function, JSFunction)
6923 // [context]: The context of the suspended computation.
6924 DECL_ACCESSORS(context, Context)
6926 // [receiver]: The receiver of the suspended computation.
6927 DECL_ACCESSORS(receiver, Object)
6929 // [continuation]: Offset into code of continuation.
6931 // A positive offset indicates a suspended generator. The special
6932 // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
6933 // cannot be resumed.
6934 inline int continuation() const;
6935 inline void set_continuation(int continuation);
6936 inline bool is_closed();
6937 inline bool is_executing();
6938 inline bool is_suspended();
6940 // [operand_stack]: Saved operand stack.
6941 DECL_ACCESSORS(operand_stack, FixedArray)
6943 DECLARE_CAST(JSGeneratorObject)
6945 // Dispatched behavior.
6946 DECLARE_PRINTER(JSGeneratorObject)
6947 DECLARE_VERIFIER(JSGeneratorObject)
6949 // Magic sentinel values for the continuation.
6950 static const int kGeneratorExecuting = -1;
6951 static const int kGeneratorClosed = 0;
6953 // Layout description.
6954 static const int kFunctionOffset = JSObject::kHeaderSize;
6955 static const int kContextOffset = kFunctionOffset + kPointerSize;
6956 static const int kReceiverOffset = kContextOffset + kPointerSize;
6957 static const int kContinuationOffset = kReceiverOffset + kPointerSize;
6958 static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
6959 static const int kSize = kOperandStackOffset + kPointerSize;
6961 // Resume mode, for use by runtime functions.
6962 enum ResumeMode { NEXT, THROW };
6964 // Yielding from a generator returns an object with the following inobject
6965 // properties. See Context::iterator_result_map() for the map.
6966 static const int kResultValuePropertyIndex = 0;
6967 static const int kResultDonePropertyIndex = 1;
6968 static const int kResultPropertyCount = 2;
6970 static const int kResultValuePropertyOffset = JSObject::kHeaderSize;
6971 static const int kResultDonePropertyOffset =
6972 kResultValuePropertyOffset + kPointerSize;
6973 static const int kResultSize = kResultDonePropertyOffset + kPointerSize;
6976 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
6980 // Representation for module instance objects.
6981 class JSModule: public JSObject {
6983 // [context]: the context holding the module's locals, or undefined if none.
6984 DECL_ACCESSORS(context, Object)
6986 // [scope_info]: Scope info.
6987 DECL_ACCESSORS(scope_info, ScopeInfo)
6989 DECLARE_CAST(JSModule)
6991 // Dispatched behavior.
6992 DECLARE_PRINTER(JSModule)
6993 DECLARE_VERIFIER(JSModule)
6995 // Layout description.
6996 static const int kContextOffset = JSObject::kHeaderSize;
6997 static const int kScopeInfoOffset = kContextOffset + kPointerSize;
6998 static const int kSize = kScopeInfoOffset + kPointerSize;
7001 DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
7005 // JSFunction describes JavaScript functions.
7006 class JSFunction: public JSObject {
7008 // [prototype_or_initial_map]:
7009 DECL_ACCESSORS(prototype_or_initial_map, Object)
7011 // [shared]: The information about the function that
7012 // can be shared by instances.
7013 DECL_ACCESSORS(shared, SharedFunctionInfo)
7015 // [context]: The context for this function.
7016 inline Context* context();
7017 inline void set_context(Object* context);
7018 inline JSObject* global_proxy();
7020 // [code]: The generated code object for this function. Executed
7021 // when the function is invoked, e.g. foo() or new foo(). See
7022 // [[Call]] and [[Construct]] description in ECMA-262, section
7024 inline Code* code();
7025 inline void set_code(Code* code);
7026 inline void set_code_no_write_barrier(Code* code);
7027 inline void ReplaceCode(Code* code);
7029 // Tells whether this function is builtin.
7030 inline bool IsBuiltin();
7032 // Tells whether this function inlines the given shared function info.
7033 bool Inlines(SharedFunctionInfo* candidate);
7035 // Tells whether this function should be subject to debugging.
7036 inline bool IsSubjectToDebugging();
7038 // Tells whether or not the function needs arguments adaption.
7039 inline bool NeedsArgumentsAdaption();
7041 // Tells whether or not this function has been optimized.
7042 inline bool IsOptimized();
7044 // Mark this function for lazy recompilation. The function will be
7045 // recompiled the next time it is executed.
7046 void MarkForOptimization();
7047 void AttemptConcurrentOptimization();
7049 // Tells whether or not the function is already marked for lazy
7051 inline bool IsMarkedForOptimization();
7052 inline bool IsMarkedForConcurrentOptimization();
7054 // Tells whether or not the function is on the concurrent recompilation queue.
7055 inline bool IsInOptimizationQueue();
7057 // Inobject slack tracking is the way to reclaim unused inobject space.
7059 // The instance size is initially determined by adding some slack to
7060 // expected_nof_properties (to allow for a few extra properties added
7061 // after the constructor). There is no guarantee that the extra space
7062 // will not be wasted.
7064 // Here is the algorithm to reclaim the unused inobject space:
7065 // - Detect the first constructor call for this JSFunction.
7066 // When it happens enter the "in progress" state: initialize construction
7067 // counter in the initial_map.
7068 // - While the tracking is in progress create objects filled with
7069 // one_pointer_filler_map instead of undefined_value. This way they can be
7070 // resized quickly and safely.
7071 // - Once enough objects have been created compute the 'slack'
7072 // (traverse the map transition tree starting from the
7073 // initial_map and find the lowest value of unused_property_fields).
7074 // - Traverse the transition tree again and decrease the instance size
7075 // of every map. Existing objects will resize automatically (they are
7076 // filled with one_pointer_filler_map). All further allocations will
7077 // use the adjusted instance size.
7078 // - SharedFunctionInfo's expected_nof_properties left unmodified since
7079 // allocations made using different closures could actually create different
7080 // kind of objects (see prototype inheritance pattern).
7082 // Important: inobject slack tracking is not attempted during the snapshot
7085 // True if the initial_map is set and the object constructions countdown
7086 // counter is not zero.
7087 static const int kGenerousAllocationCount =
7088 Map::kSlackTrackingCounterStart - Map::kSlackTrackingCounterEnd + 1;
7089 inline bool IsInobjectSlackTrackingInProgress();
7091 // Starts the tracking.
7092 // Initializes object constructions countdown counter in the initial map.
7093 void StartInobjectSlackTracking();
7095 // Completes the tracking.
7096 void CompleteInobjectSlackTracking();
7098 // [literals_or_bindings]: Fixed array holding either
7099 // the materialized literals or the bindings of a bound function.
7101 // If the function contains object, regexp or array literals, the
7102 // literals array prefix contains the object, regexp, and array
7103 // function to be used when creating these literals. This is
7104 // necessary so that we do not dynamically lookup the object, regexp
7105 // or array functions. Performing a dynamic lookup, we might end up
7106 // using the functions from a new context that we should not have
7109 // On bound functions, the array is a (copy-on-write) fixed-array containing
7110 // the function that was bound, bound this-value and any bound
7111 // arguments. Bound functions never contain literals.
7112 DECL_ACCESSORS(literals_or_bindings, FixedArray)
7114 inline FixedArray* literals();
7115 inline void set_literals(FixedArray* literals);
7117 inline FixedArray* function_bindings();
7118 inline void set_function_bindings(FixedArray* bindings);
7120 // The initial map for an object created by this constructor.
7121 inline Map* initial_map();
7122 static void SetInitialMap(Handle<JSFunction> function, Handle<Map> map,
7123 Handle<Object> prototype);
7124 inline bool has_initial_map();
7125 static void EnsureHasInitialMap(Handle<JSFunction> function);
7127 // Get and set the prototype property on a JSFunction. If the
7128 // function has an initial map the prototype is set on the initial
7129 // map. Otherwise, the prototype is put in the initial map field
7130 // until an initial map is needed.
7131 inline bool has_prototype();
7132 inline bool has_instance_prototype();
7133 inline Object* prototype();
7134 inline Object* instance_prototype();
7135 static void SetPrototype(Handle<JSFunction> function,
7136 Handle<Object> value);
7137 static void SetInstancePrototype(Handle<JSFunction> function,
7138 Handle<Object> value);
7140 // Creates a new closure for the fucntion with the same bindings,
7141 // bound values, and prototype. An equivalent of spec operations
7142 // ``CloneMethod`` and ``CloneBoundFunction``.
7143 static Handle<JSFunction> CloneClosure(Handle<JSFunction> function);
7145 // After prototype is removed, it will not be created when accessed, and
7146 // [[Construct]] from this function will not be allowed.
7147 bool RemovePrototype();
7148 inline bool should_have_prototype();
7150 // Accessor for this function's initial map's [[class]]
7151 // property. This is primarily used by ECMA native functions. This
7152 // method sets the class_name field of this function's initial map
7153 // to a given value. It creates an initial map if this function does
7154 // not have one. Note that this method does not copy the initial map
7155 // if it has one already, but simply replaces it with the new value.
7156 // Instances created afterwards will have a map whose [[class]] is
7157 // set to 'value', but there is no guarantees on instances created
7159 void SetInstanceClassName(String* name);
7161 // Returns if this function has been compiled to native code yet.
7162 inline bool is_compiled();
7164 // Returns `false` if formal parameters include rest parameters, optional
7165 // parameters, or destructuring parameters.
7166 // TODO(caitp): make this a flag set during parsing
7167 inline bool has_simple_parameters();
7169 // [next_function_link]: Links functions into various lists, e.g. the list
7170 // of optimized functions hanging off the native_context. The CodeFlusher
7171 // uses this link to chain together flushing candidates. Treated weakly
7172 // by the garbage collector.
7173 DECL_ACCESSORS(next_function_link, Object)
7175 // Prints the name of the function using PrintF.
7176 void PrintName(FILE* out = stdout);
7178 DECLARE_CAST(JSFunction)
7180 // Iterates the objects, including code objects indirectly referenced
7181 // through pointers to the first instruction in the code object.
7182 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
7184 // Dispatched behavior.
7185 DECLARE_PRINTER(JSFunction)
7186 DECLARE_VERIFIER(JSFunction)
7188 // Returns the number of allocated literals.
7189 inline int NumberOfLiterals();
7191 // Used for flags such as --hydrogen-filter.
7192 bool PassesFilter(const char* raw_filter);
7194 // The function's name if it is configured, otherwise shared function info
7196 static Handle<String> GetDebugName(Handle<JSFunction> function);
7198 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
7199 // kSize) is weak and has special handling during garbage collection.
7200 static const int kCodeEntryOffset = JSObject::kHeaderSize;
7201 static const int kPrototypeOrInitialMapOffset =
7202 kCodeEntryOffset + kPointerSize;
7203 static const int kSharedFunctionInfoOffset =
7204 kPrototypeOrInitialMapOffset + kPointerSize;
7205 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
7206 static const int kLiteralsOffset = kContextOffset + kPointerSize;
7207 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
7208 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
7209 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
7211 // Layout of the bound-function binding array.
7212 static const int kBoundFunctionIndex = 0;
7213 static const int kBoundThisIndex = 1;
7214 static const int kBoundArgumentsStartIndex = 2;
7217 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7221 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7222 // and the prototype is hidden. JSGlobalProxy always delegates
7223 // property accesses to its prototype if the prototype is not null.
7225 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7227 // Accessing a JSGlobalProxy requires security check.
7229 class JSGlobalProxy : public JSObject {
7231 // [native_context]: the owner native context of this global proxy object.
7232 // It is null value if this object is not used by any context.
7233 DECL_ACCESSORS(native_context, Object)
7235 // [hash]: The hash code property (undefined if not initialized yet).
7236 DECL_ACCESSORS(hash, Object)
7238 DECLARE_CAST(JSGlobalProxy)
7240 inline bool IsDetachedFrom(GlobalObject* global) const;
7242 // Dispatched behavior.
7243 DECLARE_PRINTER(JSGlobalProxy)
7244 DECLARE_VERIFIER(JSGlobalProxy)
7246 // Layout description.
7247 static const int kNativeContextOffset = JSObject::kHeaderSize;
7248 static const int kHashOffset = kNativeContextOffset + kPointerSize;
7249 static const int kSize = kHashOffset + kPointerSize;
7252 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7256 // Common super class for JavaScript global objects and the special
7257 // builtins global objects.
7258 class GlobalObject: public JSObject {
7260 // [builtins]: the object holding the runtime routines written in JS.
7261 DECL_ACCESSORS(builtins, JSBuiltinsObject)
7263 // [native context]: the natives corresponding to this global object.
7264 DECL_ACCESSORS(native_context, Context)
7266 // [global proxy]: the global proxy object of the context
7267 DECL_ACCESSORS(global_proxy, JSObject)
7269 DECLARE_CAST(GlobalObject)
7271 static void InvalidatePropertyCell(Handle<GlobalObject> object,
7273 // Ensure that the global object has a cell for the given property name.
7274 static Handle<PropertyCell> EnsurePropertyCell(Handle<GlobalObject> global,
7277 // Layout description.
7278 static const int kBuiltinsOffset = JSObject::kHeaderSize;
7279 static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7280 static const int kGlobalProxyOffset = kNativeContextOffset + kPointerSize;
7281 static const int kHeaderSize = kGlobalProxyOffset + kPointerSize;
7284 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7288 // JavaScript global object.
7289 class JSGlobalObject: public GlobalObject {
7291 DECLARE_CAST(JSGlobalObject)
7293 inline bool IsDetached();
7295 // Dispatched behavior.
7296 DECLARE_PRINTER(JSGlobalObject)
7297 DECLARE_VERIFIER(JSGlobalObject)
7299 // Layout description.
7300 static const int kSize = GlobalObject::kHeaderSize;
7303 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7307 // Builtins global object which holds the runtime routines written in
7309 class JSBuiltinsObject: public GlobalObject {
7311 // Accessors for the runtime routines written in JavaScript.
7312 inline Object* javascript_builtin(Builtins::JavaScript id);
7313 inline void set_javascript_builtin(Builtins::JavaScript id, Object* value);
7315 DECLARE_CAST(JSBuiltinsObject)
7317 // Dispatched behavior.
7318 DECLARE_PRINTER(JSBuiltinsObject)
7319 DECLARE_VERIFIER(JSBuiltinsObject)
7321 // Layout description. The size of the builtins object includes
7322 // room for two pointers per runtime routine written in javascript
7323 // (function and code object).
7324 static const int kJSBuiltinsCount = Builtins::id_count;
7325 static const int kJSBuiltinsOffset = GlobalObject::kHeaderSize;
7326 static const int kSize =
7327 GlobalObject::kHeaderSize + (kJSBuiltinsCount * kPointerSize);
7329 static int OffsetOfFunctionWithId(Builtins::JavaScript id) {
7330 return kJSBuiltinsOffset + id * kPointerSize;
7334 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7338 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
7339 class JSValue: public JSObject {
7341 // [value]: the object being wrapped.
7342 DECL_ACCESSORS(value, Object)
7344 DECLARE_CAST(JSValue)
7346 // Dispatched behavior.
7347 DECLARE_PRINTER(JSValue)
7348 DECLARE_VERIFIER(JSValue)
7350 // Layout description.
7351 static const int kValueOffset = JSObject::kHeaderSize;
7352 static const int kSize = kValueOffset + kPointerSize;
7355 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
7361 // Representation for JS date objects.
7362 class JSDate: public JSObject {
7364 // If one component is NaN, all of them are, indicating a NaN time value.
7365 // [value]: the time value.
7366 DECL_ACCESSORS(value, Object)
7367 // [year]: caches year. Either undefined, smi, or NaN.
7368 DECL_ACCESSORS(year, Object)
7369 // [month]: caches month. Either undefined, smi, or NaN.
7370 DECL_ACCESSORS(month, Object)
7371 // [day]: caches day. Either undefined, smi, or NaN.
7372 DECL_ACCESSORS(day, Object)
7373 // [weekday]: caches day of week. Either undefined, smi, or NaN.
7374 DECL_ACCESSORS(weekday, Object)
7375 // [hour]: caches hours. Either undefined, smi, or NaN.
7376 DECL_ACCESSORS(hour, Object)
7377 // [min]: caches minutes. Either undefined, smi, or NaN.
7378 DECL_ACCESSORS(min, Object)
7379 // [sec]: caches seconds. Either undefined, smi, or NaN.
7380 DECL_ACCESSORS(sec, Object)
7381 // [cache stamp]: sample of the date cache stamp at the
7382 // moment when chached fields were cached.
7383 DECL_ACCESSORS(cache_stamp, Object)
7385 DECLARE_CAST(JSDate)
7387 // Returns the date field with the specified index.
7388 // See FieldIndex for the list of date fields.
7389 static Object* GetField(Object* date, Smi* index);
7391 void SetValue(Object* value, bool is_value_nan);
7394 // Dispatched behavior.
7395 DECLARE_PRINTER(JSDate)
7396 DECLARE_VERIFIER(JSDate)
7398 // The order is important. It must be kept in sync with date macros
7409 kFirstUncachedField,
7410 kMillisecond = kFirstUncachedField,
7414 kYearUTC = kFirstUTCField,
7427 // Layout description.
7428 static const int kValueOffset = JSObject::kHeaderSize;
7429 static const int kYearOffset = kValueOffset + kPointerSize;
7430 static const int kMonthOffset = kYearOffset + kPointerSize;
7431 static const int kDayOffset = kMonthOffset + kPointerSize;
7432 static const int kWeekdayOffset = kDayOffset + kPointerSize;
7433 static const int kHourOffset = kWeekdayOffset + kPointerSize;
7434 static const int kMinOffset = kHourOffset + kPointerSize;
7435 static const int kSecOffset = kMinOffset + kPointerSize;
7436 static const int kCacheStampOffset = kSecOffset + kPointerSize;
7437 static const int kSize = kCacheStampOffset + kPointerSize;
7440 inline Object* DoGetField(FieldIndex index);
7442 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
7444 // Computes and caches the cacheable fields of the date.
7445 inline void SetCachedFields(int64_t local_time_ms, DateCache* date_cache);
7448 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
7452 // Representation of message objects used for error reporting through
7453 // the API. The messages are formatted in JavaScript so this object is
7454 // a real JavaScript object. The information used for formatting the
7455 // error messages are not directly accessible from JavaScript to
7456 // prevent leaking information to user code called during error
7458 class JSMessageObject: public JSObject {
7460 // [type]: the type of error message.
7461 inline int type() const;
7462 inline void set_type(int value);
7464 // [arguments]: the arguments for formatting the error message.
7465 DECL_ACCESSORS(argument, Object)
7467 // [script]: the script from which the error message originated.
7468 DECL_ACCESSORS(script, Object)
7470 // [stack_frames]: an array of stack frames for this error object.
7471 DECL_ACCESSORS(stack_frames, Object)
7473 // [start_position]: the start position in the script for the error message.
7474 inline int start_position() const;
7475 inline void set_start_position(int value);
7477 // [end_position]: the end position in the script for the error message.
7478 inline int end_position() const;
7479 inline void set_end_position(int value);
7481 DECLARE_CAST(JSMessageObject)
7483 // Dispatched behavior.
7484 DECLARE_PRINTER(JSMessageObject)
7485 DECLARE_VERIFIER(JSMessageObject)
7487 // Layout description.
7488 static const int kTypeOffset = JSObject::kHeaderSize;
7489 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
7490 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
7491 static const int kStackFramesOffset = kScriptOffset + kPointerSize;
7492 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
7493 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
7494 static const int kSize = kEndPositionOffset + kPointerSize;
7496 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
7497 kStackFramesOffset + kPointerSize,
7498 kSize> BodyDescriptor;
7502 // Regular expressions
7503 // The regular expression holds a single reference to a FixedArray in
7504 // the kDataOffset field.
7505 // The FixedArray contains the following data:
7506 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
7507 // - reference to the original source string
7508 // - reference to the original flag string
7509 // If it is an atom regexp
7510 // - a reference to a literal string to search for
7511 // If it is an irregexp regexp:
7512 // - a reference to code for Latin1 inputs (bytecode or compiled), or a smi
7513 // used for tracking the last usage (used for code flushing).
7514 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
7515 // used for tracking the last usage (used for code flushing)..
7516 // - max number of registers used by irregexp implementations.
7517 // - number of capture registers (output values) of the regexp.
7518 class JSRegExp: public JSObject {
7521 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
7522 // ATOM: A simple string to match against using an indexOf operation.
7523 // IRREGEXP: Compiled with Irregexp.
7524 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
7525 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
7532 UNICODE_ESCAPES = 16
7537 explicit Flags(uint32_t value) : value_(value) { }
7538 bool is_global() { return (value_ & GLOBAL) != 0; }
7539 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
7540 bool is_multiline() { return (value_ & MULTILINE) != 0; }
7541 bool is_sticky() { return (value_ & STICKY) != 0; }
7542 bool is_unicode() { return (value_ & UNICODE_ESCAPES) != 0; }
7543 uint32_t value() { return value_; }
7548 DECL_ACCESSORS(data, Object)
7550 inline Type TypeTag();
7551 inline int CaptureCount();
7552 inline Flags GetFlags();
7553 inline String* Pattern();
7554 inline Object* DataAt(int index);
7555 // Set implementation data after the object has been prepared.
7556 inline void SetDataAt(int index, Object* value);
7558 static int code_index(bool is_latin1) {
7560 return kIrregexpLatin1CodeIndex;
7562 return kIrregexpUC16CodeIndex;
7566 static int saved_code_index(bool is_latin1) {
7568 return kIrregexpLatin1CodeSavedIndex;
7570 return kIrregexpUC16CodeSavedIndex;
7574 DECLARE_CAST(JSRegExp)
7576 // Dispatched behavior.
7577 DECLARE_VERIFIER(JSRegExp)
7579 static const int kDataOffset = JSObject::kHeaderSize;
7580 static const int kSize = kDataOffset + kPointerSize;
7582 // Indices in the data array.
7583 static const int kTagIndex = 0;
7584 static const int kSourceIndex = kTagIndex + 1;
7585 static const int kFlagsIndex = kSourceIndex + 1;
7586 static const int kDataIndex = kFlagsIndex + 1;
7587 // The data fields are used in different ways depending on the
7588 // value of the tag.
7589 // Atom regexps (literal strings).
7590 static const int kAtomPatternIndex = kDataIndex;
7592 static const int kAtomDataSize = kAtomPatternIndex + 1;
7594 // Irregexp compiled code or bytecode for Latin1. If compilation
7595 // fails, this fields hold an exception object that should be
7596 // thrown if the regexp is used again.
7597 static const int kIrregexpLatin1CodeIndex = kDataIndex;
7598 // Irregexp compiled code or bytecode for UC16. If compilation
7599 // fails, this fields hold an exception object that should be
7600 // thrown if the regexp is used again.
7601 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
7603 // Saved instance of Irregexp compiled code or bytecode for Latin1 that
7604 // is a potential candidate for flushing.
7605 static const int kIrregexpLatin1CodeSavedIndex = kDataIndex + 2;
7606 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
7607 // a potential candidate for flushing.
7608 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
7610 // Maximal number of registers used by either Latin1 or UC16.
7611 // Only used to check that there is enough stack space
7612 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
7613 // Number of captures in the compiled regexp.
7614 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
7616 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
7618 // Offsets directly into the data fixed array.
7619 static const int kDataTagOffset =
7620 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
7621 static const int kDataOneByteCodeOffset =
7622 FixedArray::kHeaderSize + kIrregexpLatin1CodeIndex * kPointerSize;
7623 static const int kDataUC16CodeOffset =
7624 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
7625 static const int kIrregexpCaptureCountOffset =
7626 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
7628 // In-object fields.
7629 static const int kSourceFieldIndex = 0;
7630 static const int kGlobalFieldIndex = 1;
7631 static const int kIgnoreCaseFieldIndex = 2;
7632 static const int kMultilineFieldIndex = 3;
7633 static const int kLastIndexFieldIndex = 4;
7634 static const int kInObjectFieldCount = 5;
7636 // The uninitialized value for a regexp code object.
7637 static const int kUninitializedValue = -1;
7639 // The compilation error value for the regexp code object. The real error
7640 // object is in the saved code field.
7641 static const int kCompilationErrorValue = -2;
7643 // When we store the sweep generation at which we moved the code from the
7644 // code index to the saved code index we mask it of to be in the [0:255]
7646 static const int kCodeAgeMask = 0xff;
7650 class CompilationCacheShape : public BaseShape<HashTableKey*> {
7652 static inline bool IsMatch(HashTableKey* key, Object* value) {
7653 return key->IsMatch(value);
7656 static inline uint32_t Hash(HashTableKey* key) {
7660 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7661 return key->HashForObject(object);
7664 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7666 static const int kPrefixSize = 0;
7667 static const int kEntrySize = 2;
7671 // This cache is used in two different variants. For regexp caching, it simply
7672 // maps identifying info of the regexp to the cached regexp object. Scripts and
7673 // eval code only gets cached after a second probe for the code object. To do
7674 // so, on first "put" only a hash identifying the source is entered into the
7675 // cache, mapping it to a lifetime count of the hash. On each call to Age all
7676 // such lifetimes get reduced, and removed once they reach zero. If a second put
7677 // is called while such a hash is live in the cache, the hash gets replaced by
7678 // an actual cache entry. Age also removes stale live entries from the cache.
7679 // Such entries are identified by SharedFunctionInfos pointing to either the
7680 // recompilation stub, or to "old" code. This avoids memory leaks due to
7681 // premature caching of scripts and eval strings that are never needed later.
7682 class CompilationCacheTable: public HashTable<CompilationCacheTable,
7683 CompilationCacheShape,
7686 // Find cached value for a string key, otherwise return null.
7687 Handle<Object> Lookup(
7688 Handle<String> src, Handle<Context> context, LanguageMode language_mode);
7689 Handle<Object> LookupEval(
7690 Handle<String> src, Handle<SharedFunctionInfo> shared,
7691 LanguageMode language_mode, int scope_position);
7692 Handle<Object> LookupRegExp(Handle<String> source, JSRegExp::Flags flags);
7693 static Handle<CompilationCacheTable> Put(
7694 Handle<CompilationCacheTable> cache, Handle<String> src,
7695 Handle<Context> context, LanguageMode language_mode,
7696 Handle<Object> value);
7697 static Handle<CompilationCacheTable> PutEval(
7698 Handle<CompilationCacheTable> cache, Handle<String> src,
7699 Handle<SharedFunctionInfo> context, Handle<SharedFunctionInfo> value,
7700 int scope_position);
7701 static Handle<CompilationCacheTable> PutRegExp(
7702 Handle<CompilationCacheTable> cache, Handle<String> src,
7703 JSRegExp::Flags flags, Handle<FixedArray> value);
7704 void Remove(Object* value);
7706 static const int kHashGenerations = 10;
7708 DECLARE_CAST(CompilationCacheTable)
7711 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
7715 class CodeCache: public Struct {
7717 DECL_ACCESSORS(default_cache, FixedArray)
7718 DECL_ACCESSORS(normal_type_cache, Object)
7720 // Add the code object to the cache.
7722 Handle<CodeCache> cache, Handle<Name> name, Handle<Code> code);
7724 // Lookup code object in the cache. Returns code object if found and undefined
7726 Object* Lookup(Name* name, Code::Flags flags);
7728 // Get the internal index of a code object in the cache. Returns -1 if the
7729 // code object is not in that cache. This index can be used to later call
7730 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
7732 int GetIndex(Object* name, Code* code);
7734 // Remove an object from the cache with the provided internal index.
7735 void RemoveByIndex(Object* name, Code* code, int index);
7737 DECLARE_CAST(CodeCache)
7739 // Dispatched behavior.
7740 DECLARE_PRINTER(CodeCache)
7741 DECLARE_VERIFIER(CodeCache)
7743 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
7744 static const int kNormalTypeCacheOffset =
7745 kDefaultCacheOffset + kPointerSize;
7746 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
7749 static void UpdateDefaultCache(
7750 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7751 static void UpdateNormalTypeCache(
7752 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7753 Object* LookupDefaultCache(Name* name, Code::Flags flags);
7754 Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
7756 // Code cache layout of the default cache. Elements are alternating name and
7757 // code objects for non normal load/store/call IC's.
7758 static const int kCodeCacheEntrySize = 2;
7759 static const int kCodeCacheEntryNameOffset = 0;
7760 static const int kCodeCacheEntryCodeOffset = 1;
7762 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
7766 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
7768 static inline bool IsMatch(HashTableKey* key, Object* value) {
7769 return key->IsMatch(value);
7772 static inline uint32_t Hash(HashTableKey* key) {
7776 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7777 return key->HashForObject(object);
7780 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7782 static const int kPrefixSize = 0;
7783 static const int kEntrySize = 2;
7787 class CodeCacheHashTable: public HashTable<CodeCacheHashTable,
7788 CodeCacheHashTableShape,
7791 Object* Lookup(Name* name, Code::Flags flags);
7792 static Handle<CodeCacheHashTable> Put(
7793 Handle<CodeCacheHashTable> table,
7797 int GetIndex(Name* name, Code::Flags flags);
7798 void RemoveByIndex(int index);
7800 DECLARE_CAST(CodeCacheHashTable)
7802 // Initial size of the fixed array backing the hash table.
7803 static const int kInitialSize = 64;
7806 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
7810 class PolymorphicCodeCache: public Struct {
7812 DECL_ACCESSORS(cache, Object)
7814 static void Update(Handle<PolymorphicCodeCache> cache,
7815 MapHandleList* maps,
7820 // Returns an undefined value if the entry is not found.
7821 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
7823 DECLARE_CAST(PolymorphicCodeCache)
7825 // Dispatched behavior.
7826 DECLARE_PRINTER(PolymorphicCodeCache)
7827 DECLARE_VERIFIER(PolymorphicCodeCache)
7829 static const int kCacheOffset = HeapObject::kHeaderSize;
7830 static const int kSize = kCacheOffset + kPointerSize;
7833 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
7837 class PolymorphicCodeCacheHashTable
7838 : public HashTable<PolymorphicCodeCacheHashTable,
7839 CodeCacheHashTableShape,
7842 Object* Lookup(MapHandleList* maps, int code_kind);
7844 static Handle<PolymorphicCodeCacheHashTable> Put(
7845 Handle<PolymorphicCodeCacheHashTable> hash_table,
7846 MapHandleList* maps,
7850 DECLARE_CAST(PolymorphicCodeCacheHashTable)
7852 static const int kInitialSize = 64;
7854 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
7858 class TypeFeedbackInfo: public Struct {
7860 inline int ic_total_count();
7861 inline void set_ic_total_count(int count);
7863 inline int ic_with_type_info_count();
7864 inline void change_ic_with_type_info_count(int delta);
7866 inline int ic_generic_count();
7867 inline void change_ic_generic_count(int delta);
7869 inline void initialize_storage();
7871 inline void change_own_type_change_checksum();
7872 inline int own_type_change_checksum();
7874 inline void set_inlined_type_change_checksum(int checksum);
7875 inline bool matches_inlined_type_change_checksum(int checksum);
7877 DECLARE_CAST(TypeFeedbackInfo)
7879 // Dispatched behavior.
7880 DECLARE_PRINTER(TypeFeedbackInfo)
7881 DECLARE_VERIFIER(TypeFeedbackInfo)
7883 static const int kStorage1Offset = HeapObject::kHeaderSize;
7884 static const int kStorage2Offset = kStorage1Offset + kPointerSize;
7885 static const int kStorage3Offset = kStorage2Offset + kPointerSize;
7886 static const int kSize = kStorage3Offset + kPointerSize;
7889 static const int kTypeChangeChecksumBits = 7;
7891 class ICTotalCountField: public BitField<int, 0,
7892 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7893 class OwnTypeChangeChecksum: public BitField<int,
7894 kSmiValueSize - kTypeChangeChecksumBits,
7895 kTypeChangeChecksumBits> {}; // NOLINT
7896 class ICsWithTypeInfoCountField: public BitField<int, 0,
7897 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7898 class InlinedTypeChangeChecksum: public BitField<int,
7899 kSmiValueSize - kTypeChangeChecksumBits,
7900 kTypeChangeChecksumBits> {}; // NOLINT
7902 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
7906 enum AllocationSiteMode {
7907 DONT_TRACK_ALLOCATION_SITE,
7908 TRACK_ALLOCATION_SITE,
7909 LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
7913 class AllocationSite: public Struct {
7915 static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
7916 static const double kPretenureRatio;
7917 static const int kPretenureMinimumCreated = 100;
7919 // Values for pretenure decision field.
7920 enum PretenureDecision {
7926 kLastPretenureDecisionValue = kZombie
7929 const char* PretenureDecisionName(PretenureDecision decision);
7931 DECL_ACCESSORS(transition_info, Object)
7932 // nested_site threads a list of sites that represent nested literals
7933 // walked in a particular order. So [[1, 2], 1, 2] will have one
7934 // nested_site, but [[1, 2], 3, [4]] will have a list of two.
7935 DECL_ACCESSORS(nested_site, Object)
7936 DECL_ACCESSORS(pretenure_data, Smi)
7937 DECL_ACCESSORS(pretenure_create_count, Smi)
7938 DECL_ACCESSORS(dependent_code, DependentCode)
7939 DECL_ACCESSORS(weak_next, Object)
7941 inline void Initialize();
7943 // This method is expensive, it should only be called for reporting.
7944 bool IsNestedSite();
7946 // transition_info bitfields, for constructed array transition info.
7947 class ElementsKindBits: public BitField<ElementsKind, 0, 15> {};
7948 class UnusedBits: public BitField<int, 15, 14> {};
7949 class DoNotInlineBit: public BitField<bool, 29, 1> {};
7951 // Bitfields for pretenure_data
7952 class MementoFoundCountBits: public BitField<int, 0, 26> {};
7953 class PretenureDecisionBits: public BitField<PretenureDecision, 26, 3> {};
7954 class DeoptDependentCodeBit: public BitField<bool, 29, 1> {};
7955 STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
7957 // Increments the mementos found counter and returns true when the first
7958 // memento was found for a given allocation site.
7959 inline bool IncrementMementoFoundCount();
7961 inline void IncrementMementoCreateCount();
7963 PretenureFlag GetPretenureMode();
7965 void ResetPretenureDecision();
7967 PretenureDecision pretenure_decision() {
7968 int value = pretenure_data()->value();
7969 return PretenureDecisionBits::decode(value);
7972 void set_pretenure_decision(PretenureDecision decision) {
7973 int value = pretenure_data()->value();
7975 Smi::FromInt(PretenureDecisionBits::update(value, decision)),
7976 SKIP_WRITE_BARRIER);
7979 bool deopt_dependent_code() {
7980 int value = pretenure_data()->value();
7981 return DeoptDependentCodeBit::decode(value);
7984 void set_deopt_dependent_code(bool deopt) {
7985 int value = pretenure_data()->value();
7987 Smi::FromInt(DeoptDependentCodeBit::update(value, deopt)),
7988 SKIP_WRITE_BARRIER);
7991 int memento_found_count() {
7992 int value = pretenure_data()->value();
7993 return MementoFoundCountBits::decode(value);
7996 inline void set_memento_found_count(int count);
7998 int memento_create_count() {
7999 return pretenure_create_count()->value();
8002 void set_memento_create_count(int count) {
8003 set_pretenure_create_count(Smi::FromInt(count), SKIP_WRITE_BARRIER);
8006 // The pretenuring decision is made during gc, and the zombie state allows
8007 // us to recognize when an allocation site is just being kept alive because
8008 // a later traversal of new space may discover AllocationMementos that point
8009 // to this AllocationSite.
8011 return pretenure_decision() == kZombie;
8014 bool IsMaybeTenure() {
8015 return pretenure_decision() == kMaybeTenure;
8018 inline void MarkZombie();
8020 inline bool MakePretenureDecision(PretenureDecision current_decision,
8022 bool maximum_size_scavenge);
8024 inline bool DigestPretenuringFeedback(bool maximum_size_scavenge);
8026 ElementsKind GetElementsKind() {
8027 DCHECK(!SitePointsToLiteral());
8028 int value = Smi::cast(transition_info())->value();
8029 return ElementsKindBits::decode(value);
8032 void SetElementsKind(ElementsKind kind) {
8033 int value = Smi::cast(transition_info())->value();
8034 set_transition_info(Smi::FromInt(ElementsKindBits::update(value, kind)),
8035 SKIP_WRITE_BARRIER);
8038 bool CanInlineCall() {
8039 int value = Smi::cast(transition_info())->value();
8040 return DoNotInlineBit::decode(value) == 0;
8043 void SetDoNotInlineCall() {
8044 int value = Smi::cast(transition_info())->value();
8045 set_transition_info(Smi::FromInt(DoNotInlineBit::update(value, true)),
8046 SKIP_WRITE_BARRIER);
8049 bool SitePointsToLiteral() {
8050 // If transition_info is a smi, then it represents an ElementsKind
8051 // for a constructed array. Otherwise, it must be a boilerplate
8052 // for an object or array literal.
8053 return transition_info()->IsJSArray() || transition_info()->IsJSObject();
8056 static void DigestTransitionFeedback(Handle<AllocationSite> site,
8057 ElementsKind to_kind);
8059 DECLARE_PRINTER(AllocationSite)
8060 DECLARE_VERIFIER(AllocationSite)
8062 DECLARE_CAST(AllocationSite)
8063 static inline AllocationSiteMode GetMode(
8064 ElementsKind boilerplate_elements_kind);
8065 static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
8066 static inline bool CanTrack(InstanceType type);
8068 static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
8069 static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
8070 static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
8071 static const int kPretenureCreateCountOffset =
8072 kPretenureDataOffset + kPointerSize;
8073 static const int kDependentCodeOffset =
8074 kPretenureCreateCountOffset + kPointerSize;
8075 static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
8076 static const int kSize = kWeakNextOffset + kPointerSize;
8078 // During mark compact we need to take special care for the dependent code
8080 static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
8081 static const int kPointerFieldsEndOffset = kWeakNextOffset;
8083 // For other visitors, use the fixed body descriptor below.
8084 typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
8085 kDependentCodeOffset + kPointerSize,
8086 kSize> BodyDescriptor;
8089 bool PretenuringDecisionMade() {
8090 return pretenure_decision() != kUndecided;
8093 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
8097 class AllocationMemento: public Struct {
8099 static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
8100 static const int kSize = kAllocationSiteOffset + kPointerSize;
8102 DECL_ACCESSORS(allocation_site, Object)
8105 return allocation_site()->IsAllocationSite() &&
8106 !AllocationSite::cast(allocation_site())->IsZombie();
8108 AllocationSite* GetAllocationSite() {
8110 return AllocationSite::cast(allocation_site());
8113 DECLARE_PRINTER(AllocationMemento)
8114 DECLARE_VERIFIER(AllocationMemento)
8116 DECLARE_CAST(AllocationMemento)
8119 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
8123 // Representation of a slow alias as part of a sloppy arguments objects.
8124 // For fast aliases (if HasSloppyArgumentsElements()):
8125 // - the parameter map contains an index into the context
8126 // - all attributes of the element have default values
8127 // For slow aliases (if HasDictionaryArgumentsElements()):
8128 // - the parameter map contains no fast alias mapping (i.e. the hole)
8129 // - this struct (in the slow backing store) contains an index into the context
8130 // - all attributes are available as part if the property details
8131 class AliasedArgumentsEntry: public Struct {
8133 inline int aliased_context_slot() const;
8134 inline void set_aliased_context_slot(int count);
8136 DECLARE_CAST(AliasedArgumentsEntry)
8138 // Dispatched behavior.
8139 DECLARE_PRINTER(AliasedArgumentsEntry)
8140 DECLARE_VERIFIER(AliasedArgumentsEntry)
8142 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
8143 static const int kSize = kAliasedContextSlot + kPointerSize;
8146 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
8150 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
8151 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
8154 class StringHasher {
8156 explicit inline StringHasher(int length, uint32_t seed);
8158 template <typename schar>
8159 static inline uint32_t HashSequentialString(const schar* chars,
8163 // Reads all the data, even for long strings and computes the utf16 length.
8164 static uint32_t ComputeUtf8Hash(Vector<const char> chars,
8166 int* utf16_length_out);
8168 // Calculated hash value for a string consisting of 1 to
8169 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
8170 // value is represented decimal value.
8171 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
8173 // No string is allowed to have a hash of zero. That value is reserved
8174 // for internal properties. If the hash calculation yields zero then we
8176 static const int kZeroHash = 27;
8178 // Reusable parts of the hashing algorithm.
8179 INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
8180 INLINE(static uint32_t GetHashCore(uint32_t running_hash));
8181 INLINE(static uint32_t ComputeRunningHash(uint32_t running_hash,
8182 const uc16* chars, int length));
8183 INLINE(static uint32_t ComputeRunningHashOneByte(uint32_t running_hash,
8188 // Returns the value to store in the hash field of a string with
8189 // the given length and contents.
8190 uint32_t GetHashField();
8191 // Returns true if the hash of this string can be computed without
8192 // looking at the contents.
8193 inline bool has_trivial_hash();
8194 // Adds a block of characters to the hash.
8195 template<typename Char>
8196 inline void AddCharacters(const Char* chars, int len);
8199 // Add a character to the hash.
8200 inline void AddCharacter(uint16_t c);
8201 // Update index. Returns true if string is still an index.
8202 inline bool UpdateIndex(uint16_t c);
8205 uint32_t raw_running_hash_;
8206 uint32_t array_index_;
8207 bool is_array_index_;
8208 bool is_first_char_;
8209 DISALLOW_COPY_AND_ASSIGN(StringHasher);
8213 class IteratingStringHasher : public StringHasher {
8215 static inline uint32_t Hash(String* string, uint32_t seed);
8216 inline void VisitOneByteString(const uint8_t* chars, int length);
8217 inline void VisitTwoByteString(const uint16_t* chars, int length);
8220 inline IteratingStringHasher(int len, uint32_t seed)
8221 : StringHasher(len, seed) {}
8222 void VisitConsString(ConsString* cons_string);
8223 DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher);
8227 // The characteristics of a string are stored in its map. Retrieving these
8228 // few bits of information is moderately expensive, involving two memory
8229 // loads where the second is dependent on the first. To improve efficiency
8230 // the shape of the string is given its own class so that it can be retrieved
8231 // once and used for several string operations. A StringShape is small enough
8232 // to be passed by value and is immutable, but be aware that flattening a
8233 // string can potentially alter its shape. Also be aware that a GC caused by
8234 // something else can alter the shape of a string due to ConsString
8235 // shortcutting. Keeping these restrictions in mind has proven to be error-
8236 // prone and so we no longer put StringShapes in variables unless there is a
8237 // concrete performance benefit at that particular point in the code.
8238 class StringShape BASE_EMBEDDED {
8240 inline explicit StringShape(const String* s);
8241 inline explicit StringShape(Map* s);
8242 inline explicit StringShape(InstanceType t);
8243 inline bool IsSequential();
8244 inline bool IsExternal();
8245 inline bool IsCons();
8246 inline bool IsSliced();
8247 inline bool IsIndirect();
8248 inline bool IsExternalOneByte();
8249 inline bool IsExternalTwoByte();
8250 inline bool IsSequentialOneByte();
8251 inline bool IsSequentialTwoByte();
8252 inline bool IsInternalized();
8253 inline StringRepresentationTag representation_tag();
8254 inline uint32_t encoding_tag();
8255 inline uint32_t full_representation_tag();
8256 inline uint32_t size_tag();
8258 inline uint32_t type() { return type_; }
8259 inline void invalidate() { valid_ = false; }
8260 inline bool valid() { return valid_; }
8262 inline void invalidate() { }
8268 inline void set_valid() { valid_ = true; }
8271 inline void set_valid() { }
8276 // The Name abstract class captures anything that can be used as a property
8277 // name, i.e., strings and symbols. All names store a hash value.
8278 class Name: public HeapObject {
8280 // Get and set the hash field of the name.
8281 inline uint32_t hash_field();
8282 inline void set_hash_field(uint32_t value);
8284 // Tells whether the hash code has been computed.
8285 inline bool HasHashCode();
8287 // Returns a hash value used for the property table
8288 inline uint32_t Hash();
8290 // Equality operations.
8291 inline bool Equals(Name* other);
8292 inline static bool Equals(Handle<Name> one, Handle<Name> two);
8295 inline bool AsArrayIndex(uint32_t* index);
8297 // If the name is private, it can only name own properties.
8298 inline bool IsPrivate();
8300 // If the name is a non-flat string, this method returns a flat version of the
8301 // string. Otherwise it'll just return the input.
8302 static inline Handle<Name> Flatten(Handle<Name> name,
8303 PretenureFlag pretenure = NOT_TENURED);
8307 DECLARE_PRINTER(Name)
8309 void NameShortPrint();
8310 int NameShortPrint(Vector<char> str);
8313 // Layout description.
8314 static const int kHashFieldSlot = HeapObject::kHeaderSize;
8315 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
8316 static const int kHashFieldOffset = kHashFieldSlot;
8318 static const int kHashFieldOffset = kHashFieldSlot + kIntSize;
8320 static const int kSize = kHashFieldSlot + kPointerSize;
8322 // Mask constant for checking if a name has a computed hash code
8323 // and if it is a string that is an array index. The least significant bit
8324 // indicates whether a hash code has been computed. If the hash code has
8325 // been computed the 2nd bit tells whether the string can be used as an
8327 static const int kHashNotComputedMask = 1;
8328 static const int kIsNotArrayIndexMask = 1 << 1;
8329 static const int kNofHashBitFields = 2;
8331 // Shift constant retrieving hash code from hash field.
8332 static const int kHashShift = kNofHashBitFields;
8334 // Only these bits are relevant in the hash, since the top two are shifted
8336 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8338 // Array index strings this short can keep their index in the hash field.
8339 static const int kMaxCachedArrayIndexLength = 7;
8341 // For strings which are array indexes the hash value has the string length
8342 // mixed into the hash, mainly to avoid a hash value of zero which would be
8343 // the case for the string '0'. 24 bits are used for the array index value.
8344 static const int kArrayIndexValueBits = 24;
8345 static const int kArrayIndexLengthBits =
8346 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8348 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8350 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8351 kArrayIndexValueBits> {}; // NOLINT
8352 class ArrayIndexLengthBits : public BitField<unsigned int,
8353 kNofHashBitFields + kArrayIndexValueBits,
8354 kArrayIndexLengthBits> {}; // NOLINT
8356 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8357 // could use a mask to test if the length of string is less than or equal to
8358 // kMaxCachedArrayIndexLength.
8359 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8361 static const unsigned int kContainsCachedArrayIndexMask =
8362 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8363 << ArrayIndexLengthBits::kShift) |
8364 kIsNotArrayIndexMask;
8366 // Value of empty hash field indicating that the hash is not computed.
8367 static const int kEmptyHashField =
8368 kIsNotArrayIndexMask | kHashNotComputedMask;
8371 static inline bool IsHashFieldComputed(uint32_t field);
8374 DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8379 class Symbol: public Name {
8381 // [name]: The print name of a symbol, or undefined if none.
8382 DECL_ACCESSORS(name, Object)
8384 DECL_ACCESSORS(flags, Smi)
8386 // [is_private]: Whether this is a private symbol. Private symbols can only
8387 // be used to designate own properties of objects.
8388 DECL_BOOLEAN_ACCESSORS(is_private)
8390 DECLARE_CAST(Symbol)
8392 // Dispatched behavior.
8393 DECLARE_PRINTER(Symbol)
8394 DECLARE_VERIFIER(Symbol)
8396 // Layout description.
8397 static const int kNameOffset = Name::kSize;
8398 static const int kFlagsOffset = kNameOffset + kPointerSize;
8399 static const int kSize = kFlagsOffset + kPointerSize;
8401 typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
8403 void SymbolShortPrint(std::ostream& os);
8406 static const int kPrivateBit = 0;
8408 const char* PrivateSymbolToName() const;
8411 friend class Name; // For PrivateSymbolToName.
8414 DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
8420 // The String abstract class captures JavaScript string values:
8423 // 4.3.16 String Value
8424 // A string value is a member of the type String and is a finite
8425 // ordered sequence of zero or more 16-bit unsigned integer values.
8427 // All string values have a length field.
8428 class String: public Name {
8430 enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
8432 // Array index strings this short can keep their index in the hash field.
8433 static const int kMaxCachedArrayIndexLength = 7;
8435 // For strings which are array indexes the hash value has the string length
8436 // mixed into the hash, mainly to avoid a hash value of zero which would be
8437 // the case for the string '0'. 24 bits are used for the array index value.
8438 static const int kArrayIndexValueBits = 24;
8439 static const int kArrayIndexLengthBits =
8440 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8442 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8444 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8445 kArrayIndexValueBits> {}; // NOLINT
8446 class ArrayIndexLengthBits : public BitField<unsigned int,
8447 kNofHashBitFields + kArrayIndexValueBits,
8448 kArrayIndexLengthBits> {}; // NOLINT
8450 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8451 // could use a mask to test if the length of string is less than or equal to
8452 // kMaxCachedArrayIndexLength.
8453 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8455 static const unsigned int kContainsCachedArrayIndexMask =
8456 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8457 << ArrayIndexLengthBits::kShift) |
8458 kIsNotArrayIndexMask;
8460 class SubStringRange {
8462 explicit SubStringRange(String* string, int first = 0, int length = -1)
8465 length_(length == -1 ? string->length() : length) {}
8467 inline iterator begin();
8468 inline iterator end();
8476 // Representation of the flat content of a String.
8477 // A non-flat string doesn't have flat content.
8478 // A flat string has content that's encoded as a sequence of either
8479 // one-byte chars or two-byte UC16.
8480 // Returned by String::GetFlatContent().
8483 // Returns true if the string is flat and this structure contains content.
8484 bool IsFlat() { return state_ != NON_FLAT; }
8485 // Returns true if the structure contains one-byte content.
8486 bool IsOneByte() { return state_ == ONE_BYTE; }
8487 // Returns true if the structure contains two-byte content.
8488 bool IsTwoByte() { return state_ == TWO_BYTE; }
8490 // Return the one byte content of the string. Only use if IsOneByte()
8492 Vector<const uint8_t> ToOneByteVector() {
8493 DCHECK_EQ(ONE_BYTE, state_);
8494 return Vector<const uint8_t>(onebyte_start, length_);
8496 // Return the two-byte content of the string. Only use if IsTwoByte()
8498 Vector<const uc16> ToUC16Vector() {
8499 DCHECK_EQ(TWO_BYTE, state_);
8500 return Vector<const uc16>(twobyte_start, length_);
8504 DCHECK(i < length_);
8505 DCHECK(state_ != NON_FLAT);
8506 if (state_ == ONE_BYTE) return onebyte_start[i];
8507 return twobyte_start[i];
8510 bool UsesSameString(const FlatContent& other) const {
8511 return onebyte_start == other.onebyte_start;
8515 enum State { NON_FLAT, ONE_BYTE, TWO_BYTE };
8517 // Constructors only used by String::GetFlatContent().
8518 explicit FlatContent(const uint8_t* start, int length)
8519 : onebyte_start(start), length_(length), state_(ONE_BYTE) {}
8520 explicit FlatContent(const uc16* start, int length)
8521 : twobyte_start(start), length_(length), state_(TWO_BYTE) { }
8522 FlatContent() : onebyte_start(NULL), length_(0), state_(NON_FLAT) { }
8525 const uint8_t* onebyte_start;
8526 const uc16* twobyte_start;
8531 friend class String;
8532 friend class IterableSubString;
8535 template <typename Char>
8536 INLINE(Vector<const Char> GetCharVector());
8538 // Get and set the length of the string.
8539 inline int length() const;
8540 inline void set_length(int value);
8542 // Get and set the length of the string using acquire loads and release
8544 inline int synchronized_length() const;
8545 inline void synchronized_set_length(int value);
8547 // Returns whether this string has only one-byte chars, i.e. all of them can
8548 // be one-byte encoded. This might be the case even if the string is
8549 // two-byte. Such strings may appear when the embedder prefers
8550 // two-byte external representations even for one-byte data.
8551 inline bool IsOneByteRepresentation() const;
8552 inline bool IsTwoByteRepresentation() const;
8554 // Cons and slices have an encoding flag that may not represent the actual
8555 // encoding of the underlying string. This is taken into account here.
8556 // Requires: this->IsFlat()
8557 inline bool IsOneByteRepresentationUnderneath();
8558 inline bool IsTwoByteRepresentationUnderneath();
8560 // NOTE: this should be considered only a hint. False negatives are
8562 inline bool HasOnlyOneByteChars();
8564 // Get and set individual two byte chars in the string.
8565 inline void Set(int index, uint16_t value);
8566 // Get individual two byte char in the string. Repeated calls
8567 // to this method are not efficient unless the string is flat.
8568 INLINE(uint16_t Get(int index));
8570 // Flattens the string. Checks first inline to see if it is
8571 // necessary. Does nothing if the string is not a cons string.
8572 // Flattening allocates a sequential string with the same data as
8573 // the given string and mutates the cons string to a degenerate
8574 // form, where the first component is the new sequential string and
8575 // the second component is the empty string. If allocation fails,
8576 // this function returns a failure. If flattening succeeds, this
8577 // function returns the sequential string that is now the first
8578 // component of the cons string.
8580 // Degenerate cons strings are handled specially by the garbage
8581 // collector (see IsShortcutCandidate).
8583 static inline Handle<String> Flatten(Handle<String> string,
8584 PretenureFlag pretenure = NOT_TENURED);
8586 // Tries to return the content of a flat string as a structure holding either
8587 // a flat vector of char or of uc16.
8588 // If the string isn't flat, and therefore doesn't have flat content, the
8589 // returned structure will report so, and can't provide a vector of either
8591 FlatContent GetFlatContent();
8593 // Returns the parent of a sliced string or first part of a flat cons string.
8594 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
8595 inline String* GetUnderlying();
8597 // String equality operations.
8598 inline bool Equals(String* other);
8599 inline static bool Equals(Handle<String> one, Handle<String> two);
8600 bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
8601 bool IsOneByteEqualTo(Vector<const uint8_t> str);
8602 bool IsTwoByteEqualTo(Vector<const uc16> str);
8604 // Return a UTF8 representation of the string. The string is null
8605 // terminated but may optionally contain nulls. Length is returned
8606 // in length_output if length_output is not a null pointer The string
8607 // should be nearly flat, otherwise the performance of this method may
8608 // be very slow (quadratic in the length). Setting robustness_flag to
8609 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8610 // handles unexpected data without causing assert failures and it does not
8611 // do any heap allocations. This is useful when printing stack traces.
8612 base::SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
8613 RobustnessFlag robustness_flag,
8614 int offset, int length,
8615 int* length_output = 0);
8616 base::SmartArrayPointer<char> ToCString(
8617 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
8618 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
8619 int* length_output = 0);
8621 // Return a 16 bit Unicode representation of the string.
8622 // The string should be nearly flat, otherwise the performance of
8623 // of this method may be very bad. Setting robustness_flag to
8624 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8625 // handles unexpected data without causing assert failures and it does not
8626 // do any heap allocations. This is useful when printing stack traces.
8627 base::SmartArrayPointer<uc16> ToWideCString(
8628 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
8630 bool ComputeArrayIndex(uint32_t* index);
8633 bool MakeExternal(v8::String::ExternalStringResource* resource);
8634 bool MakeExternal(v8::String::ExternalOneByteStringResource* resource);
8637 inline bool AsArrayIndex(uint32_t* index);
8639 DECLARE_CAST(String)
8641 void PrintOn(FILE* out);
8643 // For use during stack traces. Performs rudimentary sanity check.
8646 // Dispatched behavior.
8647 void StringShortPrint(StringStream* accumulator);
8648 void PrintUC16(std::ostream& os, int start = 0, int end = -1); // NOLINT
8649 #if defined(DEBUG) || defined(OBJECT_PRINT)
8650 char* ToAsciiArray();
8652 DECLARE_PRINTER(String)
8653 DECLARE_VERIFIER(String)
8655 inline bool IsFlat();
8657 // Layout description.
8658 static const int kLengthOffset = Name::kSize;
8659 static const int kSize = kLengthOffset + kPointerSize;
8661 // Maximum number of characters to consider when trying to convert a string
8662 // value into an array index.
8663 static const int kMaxArrayIndexSize = 10;
8664 STATIC_ASSERT(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
8667 static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
8668 static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
8669 static const int kMaxUtf16CodeUnit = 0xffff;
8670 static const uint32_t kMaxUtf16CodeUnitU = kMaxUtf16CodeUnit;
8672 // Value of hash field containing computed hash equal to zero.
8673 static const int kEmptyStringHash = kIsNotArrayIndexMask;
8675 // Maximal string length.
8676 static const int kMaxLength = (1 << 28) - 16;
8678 // Max length for computing hash. For strings longer than this limit the
8679 // string length is used as the hash value.
8680 static const int kMaxHashCalcLength = 16383;
8682 // Limit for truncation in short printing.
8683 static const int kMaxShortPrintLength = 1024;
8685 // Support for regular expressions.
8686 const uc16* GetTwoByteData(unsigned start);
8688 // Helper function for flattening strings.
8689 template <typename sinkchar>
8690 static void WriteToFlat(String* source,
8695 // The return value may point to the first aligned word containing the first
8696 // non-one-byte character, rather than directly to the non-one-byte character.
8697 // If the return value is >= the passed length, the entire string was
8699 static inline int NonAsciiStart(const char* chars, int length) {
8700 const char* start = chars;
8701 const char* limit = chars + length;
8703 if (length >= kIntptrSize) {
8704 // Check unaligned bytes.
8705 while (!IsAligned(reinterpret_cast<intptr_t>(chars), sizeof(uintptr_t))) {
8706 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8707 return static_cast<int>(chars - start);
8711 // Check aligned words.
8712 DCHECK(unibrow::Utf8::kMaxOneByteChar == 0x7F);
8713 const uintptr_t non_one_byte_mask = kUintptrAllBitsSet / 0xFF * 0x80;
8714 while (chars + sizeof(uintptr_t) <= limit) {
8715 if (*reinterpret_cast<const uintptr_t*>(chars) & non_one_byte_mask) {
8716 return static_cast<int>(chars - start);
8718 chars += sizeof(uintptr_t);
8721 // Check remaining unaligned bytes.
8722 while (chars < limit) {
8723 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8724 return static_cast<int>(chars - start);
8729 return static_cast<int>(chars - start);
8732 static inline bool IsAscii(const char* chars, int length) {
8733 return NonAsciiStart(chars, length) >= length;
8736 static inline bool IsAscii(const uint8_t* chars, int length) {
8738 NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
8741 static inline int NonOneByteStart(const uc16* chars, int length) {
8742 const uc16* limit = chars + length;
8743 const uc16* start = chars;
8744 while (chars < limit) {
8745 if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
8748 return static_cast<int>(chars - start);
8751 static inline bool IsOneByte(const uc16* chars, int length) {
8752 return NonOneByteStart(chars, length) >= length;
8755 template<class Visitor>
8756 static inline ConsString* VisitFlat(Visitor* visitor,
8760 static Handle<FixedArray> CalculateLineEnds(Handle<String> string,
8761 bool include_ending_line);
8763 // Use the hash field to forward to the canonical internalized string
8764 // when deserializing an internalized string.
8765 inline void SetForwardedInternalizedString(String* string);
8766 inline String* GetForwardedInternalizedString();
8770 friend class StringTableInsertionKey;
8772 static Handle<String> SlowFlatten(Handle<ConsString> cons,
8773 PretenureFlag tenure);
8775 // Slow case of String::Equals. This implementation works on any strings
8776 // but it is most efficient on strings that are almost flat.
8777 bool SlowEquals(String* other);
8779 static bool SlowEquals(Handle<String> one, Handle<String> two);
8781 // Slow case of AsArrayIndex.
8782 bool SlowAsArrayIndex(uint32_t* index);
8784 // Compute and set the hash code.
8785 uint32_t ComputeAndSetHash();
8787 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
8791 // The SeqString abstract class captures sequential string values.
8792 class SeqString: public String {
8794 DECLARE_CAST(SeqString)
8796 // Layout description.
8797 static const int kHeaderSize = String::kSize;
8799 // Truncate the string in-place if possible and return the result.
8800 // In case of new_length == 0, the empty string is returned without
8801 // truncating the original string.
8802 MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
8805 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
8809 // The OneByteString class captures sequential one-byte string objects.
8810 // Each character in the OneByteString is an one-byte character.
8811 class SeqOneByteString: public SeqString {
8813 static const bool kHasOneByteEncoding = true;
8815 // Dispatched behavior.
8816 inline uint16_t SeqOneByteStringGet(int index);
8817 inline void SeqOneByteStringSet(int index, uint16_t value);
8819 // Get the address of the characters in this string.
8820 inline Address GetCharsAddress();
8822 inline uint8_t* GetChars();
8824 DECLARE_CAST(SeqOneByteString)
8826 // Garbage collection support. This method is called by the
8827 // garbage collector to compute the actual size of an OneByteString
8829 inline int SeqOneByteStringSize(InstanceType instance_type);
8831 // Computes the size for an OneByteString instance of a given length.
8832 static int SizeFor(int length) {
8833 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
8836 // Maximal memory usage for a single sequential one-byte string.
8837 static const int kMaxSize = 512 * MB - 1;
8838 STATIC_ASSERT((kMaxSize - kHeaderSize) >= String::kMaxLength);
8841 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
8845 // The TwoByteString class captures sequential unicode string objects.
8846 // Each character in the TwoByteString is a two-byte uint16_t.
8847 class SeqTwoByteString: public SeqString {
8849 static const bool kHasOneByteEncoding = false;
8851 // Dispatched behavior.
8852 inline uint16_t SeqTwoByteStringGet(int index);
8853 inline void SeqTwoByteStringSet(int index, uint16_t value);
8855 // Get the address of the characters in this string.
8856 inline Address GetCharsAddress();
8858 inline uc16* GetChars();
8861 const uint16_t* SeqTwoByteStringGetData(unsigned start);
8863 DECLARE_CAST(SeqTwoByteString)
8865 // Garbage collection support. This method is called by the
8866 // garbage collector to compute the actual size of a TwoByteString
8868 inline int SeqTwoByteStringSize(InstanceType instance_type);
8870 // Computes the size for a TwoByteString instance of a given length.
8871 static int SizeFor(int length) {
8872 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
8875 // Maximal memory usage for a single sequential two-byte string.
8876 static const int kMaxSize = 512 * MB - 1;
8877 STATIC_ASSERT(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
8878 String::kMaxLength);
8881 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
8885 // The ConsString class describes string values built by using the
8886 // addition operator on strings. A ConsString is a pair where the
8887 // first and second components are pointers to other string values.
8888 // One or both components of a ConsString can be pointers to other
8889 // ConsStrings, creating a binary tree of ConsStrings where the leaves
8890 // are non-ConsString string values. The string value represented by
8891 // a ConsString can be obtained by concatenating the leaf string
8892 // values in a left-to-right depth-first traversal of the tree.
8893 class ConsString: public String {
8895 // First string of the cons cell.
8896 inline String* first();
8897 // Doesn't check that the result is a string, even in debug mode. This is
8898 // useful during GC where the mark bits confuse the checks.
8899 inline Object* unchecked_first();
8900 inline void set_first(String* first,
8901 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8903 // Second string of the cons cell.
8904 inline String* second();
8905 // Doesn't check that the result is a string, even in debug mode. This is
8906 // useful during GC where the mark bits confuse the checks.
8907 inline Object* unchecked_second();
8908 inline void set_second(String* second,
8909 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8911 // Dispatched behavior.
8912 uint16_t ConsStringGet(int index);
8914 DECLARE_CAST(ConsString)
8916 // Layout description.
8917 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
8918 static const int kSecondOffset = kFirstOffset + kPointerSize;
8919 static const int kSize = kSecondOffset + kPointerSize;
8921 // Minimum length for a cons string.
8922 static const int kMinLength = 13;
8924 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
8927 DECLARE_VERIFIER(ConsString)
8930 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
8934 // The Sliced String class describes strings that are substrings of another
8935 // sequential string. The motivation is to save time and memory when creating
8936 // a substring. A Sliced String is described as a pointer to the parent,
8937 // the offset from the start of the parent string and the length. Using
8938 // a Sliced String therefore requires unpacking of the parent string and
8939 // adding the offset to the start address. A substring of a Sliced String
8940 // are not nested since the double indirection is simplified when creating
8941 // such a substring.
8942 // Currently missing features are:
8943 // - handling externalized parent strings
8944 // - external strings as parent
8945 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
8946 class SlicedString: public String {
8948 inline String* parent();
8949 inline void set_parent(String* parent,
8950 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8951 inline int offset() const;
8952 inline void set_offset(int offset);
8954 // Dispatched behavior.
8955 uint16_t SlicedStringGet(int index);
8957 DECLARE_CAST(SlicedString)
8959 // Layout description.
8960 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
8961 static const int kOffsetOffset = kParentOffset + kPointerSize;
8962 static const int kSize = kOffsetOffset + kPointerSize;
8964 // Minimum length for a sliced string.
8965 static const int kMinLength = 13;
8967 typedef FixedBodyDescriptor<kParentOffset,
8968 kOffsetOffset + kPointerSize, kSize>
8971 DECLARE_VERIFIER(SlicedString)
8974 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
8978 // The ExternalString class describes string values that are backed by
8979 // a string resource that lies outside the V8 heap. ExternalStrings
8980 // consist of the length field common to all strings, a pointer to the
8981 // external resource. It is important to ensure (externally) that the
8982 // resource is not deallocated while the ExternalString is live in the
8985 // The API expects that all ExternalStrings are created through the
8986 // API. Therefore, ExternalStrings should not be used internally.
8987 class ExternalString: public String {
8989 DECLARE_CAST(ExternalString)
8991 // Layout description.
8992 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
8993 static const int kShortSize = kResourceOffset + kPointerSize;
8994 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
8995 static const int kSize = kResourceDataOffset + kPointerSize;
8997 static const int kMaxShortLength =
8998 (kShortSize - SeqString::kHeaderSize) / kCharSize;
9000 // Return whether external string is short (data pointer is not cached).
9001 inline bool is_short();
9003 STATIC_ASSERT(kResourceOffset == Internals::kStringResourceOffset);
9006 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
9010 // The ExternalOneByteString class is an external string backed by an
9012 class ExternalOneByteString : public ExternalString {
9014 static const bool kHasOneByteEncoding = true;
9016 typedef v8::String::ExternalOneByteStringResource Resource;
9018 // The underlying resource.
9019 inline const Resource* resource();
9020 inline void set_resource(const Resource* buffer);
9022 // Update the pointer cache to the external character array.
9023 // The cached pointer is always valid, as the external character array does =
9024 // not move during lifetime. Deserialization is the only exception, after
9025 // which the pointer cache has to be refreshed.
9026 inline void update_data_cache();
9028 inline const uint8_t* GetChars();
9030 // Dispatched behavior.
9031 inline uint16_t ExternalOneByteStringGet(int index);
9033 DECLARE_CAST(ExternalOneByteString)
9035 // Garbage collection support.
9036 inline void ExternalOneByteStringIterateBody(ObjectVisitor* v);
9038 template <typename StaticVisitor>
9039 inline void ExternalOneByteStringIterateBody();
9042 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalOneByteString);
9046 // The ExternalTwoByteString class is an external string backed by a UTF-16
9048 class ExternalTwoByteString: public ExternalString {
9050 static const bool kHasOneByteEncoding = false;
9052 typedef v8::String::ExternalStringResource Resource;
9054 // The underlying string resource.
9055 inline const Resource* resource();
9056 inline void set_resource(const Resource* buffer);
9058 // Update the pointer cache to the external character array.
9059 // The cached pointer is always valid, as the external character array does =
9060 // not move during lifetime. Deserialization is the only exception, after
9061 // which the pointer cache has to be refreshed.
9062 inline void update_data_cache();
9064 inline const uint16_t* GetChars();
9066 // Dispatched behavior.
9067 inline uint16_t ExternalTwoByteStringGet(int index);
9070 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
9072 DECLARE_CAST(ExternalTwoByteString)
9074 // Garbage collection support.
9075 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
9077 template<typename StaticVisitor>
9078 inline void ExternalTwoByteStringIterateBody();
9081 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
9085 // Utility superclass for stack-allocated objects that must be updated
9086 // on gc. It provides two ways for the gc to update instances, either
9087 // iterating or updating after gc.
9088 class Relocatable BASE_EMBEDDED {
9090 explicit inline Relocatable(Isolate* isolate);
9091 inline virtual ~Relocatable();
9092 virtual void IterateInstance(ObjectVisitor* v) { }
9093 virtual void PostGarbageCollection() { }
9095 static void PostGarbageCollectionProcessing(Isolate* isolate);
9096 static int ArchiveSpacePerThread();
9097 static char* ArchiveState(Isolate* isolate, char* to);
9098 static char* RestoreState(Isolate* isolate, char* from);
9099 static void Iterate(Isolate* isolate, ObjectVisitor* v);
9100 static void Iterate(ObjectVisitor* v, Relocatable* top);
9101 static char* Iterate(ObjectVisitor* v, char* t);
9109 // A flat string reader provides random access to the contents of a
9110 // string independent of the character width of the string. The handle
9111 // must be valid as long as the reader is being used.
9112 class FlatStringReader : public Relocatable {
9114 FlatStringReader(Isolate* isolate, Handle<String> str);
9115 FlatStringReader(Isolate* isolate, Vector<const char> input);
9116 void PostGarbageCollection();
9117 inline uc32 Get(int index);
9118 template <typename Char>
9119 inline Char Get(int index);
9120 int length() { return length_; }
9129 // This maintains an off-stack representation of the stack frames required
9130 // to traverse a ConsString, allowing an entirely iterative and restartable
9131 // traversal of the entire string
9132 class ConsStringIterator {
9134 inline ConsStringIterator() {}
9135 inline explicit ConsStringIterator(ConsString* cons_string, int offset = 0) {
9136 Reset(cons_string, offset);
9138 inline void Reset(ConsString* cons_string, int offset = 0) {
9140 // Next will always return NULL.
9141 if (cons_string == NULL) return;
9142 Initialize(cons_string, offset);
9144 // Returns NULL when complete.
9145 inline String* Next(int* offset_out) {
9147 if (depth_ == 0) return NULL;
9148 return Continue(offset_out);
9152 static const int kStackSize = 32;
9153 // Use a mask instead of doing modulo operations for stack wrapping.
9154 static const int kDepthMask = kStackSize-1;
9155 STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
9156 static inline int OffsetForDepth(int depth);
9158 inline void PushLeft(ConsString* string);
9159 inline void PushRight(ConsString* string);
9160 inline void AdjustMaximumDepth();
9162 inline bool StackBlown() { return maximum_depth_ - depth_ == kStackSize; }
9163 void Initialize(ConsString* cons_string, int offset);
9164 String* Continue(int* offset_out);
9165 String* NextLeaf(bool* blew_stack);
9166 String* Search(int* offset_out);
9168 // Stack must always contain only frames for which right traversal
9169 // has not yet been performed.
9170 ConsString* frames_[kStackSize];
9175 DISALLOW_COPY_AND_ASSIGN(ConsStringIterator);
9179 class StringCharacterStream {
9181 inline StringCharacterStream(String* string,
9183 inline uint16_t GetNext();
9184 inline bool HasMore();
9185 inline void Reset(String* string, int offset = 0);
9186 inline void VisitOneByteString(const uint8_t* chars, int length);
9187 inline void VisitTwoByteString(const uint16_t* chars, int length);
9190 ConsStringIterator iter_;
9193 const uint8_t* buffer8_;
9194 const uint16_t* buffer16_;
9196 const uint8_t* end_;
9197 DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
9201 template <typename T>
9202 class VectorIterator {
9204 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
9205 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
9206 T GetNext() { return data_[index_++]; }
9207 bool has_more() { return index_ < data_.length(); }
9209 Vector<const T> data_;
9214 // The Oddball describes objects null, undefined, true, and false.
9215 class Oddball: public HeapObject {
9217 // [to_string]: Cached to_string computed at startup.
9218 DECL_ACCESSORS(to_string, String)
9220 // [to_number]: Cached to_number computed at startup.
9221 DECL_ACCESSORS(to_number, Object)
9223 // [typeof]: Cached type_of computed at startup.
9224 DECL_ACCESSORS(type_of, String)
9226 inline byte kind() const;
9227 inline void set_kind(byte kind);
9229 DECLARE_CAST(Oddball)
9231 // Dispatched behavior.
9232 DECLARE_VERIFIER(Oddball)
9234 // Initialize the fields.
9235 static void Initialize(Isolate* isolate, Handle<Oddball> oddball,
9236 const char* to_string, Handle<Object> to_number,
9237 const char* type_of, byte kind);
9239 // Layout description.
9240 static const int kToStringOffset = HeapObject::kHeaderSize;
9241 static const int kToNumberOffset = kToStringOffset + kPointerSize;
9242 static const int kTypeOfOffset = kToNumberOffset + kPointerSize;
9243 static const int kKindOffset = kTypeOfOffset + kPointerSize;
9244 static const int kSize = kKindOffset + kPointerSize;
9246 static const byte kFalse = 0;
9247 static const byte kTrue = 1;
9248 static const byte kNotBooleanMask = ~1;
9249 static const byte kTheHole = 2;
9250 static const byte kNull = 3;
9251 static const byte kArgumentMarker = 4;
9252 static const byte kUndefined = 5;
9253 static const byte kUninitialized = 6;
9254 static const byte kOther = 7;
9255 static const byte kException = 8;
9257 typedef FixedBodyDescriptor<kToStringOffset, kTypeOfOffset + kPointerSize,
9258 kSize> BodyDescriptor;
9260 STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset);
9261 STATIC_ASSERT(kNull == Internals::kNullOddballKind);
9262 STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind);
9265 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
9269 class Cell: public HeapObject {
9271 // [value]: value of the cell.
9272 DECL_ACCESSORS(value, Object)
9276 static inline Cell* FromValueAddress(Address value) {
9277 Object* result = FromAddress(value - kValueOffset);
9278 return static_cast<Cell*>(result);
9281 inline Address ValueAddress() {
9282 return address() + kValueOffset;
9285 // Dispatched behavior.
9286 DECLARE_PRINTER(Cell)
9287 DECLARE_VERIFIER(Cell)
9289 // Layout description.
9290 static const int kValueOffset = HeapObject::kHeaderSize;
9291 static const int kSize = kValueOffset + kPointerSize;
9293 typedef FixedBodyDescriptor<kValueOffset,
9294 kValueOffset + kPointerSize,
9295 kSize> BodyDescriptor;
9298 DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9302 class PropertyCell : public HeapObject {
9304 // [property_details]: details of the global property.
9305 DECL_ACCESSORS(property_details_raw, Object)
9306 // [value]: value of the global property.
9307 DECL_ACCESSORS(value, Object)
9308 // [dependent_code]: dependent code that depends on the type of the global
9310 DECL_ACCESSORS(dependent_code, DependentCode)
9312 PropertyDetails property_details() {
9313 return PropertyDetails(Smi::cast(property_details_raw()));
9316 void set_property_details(PropertyDetails details) {
9317 set_property_details_raw(details.AsSmi());
9320 PropertyCellConstantType GetConstantType();
9322 // Computes the new type of the cell's contents for the given value, but
9323 // without actually modifying the details.
9324 static PropertyCellType UpdatedType(Handle<PropertyCell> cell,
9325 Handle<Object> value,
9326 PropertyDetails details);
9327 static void UpdateCell(Handle<GlobalDictionary> dictionary, int entry,
9328 Handle<Object> value, PropertyDetails details);
9330 static Handle<PropertyCell> InvalidateEntry(
9331 Handle<GlobalDictionary> dictionary, int entry);
9333 static void SetValueWithInvalidation(Handle<PropertyCell> cell,
9334 Handle<Object> new_value);
9336 DECLARE_CAST(PropertyCell)
9338 // Dispatched behavior.
9339 DECLARE_PRINTER(PropertyCell)
9340 DECLARE_VERIFIER(PropertyCell)
9342 // Layout description.
9343 static const int kDetailsOffset = HeapObject::kHeaderSize;
9344 static const int kValueOffset = kDetailsOffset + kPointerSize;
9345 static const int kDependentCodeOffset = kValueOffset + kPointerSize;
9346 static const int kSize = kDependentCodeOffset + kPointerSize;
9348 static const int kPointerFieldsBeginOffset = kValueOffset;
9349 static const int kPointerFieldsEndOffset = kSize;
9351 typedef FixedBodyDescriptor<kValueOffset,
9353 kSize> BodyDescriptor;
9356 DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9360 class WeakCell : public HeapObject {
9362 inline Object* value() const;
9364 // This should not be called by anyone except GC.
9365 inline void clear();
9367 // This should not be called by anyone except allocator.
9368 inline void initialize(HeapObject* value);
9370 inline bool cleared() const;
9372 DECL_ACCESSORS(next, Object)
9374 inline void clear_next(Heap* heap);
9376 inline bool next_cleared();
9378 DECLARE_CAST(WeakCell)
9380 DECLARE_PRINTER(WeakCell)
9381 DECLARE_VERIFIER(WeakCell)
9383 // Layout description.
9384 static const int kValueOffset = HeapObject::kHeaderSize;
9385 static const int kNextOffset = kValueOffset + kPointerSize;
9386 static const int kSize = kNextOffset + kPointerSize;
9388 typedef FixedBodyDescriptor<kValueOffset, kSize, kSize> BodyDescriptor;
9391 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakCell);
9395 // The JSProxy describes EcmaScript Harmony proxies
9396 class JSProxy: public JSReceiver {
9398 // [handler]: The handler property.
9399 DECL_ACCESSORS(handler, Object)
9401 // [hash]: The hash code property (undefined if not initialized yet).
9402 DECL_ACCESSORS(hash, Object)
9404 DECLARE_CAST(JSProxy)
9406 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithHandler(
9407 Handle<JSProxy> proxy,
9408 Handle<Object> receiver,
9411 // If the handler defines an accessor property with a setter, invoke it.
9412 // If it defines an accessor property without a setter, or a data property
9413 // that is read-only, throw. In all these cases set '*done' to true,
9414 // otherwise set it to false.
9416 static MaybeHandle<Object> SetPropertyViaPrototypesWithHandler(
9417 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9418 Handle<Object> value, LanguageMode language_mode, bool* done);
9420 MUST_USE_RESULT static Maybe<PropertyAttributes>
9421 GetPropertyAttributesWithHandler(Handle<JSProxy> proxy,
9422 Handle<Object> receiver,
9424 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithHandler(
9425 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9426 Handle<Object> value, LanguageMode language_mode);
9428 // Turn the proxy into an (empty) JSObject.
9429 static void Fix(Handle<JSProxy> proxy);
9431 // Initializes the body after the handler slot.
9432 inline void InitializeBody(int object_size, Object* value);
9434 // Invoke a trap by name. If the trap does not exist on this's handler,
9435 // but derived_trap is non-NULL, invoke that instead. May cause GC.
9436 MUST_USE_RESULT static MaybeHandle<Object> CallTrap(
9437 Handle<JSProxy> proxy,
9439 Handle<Object> derived_trap,
9441 Handle<Object> args[]);
9443 // Dispatched behavior.
9444 DECLARE_PRINTER(JSProxy)
9445 DECLARE_VERIFIER(JSProxy)
9447 // Layout description. We add padding so that a proxy has the same
9448 // size as a virgin JSObject. This is essential for becoming a JSObject
9450 static const int kHandlerOffset = HeapObject::kHeaderSize;
9451 static const int kHashOffset = kHandlerOffset + kPointerSize;
9452 static const int kPaddingOffset = kHashOffset + kPointerSize;
9453 static const int kSize = JSObject::kHeaderSize;
9454 static const int kHeaderSize = kPaddingOffset;
9455 static const int kPaddingSize = kSize - kPaddingOffset;
9457 STATIC_ASSERT(kPaddingSize >= 0);
9459 typedef FixedBodyDescriptor<kHandlerOffset,
9461 kSize> BodyDescriptor;
9464 friend class JSReceiver;
9466 MUST_USE_RESULT static Maybe<bool> HasPropertyWithHandler(
9467 Handle<JSProxy> proxy, Handle<Name> name);
9469 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithHandler(
9470 Handle<JSProxy> proxy, Handle<Name> name, LanguageMode language_mode);
9472 MUST_USE_RESULT Object* GetIdentityHash();
9474 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
9476 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
9480 class JSFunctionProxy: public JSProxy {
9482 // [call_trap]: The call trap.
9483 DECL_ACCESSORS(call_trap, Object)
9485 // [construct_trap]: The construct trap.
9486 DECL_ACCESSORS(construct_trap, Object)
9488 DECLARE_CAST(JSFunctionProxy)
9490 // Dispatched behavior.
9491 DECLARE_PRINTER(JSFunctionProxy)
9492 DECLARE_VERIFIER(JSFunctionProxy)
9494 // Layout description.
9495 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
9496 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
9497 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
9498 static const int kSize = JSFunction::kSize;
9499 static const int kPaddingSize = kSize - kPaddingOffset;
9501 STATIC_ASSERT(kPaddingSize >= 0);
9503 typedef FixedBodyDescriptor<kHandlerOffset,
9504 kConstructTrapOffset + kPointerSize,
9505 kSize> BodyDescriptor;
9508 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
9512 class JSCollection : public JSObject {
9514 // [table]: the backing hash table
9515 DECL_ACCESSORS(table, Object)
9517 static const int kTableOffset = JSObject::kHeaderSize;
9518 static const int kSize = kTableOffset + kPointerSize;
9521 DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollection);
9525 // The JSSet describes EcmaScript Harmony sets
9526 class JSSet : public JSCollection {
9530 // Dispatched behavior.
9531 DECLARE_PRINTER(JSSet)
9532 DECLARE_VERIFIER(JSSet)
9535 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
9539 // The JSMap describes EcmaScript Harmony maps
9540 class JSMap : public JSCollection {
9544 // Dispatched behavior.
9545 DECLARE_PRINTER(JSMap)
9546 DECLARE_VERIFIER(JSMap)
9549 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
9553 // OrderedHashTableIterator is an iterator that iterates over the keys and
9554 // values of an OrderedHashTable.
9556 // The iterator has a reference to the underlying OrderedHashTable data,
9557 // [table], as well as the current [index] the iterator is at.
9559 // When the OrderedHashTable is rehashed it adds a reference from the old table
9560 // to the new table as well as storing enough data about the changes so that the
9561 // iterator [index] can be adjusted accordingly.
9563 // When the [Next] result from the iterator is requested, the iterator checks if
9564 // there is a newer table that it needs to transition to.
9565 template<class Derived, class TableType>
9566 class OrderedHashTableIterator: public JSObject {
9568 // [table]: the backing hash table mapping keys to values.
9569 DECL_ACCESSORS(table, Object)
9571 // [index]: The index into the data table.
9572 DECL_ACCESSORS(index, Object)
9574 // [kind]: The kind of iteration this is. One of the [Kind] enum values.
9575 DECL_ACCESSORS(kind, Object)
9578 void OrderedHashTableIteratorPrint(std::ostream& os); // NOLINT
9581 static const int kTableOffset = JSObject::kHeaderSize;
9582 static const int kIndexOffset = kTableOffset + kPointerSize;
9583 static const int kKindOffset = kIndexOffset + kPointerSize;
9584 static const int kSize = kKindOffset + kPointerSize;
9592 // Whether the iterator has more elements. This needs to be called before
9593 // calling |CurrentKey| and/or |CurrentValue|.
9596 // Move the index forward one.
9598 set_index(Smi::FromInt(Smi::cast(index())->value() + 1));
9601 // Populates the array with the next key and value and then moves the iterator
9603 // This returns the |kind| or 0 if the iterator is already at the end.
9604 Smi* Next(JSArray* value_array);
9606 // Returns the current key of the iterator. This should only be called when
9607 // |HasMore| returns true.
9608 inline Object* CurrentKey();
9611 // Transitions the iterator to the non obsolete backing store. This is a NOP
9612 // if the [table] is not obsolete.
9615 DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
9619 class JSSetIterator: public OrderedHashTableIterator<JSSetIterator,
9622 // Dispatched behavior.
9623 DECLARE_PRINTER(JSSetIterator)
9624 DECLARE_VERIFIER(JSSetIterator)
9626 DECLARE_CAST(JSSetIterator)
9628 // Called by |Next| to populate the array. This allows the subclasses to
9629 // populate the array differently.
9630 inline void PopulateValueArray(FixedArray* array);
9633 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSetIterator);
9637 class JSMapIterator: public OrderedHashTableIterator<JSMapIterator,
9640 // Dispatched behavior.
9641 DECLARE_PRINTER(JSMapIterator)
9642 DECLARE_VERIFIER(JSMapIterator)
9644 DECLARE_CAST(JSMapIterator)
9646 // Called by |Next| to populate the array. This allows the subclasses to
9647 // populate the array differently.
9648 inline void PopulateValueArray(FixedArray* array);
9651 // Returns the current value of the iterator. This should only be called when
9652 // |HasMore| returns true.
9653 inline Object* CurrentValue();
9655 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMapIterator);
9659 // Base class for both JSWeakMap and JSWeakSet
9660 class JSWeakCollection: public JSObject {
9662 // [table]: the backing hash table mapping keys to values.
9663 DECL_ACCESSORS(table, Object)
9665 // [next]: linked list of encountered weak maps during GC.
9666 DECL_ACCESSORS(next, Object)
9668 static const int kTableOffset = JSObject::kHeaderSize;
9669 static const int kNextOffset = kTableOffset + kPointerSize;
9670 static const int kSize = kNextOffset + kPointerSize;
9673 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
9677 // The JSWeakMap describes EcmaScript Harmony weak maps
9678 class JSWeakMap: public JSWeakCollection {
9680 DECLARE_CAST(JSWeakMap)
9682 // Dispatched behavior.
9683 DECLARE_PRINTER(JSWeakMap)
9684 DECLARE_VERIFIER(JSWeakMap)
9687 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
9691 // The JSWeakSet describes EcmaScript Harmony weak sets
9692 class JSWeakSet: public JSWeakCollection {
9694 DECLARE_CAST(JSWeakSet)
9696 // Dispatched behavior.
9697 DECLARE_PRINTER(JSWeakSet)
9698 DECLARE_VERIFIER(JSWeakSet)
9701 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
9705 // Whether a JSArrayBuffer is a SharedArrayBuffer or not.
9706 enum class SharedFlag { kNotShared, kShared };
9709 class JSArrayBuffer: public JSObject {
9711 // [backing_store]: backing memory for this array
9712 DECL_ACCESSORS(backing_store, void)
9714 // [byte_length]: length in bytes
9715 DECL_ACCESSORS(byte_length, Object)
9717 inline uint32_t bit_field() const;
9718 inline void set_bit_field(uint32_t bits);
9720 inline bool is_external();
9721 inline void set_is_external(bool value);
9723 inline bool is_neuterable();
9724 inline void set_is_neuterable(bool value);
9726 inline bool was_neutered();
9727 inline void set_was_neutered(bool value);
9729 inline bool is_shared();
9730 inline void set_is_shared(bool value);
9732 DECLARE_CAST(JSArrayBuffer)
9736 // Dispatched behavior.
9737 DECLARE_PRINTER(JSArrayBuffer)
9738 DECLARE_VERIFIER(JSArrayBuffer)
9740 static const int kBackingStoreOffset = JSObject::kHeaderSize;
9741 static const int kByteLengthOffset = kBackingStoreOffset + kPointerSize;
9742 static const int kBitFieldSlot = kByteLengthOffset + kPointerSize;
9743 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
9744 static const int kBitFieldOffset = kBitFieldSlot;
9746 static const int kBitFieldOffset = kBitFieldSlot + kIntSize;
9748 static const int kSize = kBitFieldSlot + kPointerSize;
9750 static const int kSizeWithInternalFields =
9751 kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
9753 class IsExternal : public BitField<bool, 1, 1> {};
9754 class IsNeuterable : public BitField<bool, 2, 1> {};
9755 class WasNeutered : public BitField<bool, 3, 1> {};
9756 class IsShared : public BitField<bool, 4, 1> {};
9759 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
9763 class JSArrayBufferView: public JSObject {
9765 // [buffer]: ArrayBuffer that this typed array views.
9766 DECL_ACCESSORS(buffer, Object)
9768 // [byte_offset]: offset of typed array in bytes.
9769 DECL_ACCESSORS(byte_offset, Object)
9771 // [byte_length]: length of typed array in bytes.
9772 DECL_ACCESSORS(byte_length, Object)
9774 DECLARE_CAST(JSArrayBufferView)
9776 DECLARE_VERIFIER(JSArrayBufferView)
9778 inline bool WasNeutered() const;
9780 static const int kBufferOffset = JSObject::kHeaderSize;
9781 static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
9782 static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
9783 static const int kViewSize = kByteLengthOffset + kPointerSize;
9787 DECL_ACCESSORS(raw_byte_offset, Object)
9788 DECL_ACCESSORS(raw_byte_length, Object)
9791 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
9795 class JSTypedArray: public JSArrayBufferView {
9797 // [length]: length of typed array in elements.
9798 DECL_ACCESSORS(length, Object)
9799 inline uint32_t length_value() const;
9801 DECLARE_CAST(JSTypedArray)
9803 ExternalArrayType type();
9804 size_t element_size();
9806 Handle<JSArrayBuffer> GetBuffer();
9808 // Dispatched behavior.
9809 DECLARE_PRINTER(JSTypedArray)
9810 DECLARE_VERIFIER(JSTypedArray)
9812 static const int kLengthOffset = kViewSize + kPointerSize;
9813 static const int kSize = kLengthOffset + kPointerSize;
9815 static const int kSizeWithInternalFields =
9816 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9819 static Handle<JSArrayBuffer> MaterializeArrayBuffer(
9820 Handle<JSTypedArray> typed_array);
9822 DECL_ACCESSORS(raw_length, Object)
9825 DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
9829 class JSDataView: public JSArrayBufferView {
9831 DECLARE_CAST(JSDataView)
9833 // Dispatched behavior.
9834 DECLARE_PRINTER(JSDataView)
9835 DECLARE_VERIFIER(JSDataView)
9837 static const int kSize = kViewSize;
9839 static const int kSizeWithInternalFields =
9840 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9843 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
9847 // Foreign describes objects pointing from JavaScript to C structures.
9848 class Foreign: public HeapObject {
9850 // [address]: field containing the address.
9851 inline Address foreign_address();
9852 inline void set_foreign_address(Address value);
9854 DECLARE_CAST(Foreign)
9856 // Dispatched behavior.
9857 inline void ForeignIterateBody(ObjectVisitor* v);
9859 template<typename StaticVisitor>
9860 inline void ForeignIterateBody();
9862 // Dispatched behavior.
9863 DECLARE_PRINTER(Foreign)
9864 DECLARE_VERIFIER(Foreign)
9866 // Layout description.
9868 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
9869 static const int kSize = kForeignAddressOffset + kPointerSize;
9871 STATIC_ASSERT(kForeignAddressOffset == Internals::kForeignAddressOffset);
9874 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
9878 // The JSArray describes JavaScript Arrays
9879 // Such an array can be in one of two modes:
9880 // - fast, backing storage is a FixedArray and length <= elements.length();
9881 // Please note: push and pop can be used to grow and shrink the array.
9882 // - slow, backing storage is a HashTable with numbers as keys.
9883 class JSArray: public JSObject {
9885 // [length]: The length property.
9886 DECL_ACCESSORS(length, Object)
9888 // Overload the length setter to skip write barrier when the length
9889 // is set to a smi. This matches the set function on FixedArray.
9890 inline void set_length(Smi* length);
9892 static bool HasReadOnlyLength(Handle<JSArray> array);
9893 static bool WouldChangeReadOnlyLength(Handle<JSArray> array, uint32_t index);
9894 static MaybeHandle<Object> ReadOnlyLengthError(Handle<JSArray> array);
9896 // Initialize the array with the given capacity. The function may
9897 // fail due to out-of-memory situations, but only if the requested
9898 // capacity is non-zero.
9899 static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
9901 // If the JSArray has fast elements, and new_length would result in
9902 // normalization, returns true.
9903 bool SetLengthWouldNormalize(uint32_t new_length);
9904 static inline bool SetLengthWouldNormalize(Heap* heap, uint32_t new_length);
9906 // Initializes the array to a certain length.
9907 inline bool AllowsSetLength();
9909 static void SetLength(Handle<JSArray> array, uint32_t length);
9910 // Same as above but will also queue splice records if |array| is observed.
9911 static MaybeHandle<Object> ObservableSetLength(Handle<JSArray> array,
9914 // Set the content of the array to the content of storage.
9915 static inline void SetContent(Handle<JSArray> array,
9916 Handle<FixedArrayBase> storage);
9918 DECLARE_CAST(JSArray)
9920 // Dispatched behavior.
9921 DECLARE_PRINTER(JSArray)
9922 DECLARE_VERIFIER(JSArray)
9924 // Number of element slots to pre-allocate for an empty array.
9925 static const int kPreallocatedArrayElements = 4;
9927 // Layout description.
9928 static const int kLengthOffset = JSObject::kHeaderSize;
9929 static const int kSize = kLengthOffset + kPointerSize;
9932 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
9936 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
9937 Handle<Map> initial_map);
9940 // JSRegExpResult is just a JSArray with a specific initial map.
9941 // This initial map adds in-object properties for "index" and "input"
9942 // properties, as assigned by RegExp.prototype.exec, which allows
9943 // faster creation of RegExp exec results.
9944 // This class just holds constants used when creating the result.
9945 // After creation the result must be treated as a JSArray in all regards.
9946 class JSRegExpResult: public JSArray {
9948 // Offsets of object fields.
9949 static const int kIndexOffset = JSArray::kSize;
9950 static const int kInputOffset = kIndexOffset + kPointerSize;
9951 static const int kSize = kInputOffset + kPointerSize;
9952 // Indices of in-object properties.
9953 static const int kIndexIndex = 0;
9954 static const int kInputIndex = 1;
9956 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
9960 class AccessorInfo: public Struct {
9962 DECL_ACCESSORS(name, Object)
9963 DECL_ACCESSORS(flag, Smi)
9964 DECL_ACCESSORS(expected_receiver_type, Object)
9966 inline bool all_can_read();
9967 inline void set_all_can_read(bool value);
9969 inline bool all_can_write();
9970 inline void set_all_can_write(bool value);
9972 inline bool is_special_data_property();
9973 inline void set_is_special_data_property(bool value);
9975 inline PropertyAttributes property_attributes();
9976 inline void set_property_attributes(PropertyAttributes attributes);
9978 // Checks whether the given receiver is compatible with this accessor.
9979 static bool IsCompatibleReceiverMap(Isolate* isolate,
9980 Handle<AccessorInfo> info,
9982 inline bool IsCompatibleReceiver(Object* receiver);
9984 DECLARE_CAST(AccessorInfo)
9986 // Dispatched behavior.
9987 DECLARE_VERIFIER(AccessorInfo)
9989 // Append all descriptors to the array that are not already there.
9990 // Return number added.
9991 static int AppendUnique(Handle<Object> descriptors,
9992 Handle<FixedArray> array,
9993 int valid_descriptors);
9995 static const int kNameOffset = HeapObject::kHeaderSize;
9996 static const int kFlagOffset = kNameOffset + kPointerSize;
9997 static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
9998 static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
10001 inline bool HasExpectedReceiverType() {
10002 return expected_receiver_type()->IsFunctionTemplateInfo();
10004 // Bit positions in flag.
10005 static const int kAllCanReadBit = 0;
10006 static const int kAllCanWriteBit = 1;
10007 static const int kSpecialDataProperty = 2;
10008 class AttributesField : public BitField<PropertyAttributes, 3, 3> {};
10010 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
10014 // An accessor must have a getter, but can have no setter.
10016 // When setting a property, V8 searches accessors in prototypes.
10017 // If an accessor was found and it does not have a setter,
10018 // the request is ignored.
10020 // If the accessor in the prototype has the READ_ONLY property attribute, then
10021 // a new value is added to the derived object when the property is set.
10022 // This shadows the accessor in the prototype.
10023 class ExecutableAccessorInfo: public AccessorInfo {
10025 DECL_ACCESSORS(getter, Object)
10026 DECL_ACCESSORS(setter, Object)
10027 DECL_ACCESSORS(data, Object)
10029 DECLARE_CAST(ExecutableAccessorInfo)
10031 // Dispatched behavior.
10032 DECLARE_PRINTER(ExecutableAccessorInfo)
10033 DECLARE_VERIFIER(ExecutableAccessorInfo)
10035 static const int kGetterOffset = AccessorInfo::kSize;
10036 static const int kSetterOffset = kGetterOffset + kPointerSize;
10037 static const int kDataOffset = kSetterOffset + kPointerSize;
10038 static const int kSize = kDataOffset + kPointerSize;
10040 static void ClearSetter(Handle<ExecutableAccessorInfo> info);
10043 DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
10047 // Support for JavaScript accessors: A pair of a getter and a setter. Each
10048 // accessor can either be
10049 // * a pointer to a JavaScript function or proxy: a real accessor
10050 // * undefined: considered an accessor by the spec, too, strangely enough
10051 // * the hole: an accessor which has not been set
10052 // * a pointer to a map: a transition used to ensure map sharing
10053 class AccessorPair: public Struct {
10055 DECL_ACCESSORS(getter, Object)
10056 DECL_ACCESSORS(setter, Object)
10058 DECLARE_CAST(AccessorPair)
10060 static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
10062 Object* get(AccessorComponent component) {
10063 return component == ACCESSOR_GETTER ? getter() : setter();
10066 void set(AccessorComponent component, Object* value) {
10067 if (component == ACCESSOR_GETTER) {
10074 // Note: Returns undefined instead in case of a hole.
10075 Object* GetComponent(AccessorComponent component);
10077 // Set both components, skipping arguments which are a JavaScript null.
10078 void SetComponents(Object* getter, Object* setter) {
10079 if (!getter->IsNull()) set_getter(getter);
10080 if (!setter->IsNull()) set_setter(setter);
10083 bool Equals(AccessorPair* pair) {
10084 return (this == pair) || pair->Equals(getter(), setter());
10087 bool Equals(Object* getter_value, Object* setter_value) {
10088 return (getter() == getter_value) && (setter() == setter_value);
10091 bool ContainsAccessor() {
10092 return IsJSAccessor(getter()) || IsJSAccessor(setter());
10095 // Dispatched behavior.
10096 DECLARE_PRINTER(AccessorPair)
10097 DECLARE_VERIFIER(AccessorPair)
10099 static const int kGetterOffset = HeapObject::kHeaderSize;
10100 static const int kSetterOffset = kGetterOffset + kPointerSize;
10101 static const int kSize = kSetterOffset + kPointerSize;
10104 // Strangely enough, in addition to functions and harmony proxies, the spec
10105 // requires us to consider undefined as a kind of accessor, too:
10107 // Object.defineProperty(obj, "foo", {get: undefined});
10108 // assertTrue("foo" in obj);
10109 bool IsJSAccessor(Object* obj) {
10110 return obj->IsSpecFunction() || obj->IsUndefined();
10113 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
10117 class AccessCheckInfo: public Struct {
10119 DECL_ACCESSORS(named_callback, Object)
10120 DECL_ACCESSORS(indexed_callback, Object)
10121 DECL_ACCESSORS(data, Object)
10123 DECLARE_CAST(AccessCheckInfo)
10125 // Dispatched behavior.
10126 DECLARE_PRINTER(AccessCheckInfo)
10127 DECLARE_VERIFIER(AccessCheckInfo)
10129 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
10130 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
10131 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
10132 static const int kSize = kDataOffset + kPointerSize;
10135 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
10139 class InterceptorInfo: public Struct {
10141 DECL_ACCESSORS(getter, Object)
10142 DECL_ACCESSORS(setter, Object)
10143 DECL_ACCESSORS(query, Object)
10144 DECL_ACCESSORS(deleter, Object)
10145 DECL_ACCESSORS(enumerator, Object)
10146 DECL_ACCESSORS(data, Object)
10147 DECL_BOOLEAN_ACCESSORS(can_intercept_symbols)
10148 DECL_BOOLEAN_ACCESSORS(all_can_read)
10149 DECL_BOOLEAN_ACCESSORS(non_masking)
10151 inline int flags() const;
10152 inline void set_flags(int flags);
10154 DECLARE_CAST(InterceptorInfo)
10156 // Dispatched behavior.
10157 DECLARE_PRINTER(InterceptorInfo)
10158 DECLARE_VERIFIER(InterceptorInfo)
10160 static const int kGetterOffset = HeapObject::kHeaderSize;
10161 static const int kSetterOffset = kGetterOffset + kPointerSize;
10162 static const int kQueryOffset = kSetterOffset + kPointerSize;
10163 static const int kDeleterOffset = kQueryOffset + kPointerSize;
10164 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
10165 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
10166 static const int kFlagsOffset = kDataOffset + kPointerSize;
10167 static const int kSize = kFlagsOffset + kPointerSize;
10169 static const int kCanInterceptSymbolsBit = 0;
10170 static const int kAllCanReadBit = 1;
10171 static const int kNonMasking = 2;
10174 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
10178 class CallHandlerInfo: public Struct {
10180 DECL_ACCESSORS(callback, Object)
10181 DECL_ACCESSORS(data, Object)
10183 DECLARE_CAST(CallHandlerInfo)
10185 // Dispatched behavior.
10186 DECLARE_PRINTER(CallHandlerInfo)
10187 DECLARE_VERIFIER(CallHandlerInfo)
10189 static const int kCallbackOffset = HeapObject::kHeaderSize;
10190 static const int kDataOffset = kCallbackOffset + kPointerSize;
10191 static const int kSize = kDataOffset + kPointerSize;
10194 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
10198 class TemplateInfo: public Struct {
10200 DECL_ACCESSORS(tag, Object)
10201 inline int number_of_properties() const;
10202 inline void set_number_of_properties(int value);
10203 DECL_ACCESSORS(property_list, Object)
10204 DECL_ACCESSORS(property_accessors, Object)
10206 DECLARE_VERIFIER(TemplateInfo)
10208 static const int kTagOffset = HeapObject::kHeaderSize;
10209 static const int kNumberOfProperties = kTagOffset + kPointerSize;
10210 static const int kPropertyListOffset = kNumberOfProperties + kPointerSize;
10211 static const int kPropertyAccessorsOffset =
10212 kPropertyListOffset + kPointerSize;
10213 static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
10216 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
10220 class FunctionTemplateInfo: public TemplateInfo {
10222 DECL_ACCESSORS(serial_number, Object)
10223 DECL_ACCESSORS(call_code, Object)
10224 DECL_ACCESSORS(prototype_template, Object)
10225 DECL_ACCESSORS(parent_template, Object)
10226 DECL_ACCESSORS(named_property_handler, Object)
10227 DECL_ACCESSORS(indexed_property_handler, Object)
10228 DECL_ACCESSORS(instance_template, Object)
10229 DECL_ACCESSORS(class_name, Object)
10230 DECL_ACCESSORS(signature, Object)
10231 DECL_ACCESSORS(instance_call_handler, Object)
10232 DECL_ACCESSORS(access_check_info, Object)
10233 DECL_ACCESSORS(flag, Smi)
10235 inline int length() const;
10236 inline void set_length(int value);
10238 // Following properties use flag bits.
10239 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
10240 DECL_BOOLEAN_ACCESSORS(undetectable)
10241 // If the bit is set, object instances created by this function
10242 // requires access check.
10243 DECL_BOOLEAN_ACCESSORS(needs_access_check)
10244 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
10245 DECL_BOOLEAN_ACCESSORS(remove_prototype)
10246 DECL_BOOLEAN_ACCESSORS(do_not_cache)
10247 DECL_BOOLEAN_ACCESSORS(instantiated)
10248 DECL_BOOLEAN_ACCESSORS(accept_any_receiver)
10250 DECLARE_CAST(FunctionTemplateInfo)
10252 // Dispatched behavior.
10253 DECLARE_PRINTER(FunctionTemplateInfo)
10254 DECLARE_VERIFIER(FunctionTemplateInfo)
10256 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
10257 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
10258 static const int kPrototypeTemplateOffset =
10259 kCallCodeOffset + kPointerSize;
10260 static const int kParentTemplateOffset =
10261 kPrototypeTemplateOffset + kPointerSize;
10262 static const int kNamedPropertyHandlerOffset =
10263 kParentTemplateOffset + kPointerSize;
10264 static const int kIndexedPropertyHandlerOffset =
10265 kNamedPropertyHandlerOffset + kPointerSize;
10266 static const int kInstanceTemplateOffset =
10267 kIndexedPropertyHandlerOffset + kPointerSize;
10268 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
10269 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
10270 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
10271 static const int kAccessCheckInfoOffset =
10272 kInstanceCallHandlerOffset + kPointerSize;
10273 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
10274 static const int kLengthOffset = kFlagOffset + kPointerSize;
10275 static const int kSize = kLengthOffset + kPointerSize;
10277 // Returns true if |object| is an instance of this function template.
10278 bool IsTemplateFor(Object* object);
10279 bool IsTemplateFor(Map* map);
10281 // Returns the holder JSObject if the function can legally be called with this
10282 // receiver. Returns Heap::null_value() if the call is illegal.
10283 Object* GetCompatibleReceiver(Isolate* isolate, Object* receiver);
10286 // Bit position in the flag, from least significant bit position.
10287 static const int kHiddenPrototypeBit = 0;
10288 static const int kUndetectableBit = 1;
10289 static const int kNeedsAccessCheckBit = 2;
10290 static const int kReadOnlyPrototypeBit = 3;
10291 static const int kRemovePrototypeBit = 4;
10292 static const int kDoNotCacheBit = 5;
10293 static const int kInstantiatedBit = 6;
10294 static const int kAcceptAnyReceiver = 7;
10296 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
10300 class ObjectTemplateInfo: public TemplateInfo {
10302 DECL_ACCESSORS(constructor, Object)
10303 DECL_ACCESSORS(internal_field_count, Object)
10305 DECLARE_CAST(ObjectTemplateInfo)
10307 // Dispatched behavior.
10308 DECLARE_PRINTER(ObjectTemplateInfo)
10309 DECLARE_VERIFIER(ObjectTemplateInfo)
10311 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10312 static const int kInternalFieldCountOffset =
10313 kConstructorOffset + kPointerSize;
10314 static const int kSize = kInternalFieldCountOffset + kPointerSize;
10318 class TypeSwitchInfo: public Struct {
10320 DECL_ACCESSORS(types, Object)
10322 DECLARE_CAST(TypeSwitchInfo)
10324 // Dispatched behavior.
10325 DECLARE_PRINTER(TypeSwitchInfo)
10326 DECLARE_VERIFIER(TypeSwitchInfo)
10328 static const int kTypesOffset = Struct::kHeaderSize;
10329 static const int kSize = kTypesOffset + kPointerSize;
10333 // The DebugInfo class holds additional information for a function being
10335 class DebugInfo: public Struct {
10337 // The shared function info for the source being debugged.
10338 DECL_ACCESSORS(shared, SharedFunctionInfo)
10339 // Code object for the patched code. This code object is the code object
10340 // currently active for the function.
10341 DECL_ACCESSORS(code, Code)
10342 // Fixed array holding status information for each active break point.
10343 DECL_ACCESSORS(break_points, FixedArray)
10345 // Check if there is a break point at a code position.
10346 bool HasBreakPoint(int code_position);
10347 // Get the break point info object for a code position.
10348 Object* GetBreakPointInfo(int code_position);
10349 // Clear a break point.
10350 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
10352 Handle<Object> break_point_object);
10353 // Set a break point.
10354 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
10355 int source_position, int statement_position,
10356 Handle<Object> break_point_object);
10357 // Get the break point objects for a code position.
10358 Handle<Object> GetBreakPointObjects(int code_position);
10359 // Find the break point info holding this break point object.
10360 static Handle<Object> FindBreakPointInfo(Handle<DebugInfo> debug_info,
10361 Handle<Object> break_point_object);
10362 // Get the number of break points for this function.
10363 int GetBreakPointCount();
10365 DECLARE_CAST(DebugInfo)
10367 // Dispatched behavior.
10368 DECLARE_PRINTER(DebugInfo)
10369 DECLARE_VERIFIER(DebugInfo)
10371 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
10372 static const int kCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
10373 static const int kBreakPointsStateIndex = kCodeIndex + kPointerSize;
10374 static const int kSize = kBreakPointsStateIndex + kPointerSize;
10376 static const int kEstimatedNofBreakPointsInFunction = 16;
10379 static const int kNoBreakPointInfo = -1;
10381 // Lookup the index in the break_points array for a code position.
10382 int GetBreakPointInfoIndex(int code_position);
10384 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
10388 // The BreakPointInfo class holds information for break points set in a
10389 // function. The DebugInfo object holds a BreakPointInfo object for each code
10390 // position with one or more break points.
10391 class BreakPointInfo: public Struct {
10393 // The position in the code for the break point.
10394 DECL_ACCESSORS(code_position, Smi)
10395 // The position in the source for the break position.
10396 DECL_ACCESSORS(source_position, Smi)
10397 // The position in the source for the last statement before this break
10399 DECL_ACCESSORS(statement_position, Smi)
10400 // List of related JavaScript break points.
10401 DECL_ACCESSORS(break_point_objects, Object)
10403 // Removes a break point.
10404 static void ClearBreakPoint(Handle<BreakPointInfo> info,
10405 Handle<Object> break_point_object);
10406 // Set a break point.
10407 static void SetBreakPoint(Handle<BreakPointInfo> info,
10408 Handle<Object> break_point_object);
10409 // Check if break point info has this break point object.
10410 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
10411 Handle<Object> break_point_object);
10412 // Get the number of break points for this code position.
10413 int GetBreakPointCount();
10415 DECLARE_CAST(BreakPointInfo)
10417 // Dispatched behavior.
10418 DECLARE_PRINTER(BreakPointInfo)
10419 DECLARE_VERIFIER(BreakPointInfo)
10421 static const int kCodePositionIndex = Struct::kHeaderSize;
10422 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
10423 static const int kStatementPositionIndex =
10424 kSourcePositionIndex + kPointerSize;
10425 static const int kBreakPointObjectsIndex =
10426 kStatementPositionIndex + kPointerSize;
10427 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
10430 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
10434 #undef DECL_BOOLEAN_ACCESSORS
10435 #undef DECL_ACCESSORS
10436 #undef DECLARE_CAST
10437 #undef DECLARE_VERIFIER
10439 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
10440 V(kStringTable, "string_table", "(Internalized strings)") \
10441 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
10442 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
10443 V(kSmiRootList, "smi_root_list", "(Smi roots)") \
10444 V(kInternalizedString, "internalized_string", "(Internal string)") \
10445 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
10446 V(kTop, "top", "(Isolate)") \
10447 V(kRelocatable, "relocatable", "(Relocatable)") \
10448 V(kDebug, "debug", "(Debugger)") \
10449 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
10450 V(kHandleScope, "handlescope", "(Handle scope)") \
10451 V(kBuiltins, "builtins", "(Builtins)") \
10452 V(kGlobalHandles, "globalhandles", "(Global handles)") \
10453 V(kEternalHandles, "eternalhandles", "(Eternal handles)") \
10454 V(kThreadManager, "threadmanager", "(Thread manager)") \
10455 V(kStrongRoots, "strong roots", "(Strong roots)") \
10456 V(kExtensions, "Extensions", "(Extensions)")
10458 class VisitorSynchronization : public AllStatic {
10460 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
10462 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
10465 #undef DECLARE_ENUM
10467 static const char* const kTags[kNumberOfSyncTags];
10468 static const char* const kTagNames[kNumberOfSyncTags];
10471 // Abstract base class for visiting, and optionally modifying, the
10472 // pointers contained in Objects. Used in GC and serialization/deserialization.
10473 class ObjectVisitor BASE_EMBEDDED {
10475 virtual ~ObjectVisitor() {}
10477 // Visits a contiguous arrays of pointers in the half-open range
10478 // [start, end). Any or all of the values may be modified on return.
10479 virtual void VisitPointers(Object** start, Object** end) = 0;
10481 // Handy shorthand for visiting a single pointer.
10482 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
10484 // Visit weak next_code_link in Code object.
10485 virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
10487 // To allow lazy clearing of inline caches the visitor has
10488 // a rich interface for iterating over Code objects..
10490 // Visits a code target in the instruction stream.
10491 virtual void VisitCodeTarget(RelocInfo* rinfo);
10493 // Visits a code entry in a JS function.
10494 virtual void VisitCodeEntry(Address entry_address);
10496 // Visits a global property cell reference in the instruction stream.
10497 virtual void VisitCell(RelocInfo* rinfo);
10499 // Visits a runtime entry in the instruction stream.
10500 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
10502 // Visits the resource of an one-byte or two-byte string.
10503 virtual void VisitExternalOneByteString(
10504 v8::String::ExternalOneByteStringResource** resource) {}
10505 virtual void VisitExternalTwoByteString(
10506 v8::String::ExternalStringResource** resource) {}
10508 // Visits a debug call target in the instruction stream.
10509 virtual void VisitDebugTarget(RelocInfo* rinfo);
10511 // Visits the byte sequence in a function's prologue that contains information
10512 // about the code's age.
10513 virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
10515 // Visit pointer embedded into a code object.
10516 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
10518 // Visits an external reference embedded into a code object.
10519 virtual void VisitExternalReference(RelocInfo* rinfo);
10521 // Visits an external reference.
10522 virtual void VisitExternalReference(Address* p) {}
10524 // Visits an (encoded) internal reference.
10525 virtual void VisitInternalReference(RelocInfo* rinfo) {}
10527 // Visits a handle that has an embedder-assigned class ID.
10528 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
10530 // Intended for serialization/deserialization checking: insert, or
10531 // check for the presence of, a tag at this position in the stream.
10532 // Also used for marking up GC roots in heap snapshots.
10533 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
10537 class StructBodyDescriptor : public
10538 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
10540 static inline int SizeOf(Map* map, HeapObject* object) {
10541 return map->instance_size();
10546 // BooleanBit is a helper class for setting and getting a bit in an
10548 class BooleanBit : public AllStatic {
10550 static inline bool get(Smi* smi, int bit_position) {
10551 return get(smi->value(), bit_position);
10554 static inline bool get(int value, int bit_position) {
10555 return (value & (1 << bit_position)) != 0;
10558 static inline Smi* set(Smi* smi, int bit_position, bool v) {
10559 return Smi::FromInt(set(smi->value(), bit_position, v));
10562 static inline int set(int value, int bit_position, bool v) {
10564 value |= (1 << bit_position);
10566 value &= ~(1 << bit_position);
10572 } } // namespace v8::internal
10574 #endif // V8_OBJECTS_H_