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
81 // - CompilationCacheTable
82 // - CodeCacheHashTable
88 // - TypeFeedbackVector
89 // - JSFunctionResultCache
92 // - ScriptContextTable
96 // - ExternalUint8ClampedArray
97 // - ExternalInt8Array
98 // - ExternalUint8Array
99 // - ExternalInt16Array
100 // - ExternalUint16Array
101 // - ExternalInt32Array
102 // - ExternalUint32Array
103 // - ExternalFloat32Array
107 // - SeqOneByteString
108 // - SeqTwoByteString
112 // - ExternalOneByteString
113 // - ExternalTwoByteString
114 // - InternalizedString
115 // - SeqInternalizedString
116 // - SeqOneByteInternalizedString
117 // - SeqTwoByteInternalizedString
118 // - ConsInternalizedString
119 // - ExternalInternalizedString
120 // - ExternalOneByteInternalizedString
121 // - ExternalTwoByteInternalizedString
131 // - SharedFunctionInfo
135 // - ExecutableAccessorInfo
141 // - FunctionTemplateInfo
142 // - ObjectTemplateInfo
151 // Formats of Object*:
152 // Smi: [31 bit signed int] 0
153 // HeapObject: [32 bit direct pointer] (4 byte aligned) | 01
158 enum KeyedAccessStoreMode {
160 STORE_TRANSITION_SMI_TO_OBJECT,
161 STORE_TRANSITION_SMI_TO_DOUBLE,
162 STORE_TRANSITION_DOUBLE_TO_OBJECT,
163 STORE_TRANSITION_HOLEY_SMI_TO_OBJECT,
164 STORE_TRANSITION_HOLEY_SMI_TO_DOUBLE,
165 STORE_TRANSITION_HOLEY_DOUBLE_TO_OBJECT,
166 STORE_AND_GROW_NO_TRANSITION,
167 STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT,
168 STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE,
169 STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT,
170 STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_OBJECT,
171 STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_DOUBLE,
172 STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT,
173 STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS,
174 STORE_NO_TRANSITION_HANDLE_COW
178 enum TypeofMode { INSIDE_TYPEOF, NOT_INSIDE_TYPEOF };
187 enum ExternalArrayType {
188 kExternalInt8Array = 1,
191 kExternalUint16Array,
193 kExternalUint32Array,
194 kExternalFloat32Array,
195 kExternalFloat64Array,
196 kExternalUint8ClampedArray,
200 static const int kGrowICDelta = STORE_AND_GROW_NO_TRANSITION -
202 STATIC_ASSERT(STANDARD_STORE == 0);
203 STATIC_ASSERT(kGrowICDelta ==
204 STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT -
205 STORE_TRANSITION_SMI_TO_OBJECT);
206 STATIC_ASSERT(kGrowICDelta ==
207 STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE -
208 STORE_TRANSITION_SMI_TO_DOUBLE);
209 STATIC_ASSERT(kGrowICDelta ==
210 STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT -
211 STORE_TRANSITION_DOUBLE_TO_OBJECT);
214 static inline KeyedAccessStoreMode GetGrowStoreMode(
215 KeyedAccessStoreMode store_mode) {
216 if (store_mode < STORE_AND_GROW_NO_TRANSITION) {
217 store_mode = static_cast<KeyedAccessStoreMode>(
218 static_cast<int>(store_mode) + kGrowICDelta);
224 static inline bool IsTransitionStoreMode(KeyedAccessStoreMode store_mode) {
225 return store_mode > STANDARD_STORE &&
226 store_mode <= STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT &&
227 store_mode != STORE_AND_GROW_NO_TRANSITION;
231 static inline KeyedAccessStoreMode GetNonTransitioningStoreMode(
232 KeyedAccessStoreMode store_mode) {
233 if (store_mode >= STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS) {
236 if (store_mode >= STORE_AND_GROW_NO_TRANSITION) {
237 return STORE_AND_GROW_NO_TRANSITION;
239 return STANDARD_STORE;
243 static inline bool IsGrowStoreMode(KeyedAccessStoreMode store_mode) {
244 return store_mode >= STORE_AND_GROW_NO_TRANSITION &&
245 store_mode <= STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT;
249 enum IcCheckType { ELEMENT, PROPERTY };
252 // SKIP_WRITE_BARRIER skips the write barrier.
253 // UPDATE_WEAK_WRITE_BARRIER skips the marking part of the write barrier and
254 // only performs the generational part.
255 // UPDATE_WRITE_BARRIER is doing the full barrier, marking and generational.
256 enum WriteBarrierMode {
258 UPDATE_WEAK_WRITE_BARRIER,
263 // Indicates whether a value can be loaded as a constant.
264 enum StoreMode { ALLOW_IN_DESCRIPTOR, FORCE_FIELD };
267 // PropertyNormalizationMode is used to specify whether to keep
268 // inobject properties when normalizing properties of a JSObject.
269 enum PropertyNormalizationMode {
270 CLEAR_INOBJECT_PROPERTIES,
271 KEEP_INOBJECT_PROPERTIES
275 // Indicates how aggressively the prototype should be optimized. FAST_PROTOTYPE
276 // will give the fastest result by tailoring the map to the prototype, but that
277 // will cause polymorphism with other objects. REGULAR_PROTOTYPE is to be used
278 // (at least for now) when dynamically modifying the prototype chain of an
279 // object using __proto__ or Object.setPrototypeOf.
280 enum PrototypeOptimizationMode { REGULAR_PROTOTYPE, FAST_PROTOTYPE };
283 // Indicates whether transitions can be added to a source map or not.
284 enum TransitionFlag {
290 // Indicates whether the transition is simple: the target map of the transition
291 // either extends the current map with a new property, or it modifies the
292 // property that was added last to the current map.
293 enum SimpleTransitionFlag {
294 SIMPLE_PROPERTY_TRANSITION,
300 // Indicates whether we are only interested in the descriptors of a particular
301 // map, or in all descriptors in the descriptor array.
302 enum DescriptorFlag {
307 // The GC maintains a bit of information, the MarkingParity, which toggles
308 // from odd to even and back every time marking is completed. Incremental
309 // marking can visit an object twice during a marking phase, so algorithms that
310 // that piggy-back on marking can use the parity to ensure that they only
311 // perform an operation on an object once per marking phase: they record the
312 // MarkingParity when they visit an object, and only re-visit the object when it
313 // is marked again and the MarkingParity changes.
320 // ICs store extra state in a Code object. The default extra state is
322 typedef int ExtraICState;
323 static const ExtraICState kNoExtraICState = 0;
325 // Instance size sentinel for objects of variable size.
326 const int kVariableSizeSentinel = 0;
328 // We may store the unsigned bit field as signed Smi value and do not
330 const int kStubMajorKeyBits = 7;
331 const int kStubMinorKeyBits = kSmiValueSize - kStubMajorKeyBits - 1;
333 // All Maps have a field instance_type containing a InstanceType.
334 // It describes the type of the instances.
336 // As an example, a JavaScript object is a heap object and its map
337 // instance_type is JS_OBJECT_TYPE.
339 // The names of the string instance types are intended to systematically
340 // mirror their encoding in the instance_type field of the map. The default
341 // encoding is considered TWO_BYTE. It is not mentioned in the name. ONE_BYTE
342 // encoding is mentioned explicitly in the name. Likewise, the default
343 // representation is considered sequential. It is not mentioned in the
344 // name. The other representations (e.g. CONS, EXTERNAL) are explicitly
345 // mentioned. Finally, the string is either a STRING_TYPE (if it is a normal
346 // string) or a INTERNALIZED_STRING_TYPE (if it is a internalized string).
348 // NOTE: The following things are some that depend on the string types having
349 // instance_types that are less than those of all other types:
350 // HeapObject::Size, HeapObject::IterateBody, the typeof operator, and
353 // NOTE: Everything following JS_VALUE_TYPE is considered a
354 // JSObject for GC purposes. The first four entries here have typeof
355 // 'object', whereas JS_FUNCTION_TYPE has typeof 'function'.
356 #define INSTANCE_TYPE_LIST(V) \
358 V(ONE_BYTE_STRING_TYPE) \
359 V(CONS_STRING_TYPE) \
360 V(CONS_ONE_BYTE_STRING_TYPE) \
361 V(SLICED_STRING_TYPE) \
362 V(SLICED_ONE_BYTE_STRING_TYPE) \
363 V(EXTERNAL_STRING_TYPE) \
364 V(EXTERNAL_ONE_BYTE_STRING_TYPE) \
365 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
366 V(SHORT_EXTERNAL_STRING_TYPE) \
367 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE) \
368 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
370 V(INTERNALIZED_STRING_TYPE) \
371 V(ONE_BYTE_INTERNALIZED_STRING_TYPE) \
372 V(EXTERNAL_INTERNALIZED_STRING_TYPE) \
373 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
374 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
375 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE) \
376 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
377 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
385 V(PROPERTY_CELL_TYPE) \
387 V(HEAP_NUMBER_TYPE) \
388 V(MUTABLE_HEAP_NUMBER_TYPE) \
393 /* Note: the order of these external array */ \
394 /* types is relied upon in */ \
395 /* Object::IsExternalArray(). */ \
396 V(EXTERNAL_INT8_ARRAY_TYPE) \
397 V(EXTERNAL_UINT8_ARRAY_TYPE) \
398 V(EXTERNAL_INT16_ARRAY_TYPE) \
399 V(EXTERNAL_UINT16_ARRAY_TYPE) \
400 V(EXTERNAL_INT32_ARRAY_TYPE) \
401 V(EXTERNAL_UINT32_ARRAY_TYPE) \
402 V(EXTERNAL_FLOAT32_ARRAY_TYPE) \
403 V(EXTERNAL_FLOAT64_ARRAY_TYPE) \
404 V(EXTERNAL_UINT8_CLAMPED_ARRAY_TYPE) \
406 V(FIXED_INT8_ARRAY_TYPE) \
407 V(FIXED_UINT8_ARRAY_TYPE) \
408 V(FIXED_INT16_ARRAY_TYPE) \
409 V(FIXED_UINT16_ARRAY_TYPE) \
410 V(FIXED_INT32_ARRAY_TYPE) \
411 V(FIXED_UINT32_ARRAY_TYPE) \
412 V(FIXED_FLOAT32_ARRAY_TYPE) \
413 V(FIXED_FLOAT64_ARRAY_TYPE) \
414 V(FIXED_UINT8_CLAMPED_ARRAY_TYPE) \
418 V(DECLARED_ACCESSOR_DESCRIPTOR_TYPE) \
419 V(DECLARED_ACCESSOR_INFO_TYPE) \
420 V(EXECUTABLE_ACCESSOR_INFO_TYPE) \
421 V(ACCESSOR_PAIR_TYPE) \
422 V(ACCESS_CHECK_INFO_TYPE) \
423 V(INTERCEPTOR_INFO_TYPE) \
424 V(CALL_HANDLER_INFO_TYPE) \
425 V(FUNCTION_TEMPLATE_INFO_TYPE) \
426 V(OBJECT_TEMPLATE_INFO_TYPE) \
427 V(SIGNATURE_INFO_TYPE) \
428 V(TYPE_SWITCH_INFO_TYPE) \
429 V(ALLOCATION_MEMENTO_TYPE) \
430 V(ALLOCATION_SITE_TYPE) \
433 V(POLYMORPHIC_CODE_CACHE_TYPE) \
434 V(TYPE_FEEDBACK_INFO_TYPE) \
435 V(ALIASED_ARGUMENTS_ENTRY_TYPE) \
437 V(PROTOTYPE_INFO_TYPE) \
439 V(FIXED_ARRAY_TYPE) \
440 V(FIXED_DOUBLE_ARRAY_TYPE) \
441 V(SHARED_FUNCTION_INFO_TYPE) \
444 V(JS_MESSAGE_OBJECT_TYPE) \
449 V(JS_CONTEXT_EXTENSION_OBJECT_TYPE) \
450 V(JS_GENERATOR_OBJECT_TYPE) \
452 V(JS_GLOBAL_OBJECT_TYPE) \
453 V(JS_BUILTINS_OBJECT_TYPE) \
454 V(JS_GLOBAL_PROXY_TYPE) \
456 V(JS_ARRAY_BUFFER_TYPE) \
457 V(JS_TYPED_ARRAY_TYPE) \
458 V(JS_DATA_VIEW_TYPE) \
462 V(JS_SET_ITERATOR_TYPE) \
463 V(JS_MAP_ITERATOR_TYPE) \
464 V(JS_WEAK_MAP_TYPE) \
465 V(JS_WEAK_SET_TYPE) \
468 V(JS_FUNCTION_TYPE) \
469 V(JS_FUNCTION_PROXY_TYPE) \
471 V(BREAK_POINT_INFO_TYPE)
474 // Since string types are not consecutive, this macro is used to
475 // iterate over them.
476 #define STRING_TYPE_LIST(V) \
477 V(STRING_TYPE, kVariableSizeSentinel, string, String) \
478 V(ONE_BYTE_STRING_TYPE, kVariableSizeSentinel, one_byte_string, \
480 V(CONS_STRING_TYPE, ConsString::kSize, cons_string, ConsString) \
481 V(CONS_ONE_BYTE_STRING_TYPE, ConsString::kSize, cons_one_byte_string, \
483 V(SLICED_STRING_TYPE, SlicedString::kSize, sliced_string, SlicedString) \
484 V(SLICED_ONE_BYTE_STRING_TYPE, SlicedString::kSize, sliced_one_byte_string, \
485 SlicedOneByteString) \
486 V(EXTERNAL_STRING_TYPE, ExternalTwoByteString::kSize, external_string, \
488 V(EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kSize, \
489 external_one_byte_string, ExternalOneByteString) \
490 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, ExternalTwoByteString::kSize, \
491 external_string_with_one_byte_data, ExternalStringWithOneByteData) \
492 V(SHORT_EXTERNAL_STRING_TYPE, ExternalTwoByteString::kShortSize, \
493 short_external_string, ShortExternalString) \
494 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kShortSize, \
495 short_external_one_byte_string, ShortExternalOneByteString) \
496 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, \
497 ExternalTwoByteString::kShortSize, \
498 short_external_string_with_one_byte_data, \
499 ShortExternalStringWithOneByteData) \
501 V(INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, internalized_string, \
502 InternalizedString) \
503 V(ONE_BYTE_INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, \
504 one_byte_internalized_string, OneByteInternalizedString) \
505 V(EXTERNAL_INTERNALIZED_STRING_TYPE, ExternalTwoByteString::kSize, \
506 external_internalized_string, ExternalInternalizedString) \
507 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, ExternalOneByteString::kSize, \
508 external_one_byte_internalized_string, ExternalOneByteInternalizedString) \
509 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
510 ExternalTwoByteString::kSize, \
511 external_internalized_string_with_one_byte_data, \
512 ExternalInternalizedStringWithOneByteData) \
513 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE, \
514 ExternalTwoByteString::kShortSize, short_external_internalized_string, \
515 ShortExternalInternalizedString) \
516 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, \
517 ExternalOneByteString::kShortSize, \
518 short_external_one_byte_internalized_string, \
519 ShortExternalOneByteInternalizedString) \
520 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
521 ExternalTwoByteString::kShortSize, \
522 short_external_internalized_string_with_one_byte_data, \
523 ShortExternalInternalizedStringWithOneByteData)
525 // A struct is a simple object a set of object-valued fields. Including an
526 // object type in this causes the compiler to generate most of the boilerplate
527 // code for the class including allocation and garbage collection routines,
528 // casts and predicates. All you need to define is the class, methods and
529 // object verification routines. Easy, no?
531 // Note that for subtle reasons related to the ordering or numerical values of
532 // type tags, elements in this list have to be added to the INSTANCE_TYPE_LIST
534 #define STRUCT_LIST(V) \
536 V(EXECUTABLE_ACCESSOR_INFO, ExecutableAccessorInfo, \
537 executable_accessor_info) \
538 V(ACCESSOR_PAIR, AccessorPair, accessor_pair) \
539 V(ACCESS_CHECK_INFO, AccessCheckInfo, access_check_info) \
540 V(INTERCEPTOR_INFO, InterceptorInfo, interceptor_info) \
541 V(CALL_HANDLER_INFO, CallHandlerInfo, call_handler_info) \
542 V(FUNCTION_TEMPLATE_INFO, FunctionTemplateInfo, function_template_info) \
543 V(OBJECT_TEMPLATE_INFO, ObjectTemplateInfo, object_template_info) \
544 V(TYPE_SWITCH_INFO, TypeSwitchInfo, type_switch_info) \
545 V(SCRIPT, Script, script) \
546 V(ALLOCATION_SITE, AllocationSite, allocation_site) \
547 V(ALLOCATION_MEMENTO, AllocationMemento, allocation_memento) \
548 V(CODE_CACHE, CodeCache, code_cache) \
549 V(POLYMORPHIC_CODE_CACHE, PolymorphicCodeCache, polymorphic_code_cache) \
550 V(TYPE_FEEDBACK_INFO, TypeFeedbackInfo, type_feedback_info) \
551 V(ALIASED_ARGUMENTS_ENTRY, AliasedArgumentsEntry, aliased_arguments_entry) \
552 V(DEBUG_INFO, DebugInfo, debug_info) \
553 V(BREAK_POINT_INFO, BreakPointInfo, break_point_info) \
554 V(PROTOTYPE_INFO, PrototypeInfo, prototype_info)
556 // We use the full 8 bits of the instance_type field to encode heap object
557 // instance types. The high-order bit (bit 7) is set if the object is not a
558 // string, and cleared if it is a string.
559 const uint32_t kIsNotStringMask = 0x80;
560 const uint32_t kStringTag = 0x0;
561 const uint32_t kNotStringTag = 0x80;
563 // Bit 6 indicates that the object is an internalized string (if set) or not.
564 // Bit 7 has to be clear as well.
565 const uint32_t kIsNotInternalizedMask = 0x40;
566 const uint32_t kNotInternalizedTag = 0x40;
567 const uint32_t kInternalizedTag = 0x0;
569 // If bit 7 is clear then bit 2 indicates whether the string consists of
570 // two-byte characters or one-byte characters.
571 const uint32_t kStringEncodingMask = 0x4;
572 const uint32_t kTwoByteStringTag = 0x0;
573 const uint32_t kOneByteStringTag = 0x4;
575 // If bit 7 is clear, the low-order 2 bits indicate the representation
577 const uint32_t kStringRepresentationMask = 0x03;
578 enum StringRepresentationTag {
580 kConsStringTag = 0x1,
581 kExternalStringTag = 0x2,
582 kSlicedStringTag = 0x3
584 const uint32_t kIsIndirectStringMask = 0x1;
585 const uint32_t kIsIndirectStringTag = 0x1;
586 STATIC_ASSERT((kSeqStringTag & kIsIndirectStringMask) == 0); // NOLINT
587 STATIC_ASSERT((kExternalStringTag & kIsIndirectStringMask) == 0); // NOLINT
588 STATIC_ASSERT((kConsStringTag &
589 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
590 STATIC_ASSERT((kSlicedStringTag &
591 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
593 // Use this mask to distinguish between cons and slice only after making
594 // sure that the string is one of the two (an indirect string).
595 const uint32_t kSlicedNotConsMask = kSlicedStringTag & ~kConsStringTag;
596 STATIC_ASSERT(IS_POWER_OF_TWO(kSlicedNotConsMask));
598 // If bit 7 is clear, then bit 3 indicates whether this two-byte
599 // string actually contains one byte data.
600 const uint32_t kOneByteDataHintMask = 0x08;
601 const uint32_t kOneByteDataHintTag = 0x08;
603 // If bit 7 is clear and string representation indicates an external string,
604 // then bit 4 indicates whether the data pointer is cached.
605 const uint32_t kShortExternalStringMask = 0x10;
606 const uint32_t kShortExternalStringTag = 0x10;
609 // A ConsString with an empty string as the right side is a candidate
610 // for being shortcut by the garbage collector. We don't allocate any
611 // non-flat internalized strings, so we do not shortcut them thereby
612 // avoiding turning internalized strings into strings. The bit-masks
613 // below contain the internalized bit as additional safety.
614 // See heap.cc, mark-compact.cc and objects-visiting.cc.
615 const uint32_t kShortcutTypeMask =
617 kIsNotInternalizedMask |
618 kStringRepresentationMask;
619 const uint32_t kShortcutTypeTag = kConsStringTag | kNotInternalizedTag;
621 static inline bool IsShortcutCandidate(int type) {
622 return ((type & kShortcutTypeMask) == kShortcutTypeTag);
628 INTERNALIZED_STRING_TYPE =
629 kTwoByteStringTag | kSeqStringTag | kInternalizedTag,
630 ONE_BYTE_INTERNALIZED_STRING_TYPE =
631 kOneByteStringTag | kSeqStringTag | kInternalizedTag,
632 EXTERNAL_INTERNALIZED_STRING_TYPE =
633 kTwoByteStringTag | kExternalStringTag | kInternalizedTag,
634 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
635 kOneByteStringTag | kExternalStringTag | kInternalizedTag,
636 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
637 EXTERNAL_INTERNALIZED_STRING_TYPE | kOneByteDataHintTag |
639 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE = EXTERNAL_INTERNALIZED_STRING_TYPE |
640 kShortExternalStringTag |
642 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
643 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kShortExternalStringTag |
645 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
646 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
647 kShortExternalStringTag | kInternalizedTag,
648 STRING_TYPE = INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
649 ONE_BYTE_STRING_TYPE =
650 ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
651 CONS_STRING_TYPE = kTwoByteStringTag | kConsStringTag | kNotInternalizedTag,
652 CONS_ONE_BYTE_STRING_TYPE =
653 kOneByteStringTag | kConsStringTag | kNotInternalizedTag,
655 kTwoByteStringTag | kSlicedStringTag | kNotInternalizedTag,
656 SLICED_ONE_BYTE_STRING_TYPE =
657 kOneByteStringTag | kSlicedStringTag | kNotInternalizedTag,
658 EXTERNAL_STRING_TYPE =
659 EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
660 EXTERNAL_ONE_BYTE_STRING_TYPE =
661 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
662 EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
663 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
665 SHORT_EXTERNAL_STRING_TYPE =
666 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
667 SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE =
668 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
669 SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
670 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
674 SYMBOL_TYPE = kNotStringTag, // FIRST_NONSTRING_TYPE, LAST_NAME_TYPE
676 // Objects allocated in their own spaces (never in new space).
681 // "Data", objects that cannot contain non-map-word pointers to heap
684 MUTABLE_HEAP_NUMBER_TYPE,
685 FLOAT32X4_TYPE, // FIRST_SIMD_TYPE, LAST_SIMD_TYPE
689 EXTERNAL_INT8_ARRAY_TYPE, // FIRST_EXTERNAL_ARRAY_TYPE
690 EXTERNAL_UINT8_ARRAY_TYPE,
691 EXTERNAL_INT16_ARRAY_TYPE,
692 EXTERNAL_UINT16_ARRAY_TYPE,
693 EXTERNAL_INT32_ARRAY_TYPE,
694 EXTERNAL_UINT32_ARRAY_TYPE,
695 EXTERNAL_FLOAT32_ARRAY_TYPE,
696 EXTERNAL_FLOAT64_ARRAY_TYPE,
697 EXTERNAL_UINT8_CLAMPED_ARRAY_TYPE, // LAST_EXTERNAL_ARRAY_TYPE
698 FIXED_INT8_ARRAY_TYPE, // FIRST_FIXED_TYPED_ARRAY_TYPE
699 FIXED_UINT8_ARRAY_TYPE,
700 FIXED_INT16_ARRAY_TYPE,
701 FIXED_UINT16_ARRAY_TYPE,
702 FIXED_INT32_ARRAY_TYPE,
703 FIXED_UINT32_ARRAY_TYPE,
704 FIXED_FLOAT32_ARRAY_TYPE,
705 FIXED_FLOAT64_ARRAY_TYPE,
706 FIXED_UINT8_CLAMPED_ARRAY_TYPE, // LAST_FIXED_TYPED_ARRAY_TYPE
707 FIXED_DOUBLE_ARRAY_TYPE,
708 FILLER_TYPE, // LAST_DATA_TYPE
711 DECLARED_ACCESSOR_DESCRIPTOR_TYPE,
712 DECLARED_ACCESSOR_INFO_TYPE,
713 EXECUTABLE_ACCESSOR_INFO_TYPE,
715 ACCESS_CHECK_INFO_TYPE,
716 INTERCEPTOR_INFO_TYPE,
717 CALL_HANDLER_INFO_TYPE,
718 FUNCTION_TEMPLATE_INFO_TYPE,
719 OBJECT_TEMPLATE_INFO_TYPE,
721 TYPE_SWITCH_INFO_TYPE,
722 ALLOCATION_SITE_TYPE,
723 ALLOCATION_MEMENTO_TYPE,
726 POLYMORPHIC_CODE_CACHE_TYPE,
727 TYPE_FEEDBACK_INFO_TYPE,
728 ALIASED_ARGUMENTS_ENTRY_TYPE,
731 BREAK_POINT_INFO_TYPE,
733 SHARED_FUNCTION_INFO_TYPE,
739 // All the following types are subtypes of JSReceiver, which corresponds to
740 // objects in the JS sense. The first and the last type in this range are
741 // the two forms of function. This organization enables using the same
742 // compares for checking the JS_RECEIVER/SPEC_OBJECT range and the
743 // NONCALLABLE_JS_OBJECT range.
744 JS_FUNCTION_PROXY_TYPE, // FIRST_JS_RECEIVER_TYPE, FIRST_JS_PROXY_TYPE
745 JS_PROXY_TYPE, // LAST_JS_PROXY_TYPE
746 JS_VALUE_TYPE, // FIRST_JS_OBJECT_TYPE
747 JS_MESSAGE_OBJECT_TYPE,
750 JS_CONTEXT_EXTENSION_OBJECT_TYPE,
751 JS_GENERATOR_OBJECT_TYPE,
753 JS_GLOBAL_OBJECT_TYPE,
754 JS_BUILTINS_OBJECT_TYPE,
755 JS_GLOBAL_PROXY_TYPE,
757 JS_ARRAY_BUFFER_TYPE,
762 JS_SET_ITERATOR_TYPE,
763 JS_MAP_ITERATOR_TYPE,
767 JS_FUNCTION_TYPE, // LAST_JS_OBJECT_TYPE, LAST_JS_RECEIVER_TYPE
771 LAST_TYPE = JS_FUNCTION_TYPE,
772 FIRST_NAME_TYPE = FIRST_TYPE,
773 LAST_NAME_TYPE = SYMBOL_TYPE,
774 FIRST_UNIQUE_NAME_TYPE = INTERNALIZED_STRING_TYPE,
775 LAST_UNIQUE_NAME_TYPE = SYMBOL_TYPE,
776 FIRST_NONSTRING_TYPE = SYMBOL_TYPE,
777 // Boundaries for testing for a SIMD type.
778 FIRST_SIMD_TYPE = FLOAT32X4_TYPE,
779 LAST_SIMD_TYPE = FLOAT32X4_TYPE,
780 // Boundaries for testing for an external array.
781 FIRST_EXTERNAL_ARRAY_TYPE = EXTERNAL_INT8_ARRAY_TYPE,
782 LAST_EXTERNAL_ARRAY_TYPE = EXTERNAL_UINT8_CLAMPED_ARRAY_TYPE,
783 // Boundaries for testing for a fixed typed array.
784 FIRST_FIXED_TYPED_ARRAY_TYPE = FIXED_INT8_ARRAY_TYPE,
785 LAST_FIXED_TYPED_ARRAY_TYPE = FIXED_UINT8_CLAMPED_ARRAY_TYPE,
786 // Boundary for promotion to old space.
787 LAST_DATA_TYPE = FILLER_TYPE,
788 // Boundary for objects represented as JSReceiver (i.e. JSObject or JSProxy).
789 // Note that there is no range for JSObject or JSProxy, since their subtypes
790 // are not continuous in this enum! The enum ranges instead reflect the
791 // external class names, where proxies are treated as either ordinary objects,
793 FIRST_JS_RECEIVER_TYPE = JS_FUNCTION_PROXY_TYPE,
794 LAST_JS_RECEIVER_TYPE = LAST_TYPE,
795 // Boundaries for testing the types represented as JSObject
796 FIRST_JS_OBJECT_TYPE = JS_VALUE_TYPE,
797 LAST_JS_OBJECT_TYPE = LAST_TYPE,
798 // Boundaries for testing the types represented as JSProxy
799 FIRST_JS_PROXY_TYPE = JS_FUNCTION_PROXY_TYPE,
800 LAST_JS_PROXY_TYPE = JS_PROXY_TYPE,
801 // Boundaries for testing whether the type is a JavaScript object.
802 FIRST_SPEC_OBJECT_TYPE = FIRST_JS_RECEIVER_TYPE,
803 LAST_SPEC_OBJECT_TYPE = LAST_JS_RECEIVER_TYPE,
804 // Boundaries for testing the types for which typeof is "object".
805 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_PROXY_TYPE,
806 LAST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_REGEXP_TYPE,
807 // Note that the types for which typeof is "function" are not continuous.
808 // Define this so that we can put assertions on discrete checks.
809 NUM_OF_CALLABLE_SPEC_OBJECT_TYPES = 2
812 const int kExternalArrayTypeCount =
813 LAST_EXTERNAL_ARRAY_TYPE - FIRST_EXTERNAL_ARRAY_TYPE + 1;
815 STATIC_ASSERT(JS_OBJECT_TYPE == Internals::kJSObjectType);
816 STATIC_ASSERT(FIRST_NONSTRING_TYPE == Internals::kFirstNonstringType);
817 STATIC_ASSERT(ODDBALL_TYPE == Internals::kOddballType);
818 STATIC_ASSERT(FOREIGN_TYPE == Internals::kForeignType);
821 #define FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(V) \
822 V(FAST_ELEMENTS_SUB_TYPE) \
823 V(DICTIONARY_ELEMENTS_SUB_TYPE) \
824 V(FAST_PROPERTIES_SUB_TYPE) \
825 V(DICTIONARY_PROPERTIES_SUB_TYPE) \
826 V(MAP_CODE_CACHE_SUB_TYPE) \
827 V(SCOPE_INFO_SUB_TYPE) \
828 V(STRING_TABLE_SUB_TYPE) \
829 V(DESCRIPTOR_ARRAY_SUB_TYPE) \
830 V(TRANSITION_ARRAY_SUB_TYPE)
832 enum FixedArraySubInstanceType {
833 #define DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE(name) name,
834 FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE)
835 #undef DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE
836 LAST_FIXED_ARRAY_SUB_TYPE = TRANSITION_ARRAY_SUB_TYPE
849 #define DECL_BOOLEAN_ACCESSORS(name) \
850 inline bool name() const; \
851 inline void set_##name(bool value); \
854 #define DECL_ACCESSORS(name, type) \
855 inline type* name() const; \
856 inline void set_##name(type* value, \
857 WriteBarrierMode mode = UPDATE_WRITE_BARRIER); \
860 #define DECLARE_CAST(type) \
861 INLINE(static type* cast(Object* object)); \
862 INLINE(static const type* cast(const Object* object));
866 class AllocationSite;
867 class AllocationSiteCreationContext;
868 class AllocationSiteUsageContext;
871 class ElementsAccessor;
872 class FixedArrayBase;
873 class FunctionLiteral;
875 class JSBuiltinsObject;
876 class LayoutDescriptor;
877 class LookupIterator;
878 class ObjectHashTable;
881 class SafepointEntry;
882 class SharedFunctionInfo;
884 class TypeFeedbackInfo;
885 class TypeFeedbackVector;
888 // We cannot just say "class HeapType;" if it is created from a template... =8-?
889 template<class> class TypeImpl;
890 struct HeapTypeConfig;
891 typedef TypeImpl<HeapTypeConfig> HeapType;
894 // A template-ized version of the IsXXX functions.
895 template <class C> inline bool Is(Object* obj);
898 #define DECLARE_VERIFIER(Name) void Name##Verify();
900 #define DECLARE_VERIFIER(Name)
904 #define DECLARE_PRINTER(Name) void Name##Print(std::ostream& os); // NOLINT
906 #define DECLARE_PRINTER(Name)
910 #define OBJECT_TYPE_LIST(V) \
915 #define HEAP_OBJECT_TYPE_LIST(V) \
917 V(MutableHeapNumber) \
925 V(ExternalTwoByteString) \
926 V(ExternalOneByteString) \
927 V(SeqTwoByteString) \
928 V(SeqOneByteString) \
929 V(InternalizedString) \
933 V(ExternalInt8Array) \
934 V(ExternalUint8Array) \
935 V(ExternalInt16Array) \
936 V(ExternalUint16Array) \
937 V(ExternalInt32Array) \
938 V(ExternalUint32Array) \
939 V(ExternalFloat32Array) \
940 V(ExternalFloat64Array) \
941 V(ExternalUint8ClampedArray) \
942 V(FixedTypedArrayBase) \
945 V(FixedUint16Array) \
947 V(FixedUint32Array) \
949 V(FixedFloat32Array) \
950 V(FixedFloat64Array) \
951 V(FixedUint8ClampedArray) \
957 V(JSContextExtensionObject) \
958 V(JSGeneratorObject) \
960 V(LayoutDescriptor) \
964 V(TypeFeedbackVector) \
965 V(DeoptimizationInputData) \
966 V(DeoptimizationOutputData) \
970 V(FixedDoubleArray) \
974 V(ScriptContextTable) \
980 V(SharedFunctionInfo) \
989 V(JSArrayBufferView) \
998 V(JSWeakCollection) \
1005 V(JSFunctionResultCache) \
1006 V(NormalizedMapCache) \
1007 V(CompilationCacheTable) \
1008 V(CodeCacheHashTable) \
1009 V(PolymorphicCodeCacheHashTable) \
1014 V(JSBuiltinsObject) \
1016 V(UndetectableObject) \
1017 V(AccessCheckNeeded) \
1021 V(ObjectHashTable) \
1023 V(WeakValueHashTable) \
1026 // Object is the abstract superclass for all classes in the
1027 // object hierarchy.
1028 // Object does not use any virtual functions to avoid the
1029 // allocation of the C++ vtable.
1030 // Since both Smi and HeapObject are subclasses of Object no
1031 // data members can be present in Object.
1035 bool IsObject() const { return true; }
1037 #define IS_TYPE_FUNCTION_DECL(type_) INLINE(bool Is##type_() const);
1038 OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1039 HEAP_OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1040 #undef IS_TYPE_FUNCTION_DECL
1042 // A non-keyed store is of the form a.x = foo or a["x"] = foo whereas
1043 // a keyed store is of the form a[expression] = foo.
1044 enum StoreFromKeyed {
1045 MAY_BE_STORE_FROM_KEYED,
1046 CERTAINLY_NOT_STORE_FROM_KEYED
1049 INLINE(bool IsFixedArrayBase() const);
1050 INLINE(bool IsExternal() const);
1051 INLINE(bool IsAccessorInfo() const);
1053 INLINE(bool IsStruct() const);
1054 #define DECLARE_STRUCT_PREDICATE(NAME, Name, name) \
1055 INLINE(bool Is##Name() const);
1056 STRUCT_LIST(DECLARE_STRUCT_PREDICATE)
1057 #undef DECLARE_STRUCT_PREDICATE
1059 INLINE(bool IsSpecObject()) const;
1060 INLINE(bool IsSpecFunction()) const;
1061 INLINE(bool IsTemplateInfo()) const;
1062 INLINE(bool IsNameDictionary() const);
1063 INLINE(bool IsGlobalDictionary() const);
1064 INLINE(bool IsSeededNumberDictionary() const);
1065 INLINE(bool IsUnseededNumberDictionary() const);
1066 INLINE(bool IsOrderedHashSet() const);
1067 INLINE(bool IsOrderedHashMap() const);
1068 bool IsCallable() const;
1069 static bool IsPromise(Handle<Object> object);
1072 INLINE(bool IsUndefined() const);
1073 INLINE(bool IsNull() const);
1074 INLINE(bool IsTheHole() const);
1075 INLINE(bool IsException() const);
1076 INLINE(bool IsUninitialized() const);
1077 INLINE(bool IsTrue() const);
1078 INLINE(bool IsFalse() const);
1079 INLINE(bool IsArgumentsMarker() const);
1081 // Filler objects (fillers and free space objects).
1082 INLINE(bool IsFiller() const);
1084 // Extract the number.
1085 inline double Number();
1086 INLINE(bool IsNaN() const);
1087 INLINE(bool IsMinusZero() const);
1088 bool ToInt32(int32_t* value);
1089 bool ToUint32(uint32_t* value);
1091 inline Representation OptimalRepresentation() {
1092 if (!FLAG_track_fields) return Representation::Tagged();
1094 return Representation::Smi();
1095 } else if (FLAG_track_double_fields && IsHeapNumber()) {
1096 return Representation::Double();
1097 } else if (FLAG_track_computed_fields && IsUninitialized()) {
1098 return Representation::None();
1099 } else if (FLAG_track_heap_object_fields) {
1100 DCHECK(IsHeapObject());
1101 return Representation::HeapObject();
1103 return Representation::Tagged();
1107 inline ElementsKind OptimalElementsKind() {
1108 if (IsSmi()) return FAST_SMI_ELEMENTS;
1109 if (IsNumber()) return FAST_DOUBLE_ELEMENTS;
1110 return FAST_ELEMENTS;
1113 inline bool FitsRepresentation(Representation representation) {
1114 if (FLAG_track_fields && representation.IsNone()) {
1116 } else if (FLAG_track_fields && representation.IsSmi()) {
1118 } else if (FLAG_track_double_fields && representation.IsDouble()) {
1119 return IsMutableHeapNumber() || IsNumber();
1120 } else if (FLAG_track_heap_object_fields && representation.IsHeapObject()) {
1121 return IsHeapObject();
1126 // Checks whether two valid primitive encodings of a property name resolve to
1127 // the same logical property. E.g., the smi 1, the string "1" and the double
1128 // 1 all refer to the same property, so this helper will return true.
1129 inline bool KeyEquals(Object* other);
1131 Handle<HeapType> OptimalType(Isolate* isolate, Representation representation);
1133 inline static Handle<Object> NewStorageFor(Isolate* isolate,
1134 Handle<Object> object,
1135 Representation representation);
1137 inline static Handle<Object> WrapForRead(Isolate* isolate,
1138 Handle<Object> object,
1139 Representation representation);
1141 // Returns true if the object is of the correct type to be used as a
1142 // implementation of a JSObject's elements.
1143 inline bool HasValidElements();
1145 inline bool HasSpecificClassOf(String* name);
1147 bool BooleanValue(); // ECMA-262 9.2.
1149 // Convert to a JSObject if needed.
1150 // native_context is used when creating wrapper object.
1151 static inline MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1152 Handle<Object> object);
1153 static MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1154 Handle<Object> object,
1155 Handle<Context> context);
1157 MUST_USE_RESULT static MaybeHandle<Object> GetProperty(
1158 LookupIterator* it, LanguageMode language_mode = SLOPPY);
1160 // Implementation of [[Put]], ECMA-262 5th edition, section 8.12.5.
1161 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1162 Handle<Object> object, Handle<Name> name, Handle<Object> value,
1163 LanguageMode language_mode,
1164 StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
1166 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1167 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1168 StoreFromKeyed store_mode);
1170 MUST_USE_RESULT static MaybeHandle<Object> SetSuperProperty(
1171 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1172 StoreFromKeyed store_mode);
1174 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1175 LookupIterator* it, LanguageMode language_mode);
1176 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1177 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1178 LanguageMode language_mode);
1179 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1180 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1181 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1182 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1183 Handle<Object> value, LanguageMode language_mode);
1184 MUST_USE_RESULT static MaybeHandle<Object> RedefineNonconfigurableProperty(
1185 Isolate* isolate, Handle<Object> name, Handle<Object> value,
1186 LanguageMode language_mode);
1187 MUST_USE_RESULT static MaybeHandle<Object> SetDataProperty(
1188 LookupIterator* it, Handle<Object> value);
1189 MUST_USE_RESULT static MaybeHandle<Object> AddDataProperty(
1190 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1191 LanguageMode language_mode, StoreFromKeyed store_mode);
1192 MUST_USE_RESULT static inline MaybeHandle<Object> GetPropertyOrElement(
1193 Handle<Object> object, Handle<Name> name,
1194 LanguageMode language_mode = SLOPPY);
1195 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1196 Isolate* isolate, Handle<Object> object, const char* key,
1197 LanguageMode language_mode = SLOPPY);
1198 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1199 Handle<Object> object, Handle<Name> name,
1200 LanguageMode language_mode = SLOPPY);
1202 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithAccessor(
1203 LookupIterator* it, LanguageMode language_mode);
1204 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithAccessor(
1205 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1207 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithDefinedGetter(
1208 Handle<Object> receiver,
1209 Handle<JSReceiver> getter);
1210 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithDefinedSetter(
1211 Handle<Object> receiver,
1212 Handle<JSReceiver> setter,
1213 Handle<Object> value);
1215 MUST_USE_RESULT static inline MaybeHandle<Object> GetElement(
1216 Isolate* isolate, Handle<Object> object, uint32_t index,
1217 LanguageMode language_mode = SLOPPY);
1219 MUST_USE_RESULT static inline MaybeHandle<Object> SetElement(
1220 Isolate* isolate, Handle<Object> object, uint32_t index,
1221 Handle<Object> value, LanguageMode language_mode);
1223 static inline Handle<Object> GetPrototypeSkipHiddenPrototypes(
1224 Isolate* isolate, Handle<Object> receiver);
1226 // Returns the permanent hash code associated with this object. May return
1227 // undefined if not yet created.
1230 // Returns undefined for JSObjects, but returns the hash code for simple
1231 // objects. This avoids a double lookup in the cases where we know we will
1232 // add the hash to the JSObject if it does not already exist.
1233 Object* GetSimpleHash();
1235 // Returns the permanent hash code associated with this object depending on
1236 // the actual object type. May create and store a hash code if needed and none
1238 static Handle<Smi> GetOrCreateHash(Isolate* isolate, Handle<Object> object);
1240 // Checks whether this object has the same value as the given one. This
1241 // function is implemented according to ES5, section 9.12 and can be used
1242 // to implement the Harmony "egal" function.
1243 bool SameValue(Object* other);
1245 // Checks whether this object has the same value as the given one.
1246 // +0 and -0 are treated equal. Everything else is the same as SameValue.
1247 // This function is implemented according to ES6, section 7.2.4 and is used
1248 // by ES6 Map and Set.
1249 bool SameValueZero(Object* other);
1251 // Tries to convert an object to an array length. Returns true and sets the
1252 // output parameter if it succeeds.
1253 inline bool ToArrayLength(uint32_t* index);
1255 // Tries to convert an object to an array index. Returns true and sets the
1256 // output parameter if it succeeds. Equivalent to ToArrayLength, but does not
1257 // allow kMaxUInt32.
1258 inline bool ToArrayIndex(uint32_t* index);
1260 // Returns true if this is a JSValue containing a string and the index is
1261 // < the length of the string. Used to implement [] on strings.
1262 inline bool IsStringObjectWithCharacterAt(uint32_t index);
1264 DECLARE_VERIFIER(Object)
1266 // Verify a pointer is a valid object pointer.
1267 static void VerifyPointer(Object* p);
1270 inline void VerifyApiCallResultType();
1272 // Prints this object without details.
1273 void ShortPrint(FILE* out = stdout);
1275 // Prints this object without details to a message accumulator.
1276 void ShortPrint(StringStream* accumulator);
1278 void ShortPrint(std::ostream& os); // NOLINT
1280 DECLARE_CAST(Object)
1282 // Layout description.
1283 static const int kHeaderSize = 0; // Object does not take up any space.
1286 // For our gdb macros, we should perhaps change these in the future.
1289 // Prints this object with details.
1290 void Print(std::ostream& os); // NOLINT
1292 void Print() { ShortPrint(); }
1293 void Print(std::ostream& os) { ShortPrint(os); } // NOLINT
1297 friend class LookupIterator;
1298 friend class PrototypeIterator;
1300 // Return the map of the root of object's prototype chain.
1301 Map* GetRootMap(Isolate* isolate);
1303 // Helper for SetProperty and SetSuperProperty.
1304 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyInternal(
1305 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1306 StoreFromKeyed store_mode, bool* found);
1308 DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
1313 explicit Brief(const Object* const v) : value(v) {}
1314 const Object* value;
1318 std::ostream& operator<<(std::ostream& os, const Brief& v);
1321 // Smi represents integer Numbers that can be stored in 31 bits.
1322 // Smis are immediate which means they are NOT allocated in the heap.
1323 // The this pointer has the following format: [31 bit signed int] 0
1324 // For long smis it has the following format:
1325 // [32 bit signed int] [31 bits zero padding] 0
1326 // Smi stands for small integer.
1327 class Smi: public Object {
1329 // Returns the integer value.
1330 inline int value() const;
1332 // Convert a value to a Smi object.
1333 static inline Smi* FromInt(int value);
1335 static inline Smi* FromIntptr(intptr_t value);
1337 // Returns whether value can be represented in a Smi.
1338 static inline bool IsValid(intptr_t value);
1342 // Dispatched behavior.
1343 void SmiPrint(std::ostream& os) const; // NOLINT
1344 DECLARE_VERIFIER(Smi)
1346 static const int kMinValue =
1347 (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1348 static const int kMaxValue = -(kMinValue + 1);
1351 DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1355 // Heap objects typically have a map pointer in their first word. However,
1356 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1357 // encoded in the first word. The class MapWord is an abstraction of the
1358 // value in a heap object's first word.
1359 class MapWord BASE_EMBEDDED {
1361 // Normal state: the map word contains a map pointer.
1363 // Create a map word from a map pointer.
1364 static inline MapWord FromMap(const Map* map);
1366 // View this map word as a map pointer.
1367 inline Map* ToMap();
1370 // Scavenge collection: the map word of live objects in the from space
1371 // contains a forwarding address (a heap object pointer in the to space).
1373 // True if this map word is a forwarding address for a scavenge
1374 // collection. Only valid during a scavenge collection (specifically,
1375 // when all map words are heap object pointers, i.e. not during a full GC).
1376 inline bool IsForwardingAddress();
1378 // Create a map word from a forwarding address.
1379 static inline MapWord FromForwardingAddress(HeapObject* object);
1381 // View this map word as a forwarding address.
1382 inline HeapObject* ToForwardingAddress();
1384 static inline MapWord FromRawValue(uintptr_t value) {
1385 return MapWord(value);
1388 inline uintptr_t ToRawValue() {
1393 // HeapObject calls the private constructor and directly reads the value.
1394 friend class HeapObject;
1396 explicit MapWord(uintptr_t value) : value_(value) {}
1402 // The content of an heap object (except for the map pointer). kTaggedValues
1403 // objects can contain both heap pointers and Smis, kMixedValues can contain
1404 // heap pointers, Smis, and raw values (e.g. doubles or strings), and kRawValues
1405 // objects can contain raw values and Smis.
1406 enum class HeapObjectContents { kTaggedValues, kMixedValues, kRawValues };
1409 // HeapObject is the superclass for all classes describing heap allocated
1411 class HeapObject: public Object {
1413 // [map]: Contains a map which contains the object's reflective
1415 inline Map* map() const;
1416 inline void set_map(Map* value);
1417 // The no-write-barrier version. This is OK if the object is white and in
1418 // new space, or if the value is an immortal immutable object, like the maps
1419 // of primitive (non-JS) objects like strings, heap numbers etc.
1420 inline void set_map_no_write_barrier(Map* value);
1422 // Get the map using acquire load.
1423 inline Map* synchronized_map();
1424 inline MapWord synchronized_map_word() const;
1426 // Set the map using release store
1427 inline void synchronized_set_map(Map* value);
1428 inline void synchronized_set_map_no_write_barrier(Map* value);
1429 inline void synchronized_set_map_word(MapWord map_word);
1431 // During garbage collection, the map word of a heap object does not
1432 // necessarily contain a map pointer.
1433 inline MapWord map_word() const;
1434 inline void set_map_word(MapWord map_word);
1436 // The Heap the object was allocated in. Used also to access Isolate.
1437 inline Heap* GetHeap() const;
1439 // Convenience method to get current isolate.
1440 inline Isolate* GetIsolate() const;
1442 // Converts an address to a HeapObject pointer.
1443 static inline HeapObject* FromAddress(Address address);
1445 // Returns the address of this HeapObject.
1446 inline Address address();
1448 // Iterates over pointers contained in the object (including the Map)
1449 void Iterate(ObjectVisitor* v);
1451 // Iterates over all pointers contained in the object except the
1452 // first map pointer. The object type is given in the first
1453 // parameter. This function does not access the map pointer in the
1454 // object, and so is safe to call while the map pointer is modified.
1455 void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1457 // Returns the heap object's size in bytes
1460 // Indicates what type of values this heap object may contain.
1461 inline HeapObjectContents ContentType();
1463 // Given a heap object's map pointer, returns the heap size in bytes
1464 // Useful when the map pointer field is used for other purposes.
1466 inline int SizeFromMap(Map* map);
1468 // Returns the field at offset in obj, as a read/write Object* reference.
1469 // Does no checking, and is safe to use during GC, while maps are invalid.
1470 // Does not invoke write barrier, so should only be assigned to
1471 // during marking GC.
1472 static inline Object** RawField(HeapObject* obj, int offset);
1474 // Adds the |code| object related to |name| to the code cache of this map. If
1475 // this map is a dictionary map that is shared, the map copied and installed
1477 static void UpdateMapCodeCache(Handle<HeapObject> object,
1481 DECLARE_CAST(HeapObject)
1483 // Return the write barrier mode for this. Callers of this function
1484 // must be able to present a reference to an DisallowHeapAllocation
1485 // object as a sign that they are not going to use this function
1486 // from code that allocates and thus invalidates the returned write
1488 inline WriteBarrierMode GetWriteBarrierMode(
1489 const DisallowHeapAllocation& promise);
1491 // Dispatched behavior.
1492 void HeapObjectShortPrint(std::ostream& os); // NOLINT
1494 void PrintHeader(std::ostream& os, const char* id); // NOLINT
1496 DECLARE_PRINTER(HeapObject)
1497 DECLARE_VERIFIER(HeapObject)
1499 inline void VerifyObjectField(int offset);
1500 inline void VerifySmiField(int offset);
1502 // Verify a pointer is a valid HeapObject pointer that points to object
1503 // areas in the heap.
1504 static void VerifyHeapPointer(Object* p);
1507 inline AllocationAlignment RequiredAlignment();
1509 // Layout description.
1510 // First field in a heap object is map.
1511 static const int kMapOffset = Object::kHeaderSize;
1512 static const int kHeaderSize = kMapOffset + kPointerSize;
1514 STATIC_ASSERT(kMapOffset == Internals::kHeapObjectMapOffset);
1517 // helpers for calling an ObjectVisitor to iterate over pointers in the
1518 // half-open range [start, end) specified as integer offsets
1519 inline void IteratePointers(ObjectVisitor* v, int start, int end);
1520 // as above, for the single element at "offset"
1521 inline void IteratePointer(ObjectVisitor* v, int offset);
1522 // as above, for the next code link of a code object.
1523 inline void IterateNextCodeLink(ObjectVisitor* v, int offset);
1526 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1530 // This class describes a body of an object of a fixed size
1531 // in which all pointer fields are located in the [start_offset, end_offset)
1533 template<int start_offset, int end_offset, int size>
1534 class FixedBodyDescriptor {
1536 static const int kStartOffset = start_offset;
1537 static const int kEndOffset = end_offset;
1538 static const int kSize = size;
1540 static inline void IterateBody(HeapObject* obj, ObjectVisitor* v);
1542 template<typename StaticVisitor>
1543 static inline void IterateBody(HeapObject* obj) {
1544 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1545 HeapObject::RawField(obj, end_offset));
1550 // This class describes a body of an object of a variable size
1551 // in which all pointer fields are located in the [start_offset, object_size)
1553 template<int start_offset>
1554 class FlexibleBodyDescriptor {
1556 static const int kStartOffset = start_offset;
1558 static inline void IterateBody(HeapObject* obj,
1562 template<typename StaticVisitor>
1563 static inline void IterateBody(HeapObject* obj, int object_size) {
1564 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1565 HeapObject::RawField(obj, object_size));
1570 // The HeapNumber class describes heap allocated numbers that cannot be
1571 // represented in a Smi (small integer)
1572 class HeapNumber: public HeapObject {
1574 // [value]: number value.
1575 inline double value() const;
1576 inline void set_value(double value);
1578 DECLARE_CAST(HeapNumber)
1580 // Dispatched behavior.
1581 bool HeapNumberBooleanValue();
1583 void HeapNumberPrint(std::ostream& os); // NOLINT
1584 DECLARE_VERIFIER(HeapNumber)
1586 inline int get_exponent();
1587 inline int get_sign();
1589 // Layout description.
1590 static const int kValueOffset = HeapObject::kHeaderSize;
1591 // IEEE doubles are two 32 bit words. The first is just mantissa, the second
1592 // is a mixture of sign, exponent and mantissa. The offsets of two 32 bit
1593 // words within double numbers are endian dependent and they are set
1595 #if defined(V8_TARGET_LITTLE_ENDIAN)
1596 static const int kMantissaOffset = kValueOffset;
1597 static const int kExponentOffset = kValueOffset + 4;
1598 #elif defined(V8_TARGET_BIG_ENDIAN)
1599 static const int kMantissaOffset = kValueOffset + 4;
1600 static const int kExponentOffset = kValueOffset;
1602 #error Unknown byte ordering
1605 static const int kSize = kValueOffset + kDoubleSize;
1606 static const uint32_t kSignMask = 0x80000000u;
1607 static const uint32_t kExponentMask = 0x7ff00000u;
1608 static const uint32_t kMantissaMask = 0xfffffu;
1609 static const int kMantissaBits = 52;
1610 static const int kExponentBits = 11;
1611 static const int kExponentBias = 1023;
1612 static const int kExponentShift = 20;
1613 static const int kInfinityOrNanExponent =
1614 (kExponentMask >> kExponentShift) - kExponentBias;
1615 static const int kMantissaBitsInTopWord = 20;
1616 static const int kNonMantissaBitsInTopWord = 12;
1619 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
1623 // The Float32x4 class describes heap allocated SIMD values holding 4 32-bit
1625 class Float32x4 : public HeapObject {
1627 inline float get_lane(int lane) const;
1628 inline void set_lane(int lane, float value);
1630 DECLARE_CAST(Float32x4)
1632 // Dispatched behavior.
1633 void Float32x4Print(std::ostream& os); // NOLINT
1634 DECLARE_VERIFIER(Float32x4)
1636 // Layout description.
1637 static const int kValueOffset = HeapObject::kHeaderSize;
1638 static const int kSize = kValueOffset + kSimd128Size;
1641 DISALLOW_IMPLICIT_CONSTRUCTORS(Float32x4);
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, an
1772 // ExternalArray, or a FixedArray parameter map for a (sloppy)
1773 // arguments object.
1774 DECL_ACCESSORS(elements, FixedArrayBase)
1775 inline void initialize_elements();
1776 static void ResetElements(Handle<JSObject> object);
1777 static inline void SetMapAndElements(Handle<JSObject> object,
1779 Handle<FixedArrayBase> elements);
1780 inline ElementsKind GetElementsKind();
1781 ElementsAccessor* GetElementsAccessor();
1782 // Returns true if an object has elements of FAST_SMI_ELEMENTS ElementsKind.
1783 inline bool HasFastSmiElements();
1784 // Returns true if an object has elements of FAST_ELEMENTS ElementsKind.
1785 inline bool HasFastObjectElements();
1786 // Returns true if an object has elements of FAST_ELEMENTS or
1787 // FAST_SMI_ONLY_ELEMENTS.
1788 inline bool HasFastSmiOrObjectElements();
1789 // Returns true if an object has any of the fast elements kinds.
1790 inline bool HasFastElements();
1791 // Returns true if an object has elements of FAST_DOUBLE_ELEMENTS
1793 inline bool HasFastDoubleElements();
1794 // Returns true if an object has elements of FAST_HOLEY_*_ELEMENTS
1796 inline bool HasFastHoleyElements();
1797 inline bool HasSloppyArgumentsElements();
1798 inline bool HasDictionaryElements();
1800 inline bool HasExternalUint8ClampedElements();
1801 inline bool HasExternalArrayElements();
1802 inline bool HasExternalInt8Elements();
1803 inline bool HasExternalUint8Elements();
1804 inline bool HasExternalInt16Elements();
1805 inline bool HasExternalUint16Elements();
1806 inline bool HasExternalInt32Elements();
1807 inline bool HasExternalUint32Elements();
1808 inline bool HasExternalFloat32Elements();
1809 inline bool HasExternalFloat64Elements();
1811 inline bool HasFixedTypedArrayElements();
1813 inline bool HasFixedUint8ClampedElements();
1814 inline bool HasFixedArrayElements();
1815 inline bool HasFixedInt8Elements();
1816 inline bool HasFixedUint8Elements();
1817 inline bool HasFixedInt16Elements();
1818 inline bool HasFixedUint16Elements();
1819 inline bool HasFixedInt32Elements();
1820 inline bool HasFixedUint32Elements();
1821 inline bool HasFixedFloat32Elements();
1822 inline bool HasFixedFloat64Elements();
1824 inline bool HasFastArgumentsElements();
1825 inline bool HasSlowArgumentsElements();
1826 inline SeededNumberDictionary* element_dictionary(); // Gets slow elements.
1828 // Requires: HasFastElements().
1829 static Handle<FixedArray> EnsureWritableFastElements(
1830 Handle<JSObject> object);
1832 // Collects elements starting at index 0.
1833 // Undefined values are placed after non-undefined values.
1834 // Returns the number of non-undefined values.
1835 static Handle<Object> PrepareElementsForSort(Handle<JSObject> object,
1837 // As PrepareElementsForSort, but only on objects where elements is
1838 // a dictionary, and it will stay a dictionary. Collates undefined and
1839 // unexisting elements below limit from position zero of the elements.
1840 static Handle<Object> PrepareSlowElementsForSort(Handle<JSObject> object,
1843 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithInterceptor(
1844 LookupIterator* it, Handle<Object> value);
1846 // SetLocalPropertyIgnoreAttributes converts callbacks to fields. We need to
1847 // grant an exemption to ExecutableAccessor callbacks in some cases.
1848 enum ExecutableAccessorInfoHandling { DEFAULT_HANDLING, DONT_FORCE_FIELD };
1850 MUST_USE_RESULT static MaybeHandle<Object> DefineOwnPropertyIgnoreAttributes(
1851 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1852 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1854 MUST_USE_RESULT static MaybeHandle<Object> SetOwnPropertyIgnoreAttributes(
1855 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1856 PropertyAttributes attributes,
1857 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1859 MUST_USE_RESULT static MaybeHandle<Object> SetOwnElementIgnoreAttributes(
1860 Handle<JSObject> object, uint32_t index, Handle<Object> value,
1861 PropertyAttributes attributes,
1862 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1864 // Equivalent to one of the above depending on whether |name| can be converted
1865 // to an array index.
1866 MUST_USE_RESULT static MaybeHandle<Object>
1867 DefinePropertyOrElementIgnoreAttributes(
1868 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1869 PropertyAttributes attributes = NONE,
1870 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1872 // Adds or reconfigures a property to attributes NONE. It will fail when it
1874 MUST_USE_RESULT static Maybe<bool> CreateDataProperty(LookupIterator* it,
1875 Handle<Object> value);
1877 static void AddProperty(Handle<JSObject> object, Handle<Name> name,
1878 Handle<Object> value, PropertyAttributes attributes);
1880 MUST_USE_RESULT static MaybeHandle<Object> AddDataElement(
1881 Handle<JSObject> receiver, uint32_t index, Handle<Object> value,
1882 PropertyAttributes attributes);
1884 // Extend the receiver with a single fast property appeared first in the
1885 // passed map. This also extends the property backing store if necessary.
1886 static void AllocateStorageForMap(Handle<JSObject> object, Handle<Map> map);
1888 // Migrates the given object to a map whose field representations are the
1889 // lowest upper bound of all known representations for that field.
1890 static void MigrateInstance(Handle<JSObject> instance);
1892 // Migrates the given object only if the target map is already available,
1893 // or returns false if such a map is not yet available.
1894 static bool TryMigrateInstance(Handle<JSObject> instance);
1896 // Sets the property value in a normalized object given (key, value, details).
1897 // Handles the special representation of JS global objects.
1898 static void SetNormalizedProperty(Handle<JSObject> object, Handle<Name> name,
1899 Handle<Object> value,
1900 PropertyDetails details);
1901 static void SetDictionaryElement(Handle<JSObject> object, uint32_t index,
1902 Handle<Object> value,
1903 PropertyAttributes attributes);
1904 static void SetDictionaryArgumentsElement(Handle<JSObject> object,
1906 Handle<Object> value,
1907 PropertyAttributes attributes);
1909 static void OptimizeAsPrototype(Handle<JSObject> object,
1910 PrototypeOptimizationMode mode);
1911 static void ReoptimizeIfPrototype(Handle<JSObject> object);
1912 static void LazyRegisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1913 static bool RegisterPrototypeUserIfNotRegistered(Handle<JSObject> prototype,
1914 Handle<HeapObject> user,
1916 static bool UnregisterPrototypeUser(Handle<JSObject> prototype,
1917 Handle<HeapObject> user);
1918 static void InvalidatePrototypeChains(Map* map);
1920 // Retrieve interceptors.
1921 InterceptorInfo* GetNamedInterceptor();
1922 InterceptorInfo* GetIndexedInterceptor();
1924 // Used from JSReceiver.
1925 MUST_USE_RESULT static Maybe<PropertyAttributes>
1926 GetPropertyAttributesWithInterceptor(LookupIterator* it);
1927 MUST_USE_RESULT static Maybe<PropertyAttributes>
1928 GetPropertyAttributesWithFailedAccessCheck(LookupIterator* it);
1930 // Retrieves an AccessorPair property from the given object. Might return
1931 // undefined if the property doesn't exist or is of a different kind.
1932 MUST_USE_RESULT static MaybeHandle<Object> GetAccessor(
1933 Handle<JSObject> object,
1935 AccessorComponent component);
1937 // Defines an AccessorPair property on the given object.
1938 // TODO(mstarzinger): Rename to SetAccessor().
1939 static MaybeHandle<Object> DefineAccessor(Handle<JSObject> object,
1941 Handle<Object> getter,
1942 Handle<Object> setter,
1943 PropertyAttributes attributes);
1945 // Defines an AccessorInfo property on the given object.
1946 MUST_USE_RESULT static MaybeHandle<Object> SetAccessor(
1947 Handle<JSObject> object,
1948 Handle<AccessorInfo> info);
1950 // The result must be checked first for exceptions. If there's no exception,
1951 // the output parameter |done| indicates whether the interceptor has a result
1953 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithInterceptor(
1954 LookupIterator* it, bool* done);
1956 // Accessors for hidden properties object.
1958 // Hidden properties are not own properties of the object itself.
1959 // Instead they are stored in an auxiliary structure kept as an own
1960 // property with a special name Heap::hidden_string(). But if the
1961 // receiver is a JSGlobalProxy then the auxiliary object is a property
1962 // of its prototype, and if it's a detached proxy, then you can't have
1963 // hidden properties.
1965 // Sets a hidden property on this object. Returns this object if successful,
1966 // undefined if called on a detached proxy.
1967 static Handle<Object> SetHiddenProperty(Handle<JSObject> object,
1969 Handle<Object> value);
1970 // Gets the value of a hidden property with the given key. Returns the hole
1971 // if the property doesn't exist (or if called on a detached proxy),
1972 // otherwise returns the value set for the key.
1973 Object* GetHiddenProperty(Handle<Name> key);
1974 // Deletes a hidden property. Deleting a non-existing property is
1975 // considered successful.
1976 static void DeleteHiddenProperty(Handle<JSObject> object,
1978 // Returns true if the object has a property with the hidden string as name.
1979 static bool HasHiddenProperties(Handle<JSObject> object);
1981 static void SetIdentityHash(Handle<JSObject> object, Handle<Smi> hash);
1983 static void ValidateElements(Handle<JSObject> object);
1985 // Makes sure that this object can contain HeapObject as elements.
1986 static inline void EnsureCanContainHeapObjectElements(Handle<JSObject> obj);
1988 // Makes sure that this object can contain the specified elements.
1989 static inline void EnsureCanContainElements(
1990 Handle<JSObject> object,
1993 EnsureElementsMode mode);
1994 static inline void EnsureCanContainElements(
1995 Handle<JSObject> object,
1996 Handle<FixedArrayBase> elements,
1998 EnsureElementsMode mode);
1999 static void EnsureCanContainElements(
2000 Handle<JSObject> object,
2001 Arguments* arguments,
2004 EnsureElementsMode mode);
2006 // Would we convert a fast elements array to dictionary mode given
2007 // an access at key?
2008 bool WouldConvertToSlowElements(uint32_t index);
2010 // Computes the new capacity when expanding the elements of a JSObject.
2011 static uint32_t NewElementsCapacity(uint32_t old_capacity) {
2012 // (old_capacity + 50%) + 16
2013 return old_capacity + (old_capacity >> 1) + 16;
2016 // These methods do not perform access checks!
2017 static void UpdateAllocationSite(Handle<JSObject> object,
2018 ElementsKind to_kind);
2020 // Lookup interceptors are used for handling properties controlled by host
2022 inline bool HasNamedInterceptor();
2023 inline bool HasIndexedInterceptor();
2025 // Computes the enumerable keys from interceptors. Used for debug mirrors and
2026 // by JSReceiver::GetKeys.
2027 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForNamedInterceptor(
2028 Handle<JSObject> object,
2029 Handle<JSReceiver> receiver);
2030 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForIndexedInterceptor(
2031 Handle<JSObject> object,
2032 Handle<JSReceiver> receiver);
2034 // Support functions for v8 api (needed for correct interceptor behavior).
2035 MUST_USE_RESULT static Maybe<bool> HasRealNamedProperty(
2036 Handle<JSObject> object, Handle<Name> name);
2037 MUST_USE_RESULT static Maybe<bool> HasRealElementProperty(
2038 Handle<JSObject> object, uint32_t index);
2039 MUST_USE_RESULT static Maybe<bool> HasRealNamedCallbackProperty(
2040 Handle<JSObject> object, Handle<Name> name);
2042 // Get the header size for a JSObject. Used to compute the index of
2043 // internal fields as well as the number of internal fields.
2044 inline int GetHeaderSize();
2046 inline int GetInternalFieldCount();
2047 inline int GetInternalFieldOffset(int index);
2048 inline Object* GetInternalField(int index);
2049 inline void SetInternalField(int index, Object* value);
2050 inline void SetInternalField(int index, Smi* value);
2052 // Returns the number of properties on this object filtering out properties
2053 // with the specified attributes (ignoring interceptors).
2054 int NumberOfOwnProperties(PropertyAttributes filter = NONE);
2055 // Fill in details for properties into storage starting at the specified
2057 void GetOwnPropertyNames(
2058 FixedArray* storage, int index, PropertyAttributes filter = NONE);
2060 // Returns the number of properties on this object filtering out properties
2061 // with the specified attributes (ignoring interceptors).
2062 int NumberOfOwnElements(PropertyAttributes filter);
2063 // Returns the number of enumerable elements (ignoring interceptors).
2064 int NumberOfEnumElements();
2065 // Returns the number of elements on this object filtering out elements
2066 // with the specified attributes (ignoring interceptors).
2067 int GetOwnElementKeys(FixedArray* storage, PropertyAttributes filter);
2068 // Count and fill in the enumerable elements into storage.
2069 // (storage->length() == NumberOfEnumElements()).
2070 // If storage is NULL, will count the elements without adding
2071 // them to any storage.
2072 // Returns the number of enumerable elements.
2073 int GetEnumElementKeys(FixedArray* storage);
2075 static Handle<FixedArray> GetEnumPropertyKeys(Handle<JSObject> object,
2078 // Returns a new map with all transitions dropped from the object's current
2079 // map and the ElementsKind set.
2080 static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
2081 ElementsKind to_kind);
2082 static void TransitionElementsKind(Handle<JSObject> object,
2083 ElementsKind to_kind);
2085 // Always use this to migrate an object to a new map.
2086 // |expected_additional_properties| is only used for fast-to-slow transitions
2087 // and ignored otherwise.
2088 static void MigrateToMap(Handle<JSObject> object, Handle<Map> new_map,
2089 int expected_additional_properties = 0);
2091 // Convert the object to use the canonical dictionary
2092 // representation. If the object is expected to have additional properties
2093 // added this number can be indicated to have the backing store allocated to
2094 // an initial capacity for holding these properties.
2095 static void NormalizeProperties(Handle<JSObject> object,
2096 PropertyNormalizationMode mode,
2097 int expected_additional_properties,
2098 const char* reason);
2100 // Convert and update the elements backing store to be a
2101 // SeededNumberDictionary dictionary. Returns the backing after conversion.
2102 static Handle<SeededNumberDictionary> NormalizeElements(
2103 Handle<JSObject> object);
2105 void RequireSlowElements(SeededNumberDictionary* dictionary);
2107 // Transform slow named properties to fast variants.
2108 static void MigrateSlowToFast(Handle<JSObject> object,
2109 int unused_property_fields, const char* reason);
2111 inline bool IsUnboxedDoubleField(FieldIndex index);
2113 // Access fast-case object properties at index.
2114 static Handle<Object> FastPropertyAt(Handle<JSObject> object,
2115 Representation representation,
2117 inline Object* RawFastPropertyAt(FieldIndex index);
2118 inline double RawFastDoublePropertyAt(FieldIndex index);
2120 inline void FastPropertyAtPut(FieldIndex index, Object* value);
2121 inline void RawFastPropertyAtPut(FieldIndex index, Object* value);
2122 inline void RawFastDoublePropertyAtPut(FieldIndex index, double value);
2123 inline void WriteToField(int descriptor, Object* value);
2125 // Access to in object properties.
2126 inline int GetInObjectPropertyOffset(int index);
2127 inline Object* InObjectPropertyAt(int index);
2128 inline Object* InObjectPropertyAtPut(int index,
2130 WriteBarrierMode mode
2131 = UPDATE_WRITE_BARRIER);
2133 // Set the object's prototype (only JSReceiver and null are allowed values).
2134 MUST_USE_RESULT static MaybeHandle<Object> SetPrototype(
2135 Handle<JSObject> object, Handle<Object> value, bool from_javascript);
2137 // Initializes the body after properties slot, properties slot is
2138 // initialized by set_properties. Fill the pre-allocated fields with
2139 // pre_allocated_value and the rest with filler_value.
2140 // Note: this call does not update write barrier, the caller is responsible
2141 // to ensure that |filler_value| can be collected without WB here.
2142 inline void InitializeBody(Map* map,
2143 Object* pre_allocated_value,
2144 Object* filler_value);
2146 // Check whether this object references another object
2147 bool ReferencesObject(Object* obj);
2149 // Disalow further properties to be added to the oject.
2150 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensions(
2151 Handle<JSObject> object);
2153 bool IsExtensible();
2156 MUST_USE_RESULT static MaybeHandle<Object> Seal(Handle<JSObject> object);
2158 // ES5 Object.freeze
2159 MUST_USE_RESULT static MaybeHandle<Object> Freeze(Handle<JSObject> object);
2161 // Called the first time an object is observed with ES7 Object.observe.
2162 static void SetObserved(Handle<JSObject> object);
2165 enum DeepCopyHints { kNoHints = 0, kObjectIsShallow = 1 };
2167 MUST_USE_RESULT static MaybeHandle<JSObject> DeepCopy(
2168 Handle<JSObject> object,
2169 AllocationSiteUsageContext* site_context,
2170 DeepCopyHints hints = kNoHints);
2171 MUST_USE_RESULT static MaybeHandle<JSObject> DeepWalk(
2172 Handle<JSObject> object,
2173 AllocationSiteCreationContext* site_context);
2175 DECLARE_CAST(JSObject)
2177 // Dispatched behavior.
2178 void JSObjectShortPrint(StringStream* accumulator);
2179 DECLARE_PRINTER(JSObject)
2180 DECLARE_VERIFIER(JSObject)
2182 void PrintProperties(std::ostream& os); // NOLINT
2183 void PrintElements(std::ostream& os); // NOLINT
2185 #if defined(DEBUG) || defined(OBJECT_PRINT)
2186 void PrintTransitions(std::ostream& os); // NOLINT
2189 static void PrintElementsTransition(
2190 FILE* file, Handle<JSObject> object,
2191 ElementsKind from_kind, Handle<FixedArrayBase> from_elements,
2192 ElementsKind to_kind, Handle<FixedArrayBase> to_elements);
2194 void PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map);
2197 // Structure for collecting spill information about JSObjects.
2198 class SpillInformation {
2202 int number_of_objects_;
2203 int number_of_objects_with_fast_properties_;
2204 int number_of_objects_with_fast_elements_;
2205 int number_of_fast_used_fields_;
2206 int number_of_fast_unused_fields_;
2207 int number_of_slow_used_properties_;
2208 int number_of_slow_unused_properties_;
2209 int number_of_fast_used_elements_;
2210 int number_of_fast_unused_elements_;
2211 int number_of_slow_used_elements_;
2212 int number_of_slow_unused_elements_;
2215 void IncrementSpillStatistics(SpillInformation* info);
2219 // If a GC was caused while constructing this object, the elements pointer
2220 // may point to a one pointer filler map. The object won't be rooted, but
2221 // our heap verification code could stumble across it.
2222 bool ElementsAreSafeToExamine();
2225 Object* SlowReverseLookup(Object* value);
2227 // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2228 // Also maximal value of JSArray's length property.
2229 static const uint32_t kMaxElementCount = 0xffffffffu;
2231 // Constants for heuristics controlling conversion of fast elements
2232 // to slow elements.
2234 // Maximal gap that can be introduced by adding an element beyond
2235 // the current elements length.
2236 static const uint32_t kMaxGap = 1024;
2238 // Maximal length of fast elements array that won't be checked for
2239 // being dense enough on expansion.
2240 static const int kMaxUncheckedFastElementsLength = 5000;
2242 // Same as above but for old arrays. This limit is more strict. We
2243 // don't want to be wasteful with long lived objects.
2244 static const int kMaxUncheckedOldFastElementsLength = 500;
2246 // Note that Page::kMaxRegularHeapObjectSize puts a limit on
2247 // permissible values (see the DCHECK in heap.cc).
2248 static const int kInitialMaxFastElementArray = 100000;
2250 // This constant applies only to the initial map of "global.Object" and
2251 // not to arbitrary other JSObject maps.
2252 static const int kInitialGlobalObjectUnusedPropertiesCount = 4;
2254 static const int kMaxInstanceSize = 255 * kPointerSize;
2255 // When extending the backing storage for property values, we increase
2256 // its size by more than the 1 entry necessary, so sequentially adding fields
2257 // to the same object requires fewer allocations and copies.
2258 static const int kFieldsAdded = 3;
2260 // Layout description.
2261 static const int kPropertiesOffset = HeapObject::kHeaderSize;
2262 static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2263 static const int kHeaderSize = kElementsOffset + kPointerSize;
2265 STATIC_ASSERT(kHeaderSize == Internals::kJSObjectHeaderSize);
2267 class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2269 static inline int SizeOf(Map* map, HeapObject* object);
2272 Context* GetCreationContext();
2274 // Enqueue change record for Object.observe. May cause GC.
2275 MUST_USE_RESULT static MaybeHandle<Object> EnqueueChangeRecord(
2276 Handle<JSObject> object, const char* type, Handle<Name> name,
2277 Handle<Object> old_value);
2279 // Gets the number of currently used elements.
2280 int GetFastElementsUsage();
2282 // Deletes an existing named property in a normalized object.
2283 static void DeleteNormalizedProperty(Handle<JSObject> object,
2284 Handle<Name> name, int entry);
2287 friend class JSReceiver;
2288 friend class Object;
2290 static void MigrateFastToFast(Handle<JSObject> object, Handle<Map> new_map);
2291 static void MigrateFastToSlow(Handle<JSObject> object,
2292 Handle<Map> new_map,
2293 int expected_additional_properties);
2295 // Used from Object::GetProperty().
2296 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithFailedAccessCheck(
2297 LookupIterator* it);
2299 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithFailedAccessCheck(
2300 LookupIterator* it, Handle<Object> value);
2302 // Add a property to a slow-case object.
2303 static void AddSlowProperty(Handle<JSObject> object,
2305 Handle<Object> value,
2306 PropertyAttributes attributes);
2308 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithInterceptor(
2309 LookupIterator* it);
2311 bool ReferencesObjectFromElements(FixedArray* elements,
2315 // Return the hash table backing store or the inline stored identity hash,
2316 // whatever is found.
2317 MUST_USE_RESULT Object* GetHiddenPropertiesHashTable();
2319 // Return the hash table backing store for hidden properties. If there is no
2320 // backing store, allocate one.
2321 static Handle<ObjectHashTable> GetOrCreateHiddenPropertiesHashtable(
2322 Handle<JSObject> object);
2324 // Set the hidden property backing store to either a hash table or
2325 // the inline-stored identity hash.
2326 static Handle<Object> SetHiddenPropertiesHashTable(
2327 Handle<JSObject> object,
2328 Handle<Object> value);
2330 MUST_USE_RESULT Object* GetIdentityHash();
2332 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSObject> object);
2334 static Handle<SeededNumberDictionary> GetNormalizedElementDictionary(
2335 Handle<JSObject> object, Handle<FixedArrayBase> elements);
2337 // Helper for fast versions of preventExtensions, seal, and freeze.
2338 // attrs is one of NONE, SEALED, or FROZEN (depending on the operation).
2339 template <PropertyAttributes attrs>
2340 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensionsWithTransition(
2341 Handle<JSObject> object);
2343 DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
2347 // Common superclass for FixedArrays that allow implementations to share
2348 // common accessors and some code paths.
2349 class FixedArrayBase: public HeapObject {
2351 // [length]: length of the array.
2352 inline int length() const;
2353 inline void set_length(int value);
2355 // Get and set the length using acquire loads and release stores.
2356 inline int synchronized_length() const;
2357 inline void synchronized_set_length(int value);
2359 DECLARE_CAST(FixedArrayBase)
2361 // Layout description.
2362 // Length is smi tagged when it is stored.
2363 static const int kLengthOffset = HeapObject::kHeaderSize;
2364 static const int kHeaderSize = kLengthOffset + kPointerSize;
2368 class FixedDoubleArray;
2369 class IncrementalMarking;
2372 // FixedArray describes fixed-sized arrays with element type Object*.
2373 class FixedArray: public FixedArrayBase {
2375 // Setter and getter for elements.
2376 inline Object* get(int index) const;
2377 void SetValue(uint32_t index, Object* value);
2378 static inline Handle<Object> get(Handle<FixedArray> array, int index);
2379 // Setter that uses write barrier.
2380 inline void set(int index, Object* value);
2381 inline bool is_the_hole(int index);
2383 // Setter that doesn't need write barrier.
2384 inline void set(int index, Smi* value);
2385 // Setter with explicit barrier mode.
2386 inline void set(int index, Object* value, WriteBarrierMode mode);
2388 // Setters for frequently used oddballs located in old space.
2389 inline void set_undefined(int index);
2390 inline void set_null(int index);
2391 inline void set_the_hole(int index);
2393 inline Object** GetFirstElementAddress();
2394 inline bool ContainsOnlySmisOrHoles();
2396 // Gives access to raw memory which stores the array's data.
2397 inline Object** data_start();
2399 inline void FillWithHoles(int from, int to);
2401 // Shrink length and insert filler objects.
2402 void Shrink(int length);
2405 static Handle<FixedArray> CopySize(Handle<FixedArray> array,
2407 PretenureFlag pretenure = NOT_TENURED);
2409 enum KeyFilter { ALL_KEYS, NON_SYMBOL_KEYS };
2411 // Add the elements of a JSArray to this FixedArray.
2412 MUST_USE_RESULT static MaybeHandle<FixedArray> AddKeysFromArrayLike(
2413 Handle<FixedArray> content, Handle<JSObject> array,
2414 KeyFilter filter = ALL_KEYS);
2416 // Computes the union of keys and return the result.
2417 // Used for implementing "for (n in object) { }"
2418 MUST_USE_RESULT static MaybeHandle<FixedArray> UnionOfKeys(
2419 Handle<FixedArray> first,
2420 Handle<FixedArray> second);
2422 // Copy a sub array from the receiver to dest.
2423 void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
2425 // Garbage collection support.
2426 static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
2428 // Code Generation support.
2429 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2431 // Garbage collection support.
2432 Object** RawFieldOfElementAt(int index) {
2433 return HeapObject::RawField(this, OffsetOfElementAt(index));
2436 DECLARE_CAST(FixedArray)
2438 // Maximal allowed size, in bytes, of a single FixedArray.
2439 // Prevents overflowing size computations, as well as extreme memory
2441 static const int kMaxSize = 128 * MB * kPointerSize;
2442 // Maximally allowed length of a FixedArray.
2443 static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
2445 // Dispatched behavior.
2446 DECLARE_PRINTER(FixedArray)
2447 DECLARE_VERIFIER(FixedArray)
2449 // Checks if two FixedArrays have identical contents.
2450 bool IsEqualTo(FixedArray* other);
2453 // Swap two elements in a pair of arrays. If this array and the
2454 // numbers array are the same object, the elements are only swapped
2456 void SwapPairs(FixedArray* numbers, int i, int j);
2458 // Sort prefix of this array and the numbers array as pairs wrt. the
2459 // numbers. If the numbers array and the this array are the same
2460 // object, the prefix of this array is sorted.
2461 void SortPairs(FixedArray* numbers, uint32_t len);
2463 class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
2465 static inline int SizeOf(Map* map, HeapObject* object) {
2467 reinterpret_cast<FixedArray*>(object)->synchronized_length());
2472 // Set operation on FixedArray without using write barriers. Can
2473 // only be used for storing old space objects or smis.
2474 static inline void NoWriteBarrierSet(FixedArray* array,
2478 // Set operation on FixedArray without incremental write barrier. Can
2479 // only be used if the object is guaranteed to be white (whiteness witness
2481 static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
2486 STATIC_ASSERT(kHeaderSize == Internals::kFixedArrayHeaderSize);
2488 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
2492 // FixedDoubleArray describes fixed-sized arrays with element type double.
2493 class FixedDoubleArray: public FixedArrayBase {
2495 // Setter and getter for elements.
2496 inline double get_scalar(int index);
2497 inline uint64_t get_representation(int index);
2498 static inline Handle<Object> get(Handle<FixedDoubleArray> array, int index);
2499 // This accessor has to get a Number as |value|.
2500 void SetValue(uint32_t index, Object* value);
2501 inline void set(int index, double value);
2502 inline void set_the_hole(int index);
2504 // Checking for the hole.
2505 inline bool is_the_hole(int index);
2507 // Garbage collection support.
2508 inline static int SizeFor(int length) {
2509 return kHeaderSize + length * kDoubleSize;
2512 // Gives access to raw memory which stores the array's data.
2513 inline double* data_start();
2515 inline void FillWithHoles(int from, int to);
2517 // Code Generation support.
2518 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2520 DECLARE_CAST(FixedDoubleArray)
2522 // Maximal allowed size, in bytes, of a single FixedDoubleArray.
2523 // Prevents overflowing size computations, as well as extreme memory
2525 static const int kMaxSize = 512 * MB;
2526 // Maximally allowed length of a FixedArray.
2527 static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
2529 // Dispatched behavior.
2530 DECLARE_PRINTER(FixedDoubleArray)
2531 DECLARE_VERIFIER(FixedDoubleArray)
2534 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
2538 class WeakFixedArray : public FixedArray {
2540 enum SearchForDuplicates { kAlwaysAdd, kAddIfNotFound };
2542 // If |maybe_array| is not a WeakFixedArray, a fresh one will be allocated.
2543 static Handle<WeakFixedArray> Add(
2544 Handle<Object> maybe_array, Handle<HeapObject> value,
2545 SearchForDuplicates search_for_duplicates = kAlwaysAdd,
2546 bool* was_present = NULL);
2548 // Returns true if an entry was found and removed.
2549 bool Remove(Handle<HeapObject> value);
2553 inline Object* Get(int index) const;
2554 inline void Clear(int index);
2555 inline int Length() const;
2557 inline bool IsEmptySlot(int index) const;
2558 static Object* Empty() { return Smi::FromInt(0); }
2560 DECLARE_CAST(WeakFixedArray)
2563 static const int kLastUsedIndexIndex = 0;
2564 static const int kFirstIndex = 1;
2566 static Handle<WeakFixedArray> Allocate(
2567 Isolate* isolate, int size, Handle<WeakFixedArray> initialize_from);
2569 static void Set(Handle<WeakFixedArray> array, int index,
2570 Handle<HeapObject> value);
2571 inline void clear(int index);
2573 inline int last_used_index() const;
2574 inline void set_last_used_index(int index);
2576 // Disallow inherited setters.
2577 void set(int index, Smi* value);
2578 void set(int index, Object* value);
2579 void set(int index, Object* value, WriteBarrierMode mode);
2580 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakFixedArray);
2584 // Generic array grows dynamically with O(1) amortized insertion.
2585 class ArrayList : public FixedArray {
2589 // Use this if GC can delete elements from the array.
2590 kReloadLengthAfterAllocation,
2592 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj,
2593 AddMode mode = kNone);
2594 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj1,
2595 Handle<Object> obj2, AddMode = kNone);
2596 inline int Length();
2597 inline void SetLength(int length);
2598 inline Object* Get(int index);
2599 inline Object** Slot(int index);
2600 inline void Set(int index, Object* obj);
2601 inline void Clear(int index, Object* undefined);
2602 DECLARE_CAST(ArrayList)
2605 static Handle<ArrayList> EnsureSpace(Handle<ArrayList> array, int length);
2606 static const int kLengthIndex = 0;
2607 static const int kFirstIndex = 1;
2608 DISALLOW_IMPLICIT_CONSTRUCTORS(ArrayList);
2612 // DescriptorArrays are fixed arrays used to hold instance descriptors.
2613 // The format of the these objects is:
2614 // [0]: Number of descriptors
2615 // [1]: Either Smi(0) if uninitialized, or a pointer to small fixed array:
2616 // [0]: pointer to fixed array with enum cache
2617 // [1]: either Smi(0) or pointer to fixed array with indices
2619 // [2 + number of descriptors * kDescriptorSize]: start of slack
2620 class DescriptorArray: public FixedArray {
2622 // Returns true for both shared empty_descriptor_array and for smis, which the
2623 // map uses to encode additional bit fields when the descriptor array is not
2625 inline bool IsEmpty();
2627 // Returns the number of descriptors in the array.
2628 int number_of_descriptors() {
2629 DCHECK(length() >= kFirstIndex || IsEmpty());
2631 return len == 0 ? 0 : Smi::cast(get(kDescriptorLengthIndex))->value();
2634 int number_of_descriptors_storage() {
2636 return len == 0 ? 0 : (len - kFirstIndex) / kDescriptorSize;
2639 int NumberOfSlackDescriptors() {
2640 return number_of_descriptors_storage() - number_of_descriptors();
2643 inline void SetNumberOfDescriptors(int number_of_descriptors);
2644 inline int number_of_entries() { return number_of_descriptors(); }
2646 bool HasEnumCache() {
2647 return !IsEmpty() && !get(kEnumCacheIndex)->IsSmi();
2650 void CopyEnumCacheFrom(DescriptorArray* array) {
2651 set(kEnumCacheIndex, array->get(kEnumCacheIndex));
2654 FixedArray* GetEnumCache() {
2655 DCHECK(HasEnumCache());
2656 FixedArray* bridge = FixedArray::cast(get(kEnumCacheIndex));
2657 return FixedArray::cast(bridge->get(kEnumCacheBridgeCacheIndex));
2660 bool HasEnumIndicesCache() {
2661 if (IsEmpty()) return false;
2662 Object* object = get(kEnumCacheIndex);
2663 if (object->IsSmi()) return false;
2664 FixedArray* bridge = FixedArray::cast(object);
2665 return !bridge->get(kEnumCacheBridgeIndicesCacheIndex)->IsSmi();
2668 FixedArray* GetEnumIndicesCache() {
2669 DCHECK(HasEnumIndicesCache());
2670 FixedArray* bridge = FixedArray::cast(get(kEnumCacheIndex));
2671 return FixedArray::cast(bridge->get(kEnumCacheBridgeIndicesCacheIndex));
2674 Object** GetEnumCacheSlot() {
2675 DCHECK(HasEnumCache());
2676 return HeapObject::RawField(reinterpret_cast<HeapObject*>(this),
2680 void ClearEnumCache();
2682 // Initialize or change the enum cache,
2683 // using the supplied storage for the small "bridge".
2684 void SetEnumCache(FixedArray* bridge_storage,
2685 FixedArray* new_cache,
2686 Object* new_index_cache);
2688 bool CanHoldValue(int descriptor, Object* value);
2690 // Accessors for fetching instance descriptor at descriptor number.
2691 inline Name* GetKey(int descriptor_number);
2692 inline Object** GetKeySlot(int descriptor_number);
2693 inline Object* GetValue(int descriptor_number);
2694 inline void SetValue(int descriptor_number, Object* value);
2695 inline Object** GetValueSlot(int descriptor_number);
2696 static inline int GetValueOffset(int descriptor_number);
2697 inline Object** GetDescriptorStartSlot(int descriptor_number);
2698 inline Object** GetDescriptorEndSlot(int descriptor_number);
2699 inline PropertyDetails GetDetails(int descriptor_number);
2700 inline PropertyType GetType(int descriptor_number);
2701 inline int GetFieldIndex(int descriptor_number);
2702 inline HeapType* GetFieldType(int descriptor_number);
2703 inline Object* GetConstant(int descriptor_number);
2704 inline Object* GetCallbacksObject(int descriptor_number);
2705 inline AccessorDescriptor* GetCallbacks(int descriptor_number);
2707 inline Name* GetSortedKey(int descriptor_number);
2708 inline int GetSortedKeyIndex(int descriptor_number);
2709 inline void SetSortedKey(int pointer, int descriptor_number);
2710 inline void SetRepresentation(int descriptor_number,
2711 Representation representation);
2713 // Accessor for complete descriptor.
2714 inline void Get(int descriptor_number, Descriptor* desc);
2715 inline void Set(int descriptor_number, Descriptor* desc);
2716 void Replace(int descriptor_number, Descriptor* descriptor);
2718 // Append automatically sets the enumeration index. This should only be used
2719 // to add descriptors in bulk at the end, followed by sorting the descriptor
2721 inline void Append(Descriptor* desc);
2723 static Handle<DescriptorArray> CopyUpTo(Handle<DescriptorArray> desc,
2724 int enumeration_index,
2727 static Handle<DescriptorArray> CopyUpToAddAttributes(
2728 Handle<DescriptorArray> desc,
2729 int enumeration_index,
2730 PropertyAttributes attributes,
2733 // Sort the instance descriptors by the hash codes of their keys.
2736 // Search the instance descriptors for given name.
2737 INLINE(int Search(Name* name, int number_of_own_descriptors));
2739 // As the above, but uses DescriptorLookupCache and updates it when
2741 INLINE(int SearchWithCache(Name* name, Map* map));
2743 // Allocates a DescriptorArray, but returns the singleton
2744 // empty descriptor array object if number_of_descriptors is 0.
2745 static Handle<DescriptorArray> Allocate(Isolate* isolate,
2746 int number_of_descriptors,
2749 DECLARE_CAST(DescriptorArray)
2751 // Constant for denoting key was not found.
2752 static const int kNotFound = -1;
2754 static const int kDescriptorLengthIndex = 0;
2755 static const int kEnumCacheIndex = 1;
2756 static const int kFirstIndex = 2;
2758 // The length of the "bridge" to the enum cache.
2759 static const int kEnumCacheBridgeLength = 2;
2760 static const int kEnumCacheBridgeCacheIndex = 0;
2761 static const int kEnumCacheBridgeIndicesCacheIndex = 1;
2763 // Layout description.
2764 static const int kDescriptorLengthOffset = FixedArray::kHeaderSize;
2765 static const int kEnumCacheOffset = kDescriptorLengthOffset + kPointerSize;
2766 static const int kFirstOffset = kEnumCacheOffset + kPointerSize;
2768 // Layout description for the bridge array.
2769 static const int kEnumCacheBridgeCacheOffset = FixedArray::kHeaderSize;
2771 // Layout of descriptor.
2772 static const int kDescriptorKey = 0;
2773 static const int kDescriptorDetails = 1;
2774 static const int kDescriptorValue = 2;
2775 static const int kDescriptorSize = 3;
2777 #if defined(DEBUG) || defined(OBJECT_PRINT)
2778 // For our gdb macros, we should perhaps change these in the future.
2781 // Print all the descriptors.
2782 void PrintDescriptors(std::ostream& os); // NOLINT
2786 // Is the descriptor array sorted and without duplicates?
2787 bool IsSortedNoDuplicates(int valid_descriptors = -1);
2789 // Is the descriptor array consistent with the back pointers in targets?
2790 bool IsConsistentWithBackPointers(Map* current_map);
2792 // Are two DescriptorArrays equal?
2793 bool IsEqualTo(DescriptorArray* other);
2796 // Returns the fixed array length required to hold number_of_descriptors
2798 static int LengthFor(int number_of_descriptors) {
2799 return ToKeyIndex(number_of_descriptors);
2803 // WhitenessWitness is used to prove that a descriptor array is white
2804 // (unmarked), so incremental write barriers can be skipped because the
2805 // marking invariant cannot be broken and slots pointing into evacuation
2806 // candidates will be discovered when the object is scanned. A witness is
2807 // always stack-allocated right after creating an array. By allocating a
2808 // witness, incremental marking is globally disabled. The witness is then
2809 // passed along wherever needed to statically prove that the array is known to
2811 class WhitenessWitness {
2813 inline explicit WhitenessWitness(DescriptorArray* array);
2814 inline ~WhitenessWitness();
2817 IncrementalMarking* marking_;
2820 // An entry in a DescriptorArray, represented as an (array, index) pair.
2823 inline explicit Entry(DescriptorArray* descs, int index) :
2824 descs_(descs), index_(index) { }
2826 inline PropertyType type() { return descs_->GetType(index_); }
2827 inline Object* GetCallbackObject() { return descs_->GetValue(index_); }
2830 DescriptorArray* descs_;
2834 // Conversion from descriptor number to array indices.
2835 static int ToKeyIndex(int descriptor_number) {
2836 return kFirstIndex +
2837 (descriptor_number * kDescriptorSize) +
2841 static int ToDetailsIndex(int descriptor_number) {
2842 return kFirstIndex +
2843 (descriptor_number * kDescriptorSize) +
2847 static int ToValueIndex(int descriptor_number) {
2848 return kFirstIndex +
2849 (descriptor_number * kDescriptorSize) +
2853 // Transfer a complete descriptor from the src descriptor array to this
2854 // descriptor array.
2855 void CopyFrom(int index, DescriptorArray* src, const WhitenessWitness&);
2857 inline void Set(int descriptor_number,
2859 const WhitenessWitness&);
2861 // Swap first and second descriptor.
2862 inline void SwapSortedKeys(int first, int second);
2864 DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
2868 enum SearchMode { ALL_ENTRIES, VALID_ENTRIES };
2870 template <SearchMode search_mode, typename T>
2871 inline int Search(T* array, Name* name, int valid_entries = 0,
2872 int* out_insertion_index = NULL);
2875 // HashTable is a subclass of FixedArray that implements a hash table
2876 // that uses open addressing and quadratic probing.
2878 // In order for the quadratic probing to work, elements that have not
2879 // yet been used and elements that have been deleted are
2880 // distinguished. Probing continues when deleted elements are
2881 // encountered and stops when unused elements are encountered.
2883 // - Elements with key == undefined have not been used yet.
2884 // - Elements with key == the_hole have been deleted.
2886 // The hash table class is parameterized with a Shape and a Key.
2887 // Shape must be a class with the following interface:
2888 // class ExampleShape {
2890 // // Tells whether key matches other.
2891 // static bool IsMatch(Key key, Object* other);
2892 // // Returns the hash value for key.
2893 // static uint32_t Hash(Key key);
2894 // // Returns the hash value for object.
2895 // static uint32_t HashForObject(Key key, Object* object);
2896 // // Convert key to an object.
2897 // static inline Handle<Object> AsHandle(Isolate* isolate, Key key);
2898 // // The prefix size indicates number of elements in the beginning
2899 // // of the backing storage.
2900 // static const int kPrefixSize = ..;
2901 // // The Element size indicates number of elements per entry.
2902 // static const int kEntrySize = ..;
2904 // The prefix size indicates an amount of memory in the
2905 // beginning of the backing storage that can be used for non-element
2906 // information by subclasses.
2908 template<typename Key>
2911 static const bool UsesSeed = false;
2912 static uint32_t Hash(Key key) { return 0; }
2913 static uint32_t SeededHash(Key key, uint32_t seed) {
2917 static uint32_t HashForObject(Key key, Object* object) { return 0; }
2918 static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
2920 return HashForObject(key, object);
2925 class HashTableBase : public FixedArray {
2927 // Returns the number of elements in the hash table.
2928 int NumberOfElements() {
2929 return Smi::cast(get(kNumberOfElementsIndex))->value();
2932 // Returns the number of deleted elements in the hash table.
2933 int NumberOfDeletedElements() {
2934 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
2937 // Returns the capacity of the hash table.
2939 return Smi::cast(get(kCapacityIndex))->value();
2942 // ElementAdded should be called whenever an element is added to a
2944 void ElementAdded() { SetNumberOfElements(NumberOfElements() + 1); }
2946 // ElementRemoved should be called whenever an element is removed from
2948 void ElementRemoved() {
2949 SetNumberOfElements(NumberOfElements() - 1);
2950 SetNumberOfDeletedElements(NumberOfDeletedElements() + 1);
2952 void ElementsRemoved(int n) {
2953 SetNumberOfElements(NumberOfElements() - n);
2954 SetNumberOfDeletedElements(NumberOfDeletedElements() + n);
2957 // Computes the required capacity for a table holding the given
2958 // number of elements. May be more than HashTable::kMaxCapacity.
2959 static inline int ComputeCapacity(int at_least_space_for);
2961 // Use a different heuristic to compute capacity when serializing.
2962 static inline int ComputeCapacityForSerialization(int at_least_space_for);
2964 // Tells whether k is a real key. The hole and undefined are not allowed
2965 // as keys and can be used to indicate missing or deleted elements.
2966 bool IsKey(Object* k) {
2967 return !k->IsTheHole() && !k->IsUndefined();
2970 // Compute the probe offset (quadratic probing).
2971 INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
2972 return (n + n * n) >> 1;
2975 static const int kNumberOfElementsIndex = 0;
2976 static const int kNumberOfDeletedElementsIndex = 1;
2977 static const int kCapacityIndex = 2;
2978 static const int kPrefixStartIndex = 3;
2980 // Constant used for denoting a absent entry.
2981 static const int kNotFound = -1;
2984 // Update the number of elements in the hash table.
2985 void SetNumberOfElements(int nof) {
2986 set(kNumberOfElementsIndex, Smi::FromInt(nof));
2989 // Update the number of deleted elements in the hash table.
2990 void SetNumberOfDeletedElements(int nod) {
2991 set(kNumberOfDeletedElementsIndex, Smi::FromInt(nod));
2994 // Returns probe entry.
2995 static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
2996 DCHECK(base::bits::IsPowerOfTwo32(size));
2997 return (hash + GetProbeOffset(number)) & (size - 1);
3000 inline static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
3001 return hash & (size - 1);
3004 inline static uint32_t NextProbe(
3005 uint32_t last, uint32_t number, uint32_t size) {
3006 return (last + number) & (size - 1);
3011 template <typename Derived, typename Shape, typename Key>
3012 class HashTable : public HashTableBase {
3015 inline uint32_t Hash(Key key) {
3016 if (Shape::UsesSeed) {
3017 return Shape::SeededHash(key, GetHeap()->HashSeed());
3019 return Shape::Hash(key);
3023 inline uint32_t HashForObject(Key key, Object* object) {
3024 if (Shape::UsesSeed) {
3025 return Shape::SeededHashForObject(key, GetHeap()->HashSeed(), object);
3027 return Shape::HashForObject(key, object);
3031 // Returns a new HashTable object.
3032 MUST_USE_RESULT static Handle<Derived> New(
3033 Isolate* isolate, int at_least_space_for,
3034 MinimumCapacity capacity_option = USE_DEFAULT_MINIMUM_CAPACITY,
3035 PretenureFlag pretenure = NOT_TENURED);
3037 DECLARE_CAST(HashTable)
3039 // Garbage collection support.
3040 void IteratePrefix(ObjectVisitor* visitor);
3041 void IterateElements(ObjectVisitor* visitor);
3043 // Find entry for key otherwise return kNotFound.
3044 inline int FindEntry(Key key);
3045 inline int FindEntry(Isolate* isolate, Key key, int32_t hash);
3046 int FindEntry(Isolate* isolate, Key key);
3048 // Rehashes the table in-place.
3049 void Rehash(Key key);
3051 // Returns the key at entry.
3052 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3054 static const int kElementsStartIndex = kPrefixStartIndex + Shape::kPrefixSize;
3055 static const int kEntrySize = Shape::kEntrySize;
3056 static const int kElementsStartOffset =
3057 kHeaderSize + kElementsStartIndex * kPointerSize;
3058 static const int kCapacityOffset =
3059 kHeaderSize + kCapacityIndex * kPointerSize;
3061 // Returns the index for an entry (of the key)
3062 static inline int EntryToIndex(int entry) {
3063 return (entry * kEntrySize) + kElementsStartIndex;
3067 friend class ObjectHashTable;
3069 // Find the entry at which to insert element with the given key that
3070 // has the given hash value.
3071 uint32_t FindInsertionEntry(uint32_t hash);
3073 // Attempt to shrink hash table after removal of key.
3074 MUST_USE_RESULT static Handle<Derived> Shrink(Handle<Derived> table, Key key);
3076 // Ensure enough space for n additional elements.
3077 MUST_USE_RESULT static Handle<Derived> EnsureCapacity(
3078 Handle<Derived> table,
3081 PretenureFlag pretenure = NOT_TENURED);
3083 // Sets the capacity of the hash table.
3084 void SetCapacity(int capacity) {
3085 // To scale a computed hash code to fit within the hash table, we
3086 // use bit-wise AND with a mask, so the capacity must be positive
3088 DCHECK(capacity > 0);
3089 DCHECK(capacity <= kMaxCapacity);
3090 set(kCapacityIndex, Smi::FromInt(capacity));
3093 // Maximal capacity of HashTable. Based on maximal length of underlying
3094 // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
3096 static const int kMaxCapacity =
3097 (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
3100 // Returns _expected_ if one of entries given by the first _probe_ probes is
3101 // equal to _expected_. Otherwise, returns the entry given by the probe
3103 uint32_t EntryForProbe(Key key, Object* k, int probe, uint32_t expected);
3105 void Swap(uint32_t entry1, uint32_t entry2, WriteBarrierMode mode);
3107 // Rehashes this hash-table into the new table.
3108 void Rehash(Handle<Derived> new_table, Key key);
3112 // HashTableKey is an abstract superclass for virtual key behavior.
3113 class HashTableKey {
3115 // Returns whether the other object matches this key.
3116 virtual bool IsMatch(Object* other) = 0;
3117 // Returns the hash value for this key.
3118 virtual uint32_t Hash() = 0;
3119 // Returns the hash value for object.
3120 virtual uint32_t HashForObject(Object* key) = 0;
3121 // Returns the key object for storing into the hash table.
3122 MUST_USE_RESULT virtual Handle<Object> AsHandle(Isolate* isolate) = 0;
3124 virtual ~HashTableKey() {}
3128 class StringTableShape : public BaseShape<HashTableKey*> {
3130 static inline bool IsMatch(HashTableKey* key, Object* value) {
3131 return key->IsMatch(value);
3134 static inline uint32_t Hash(HashTableKey* key) {
3138 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3139 return key->HashForObject(object);
3142 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3144 static const int kPrefixSize = 0;
3145 static const int kEntrySize = 1;
3148 class SeqOneByteString;
3152 // No special elements in the prefix and the element size is 1
3153 // because only the string itself (the key) needs to be stored.
3154 class StringTable: public HashTable<StringTable,
3158 // Find string in the string table. If it is not there yet, it is
3159 // added. The return value is the string found.
3160 static Handle<String> LookupString(Isolate* isolate, Handle<String> key);
3161 static Handle<String> LookupKey(Isolate* isolate, HashTableKey* key);
3162 static String* LookupKeyIfExists(Isolate* isolate, HashTableKey* key);
3164 // Tries to internalize given string and returns string handle on success
3165 // or an empty handle otherwise.
3166 MUST_USE_RESULT static MaybeHandle<String> InternalizeStringIfExists(
3168 Handle<String> string);
3170 // Looks up a string that is equal to the given string and returns
3171 // string handle if it is found, or an empty handle otherwise.
3172 MUST_USE_RESULT static MaybeHandle<String> LookupStringIfExists(
3174 Handle<String> str);
3175 MUST_USE_RESULT static MaybeHandle<String> LookupTwoCharsStringIfExists(
3180 static void EnsureCapacityForDeserialization(Isolate* isolate, int expected);
3182 DECLARE_CAST(StringTable)
3185 template <bool seq_one_byte>
3186 friend class JsonParser;
3188 DISALLOW_IMPLICIT_CONSTRUCTORS(StringTable);
3192 template <typename Derived, typename Shape, typename Key>
3193 class Dictionary: public HashTable<Derived, Shape, Key> {
3194 typedef HashTable<Derived, Shape, Key> DerivedHashTable;
3197 // Returns the value at entry.
3198 Object* ValueAt(int entry) {
3199 return this->get(Derived::EntryToIndex(entry) + 1);
3202 // Set the value for entry.
3203 void ValueAtPut(int entry, Object* value) {
3204 this->set(Derived::EntryToIndex(entry) + 1, value);
3207 // Returns the property details for the property at entry.
3208 PropertyDetails DetailsAt(int entry) {
3209 return Shape::DetailsAt(static_cast<Derived*>(this), entry);
3212 // Set the details for entry.
3213 void DetailsAtPut(int entry, PropertyDetails value) {
3214 Shape::DetailsAtPut(static_cast<Derived*>(this), entry, value);
3217 // Returns true if property at given entry is deleted.
3218 bool IsDeleted(int entry) {
3219 return Shape::IsDeleted(static_cast<Derived*>(this), entry);
3222 // Delete a property from the dictionary.
3223 static Handle<Object> DeleteProperty(Handle<Derived> dictionary, int entry);
3225 // Attempt to shrink the dictionary after deletion of key.
3226 MUST_USE_RESULT static inline Handle<Derived> Shrink(
3227 Handle<Derived> dictionary,
3229 return DerivedHashTable::Shrink(dictionary, key);
3233 // TODO(dcarney): templatize or move to SeededNumberDictionary
3234 void CopyValuesTo(FixedArray* elements);
3236 // Returns the number of elements in the dictionary filtering out properties
3237 // with the specified attributes.
3238 int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3240 // Returns the number of enumerable elements in the dictionary.
3241 int NumberOfEnumElements() {
3242 return NumberOfElementsFilterAttributes(
3243 static_cast<PropertyAttributes>(DONT_ENUM | SYMBOLIC));
3246 // Returns true if the dictionary contains any elements that are non-writable,
3247 // non-configurable, non-enumerable, or have getters/setters.
3248 bool HasComplexElements();
3250 enum SortMode { UNSORTED, SORTED };
3252 // Copies keys to preallocated fixed array.
3253 void CopyKeysTo(FixedArray* storage, PropertyAttributes filter,
3254 SortMode sort_mode);
3256 // Fill in details for properties into storage.
3257 void CopyKeysTo(FixedArray* storage, int index, PropertyAttributes filter,
3258 SortMode sort_mode);
3260 // Copies enumerable keys to preallocated fixed array.
3261 void CopyEnumKeysTo(FixedArray* storage);
3263 // Accessors for next enumeration index.
3264 void SetNextEnumerationIndex(int index) {
3266 this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
3269 int NextEnumerationIndex() {
3270 return Smi::cast(this->get(kNextEnumerationIndexIndex))->value();
3273 // Creates a new dictionary.
3274 MUST_USE_RESULT static Handle<Derived> New(
3276 int at_least_space_for,
3277 PretenureFlag pretenure = NOT_TENURED);
3279 // Ensure enough space for n additional elements.
3280 static Handle<Derived> EnsureCapacity(Handle<Derived> obj, int n, Key key);
3283 void Print(std::ostream& os); // NOLINT
3285 // Returns the key (slow).
3286 Object* SlowReverseLookup(Object* value);
3288 // Sets the entry to (key, value) pair.
3289 inline void SetEntry(int entry,
3291 Handle<Object> value);
3292 inline void SetEntry(int entry,
3294 Handle<Object> value,
3295 PropertyDetails details);
3297 MUST_USE_RESULT static Handle<Derived> Add(
3298 Handle<Derived> dictionary,
3300 Handle<Object> value,
3301 PropertyDetails details);
3303 // Returns iteration indices array for the |dictionary|.
3304 // Values are direct indices in the |HashTable| array.
3305 static Handle<FixedArray> BuildIterationIndicesArray(
3306 Handle<Derived> dictionary);
3309 // Generic at put operation.
3310 MUST_USE_RESULT static Handle<Derived> AtPut(
3311 Handle<Derived> dictionary,
3313 Handle<Object> value);
3315 // Add entry to dictionary.
3316 static void AddEntry(
3317 Handle<Derived> dictionary,
3319 Handle<Object> value,
3320 PropertyDetails details,
3323 // Generate new enumeration indices to avoid enumeration index overflow.
3324 // Returns iteration indices array for the |dictionary|.
3325 static Handle<FixedArray> GenerateNewEnumerationIndices(
3326 Handle<Derived> dictionary);
3327 static const int kMaxNumberKeyIndex = DerivedHashTable::kPrefixStartIndex;
3328 static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
3332 template <typename Derived, typename Shape>
3333 class NameDictionaryBase : public Dictionary<Derived, Shape, Handle<Name> > {
3334 typedef Dictionary<Derived, Shape, Handle<Name> > DerivedDictionary;
3337 // Find entry for key, otherwise return kNotFound. Optimized version of
3338 // HashTable::FindEntry.
3339 int FindEntry(Handle<Name> key);
3343 template <typename Key>
3344 class BaseDictionaryShape : public BaseShape<Key> {
3346 template <typename Dictionary>
3347 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry) {
3348 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3349 DCHECK(entry >= 0); // Not found is -1, which is not caught by get().
3350 return PropertyDetails(
3351 Smi::cast(dict->get(Dictionary::EntryToIndex(entry) + 2)));
3354 template <typename Dictionary>
3355 static inline void DetailsAtPut(Dictionary* dict, int entry,
3356 PropertyDetails value) {
3357 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3358 dict->set(Dictionary::EntryToIndex(entry) + 2, value.AsSmi());
3361 template <typename Dictionary>
3362 static bool IsDeleted(Dictionary* dict, int entry) {
3366 template <typename Dictionary>
3367 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3368 Handle<Object> value, PropertyDetails details);
3372 class NameDictionaryShape : public BaseDictionaryShape<Handle<Name> > {
3374 static inline bool IsMatch(Handle<Name> key, Object* other);
3375 static inline uint32_t Hash(Handle<Name> key);
3376 static inline uint32_t HashForObject(Handle<Name> key, Object* object);
3377 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Name> key);
3378 static const int kPrefixSize = 2;
3379 static const int kEntrySize = 3;
3380 static const bool kIsEnumerable = true;
3384 class NameDictionary
3385 : public NameDictionaryBase<NameDictionary, NameDictionaryShape> {
3386 typedef NameDictionaryBase<NameDictionary, NameDictionaryShape>
3390 DECLARE_CAST(NameDictionary)
3392 inline static Handle<FixedArray> DoGenerateNewEnumerationIndices(
3393 Handle<NameDictionary> dictionary);
3397 class GlobalDictionaryShape : public NameDictionaryShape {
3399 static const int kEntrySize = 2; // Overrides NameDictionaryShape::kEntrySize
3401 template <typename Dictionary>
3402 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry);
3404 template <typename Dictionary>
3405 static inline void DetailsAtPut(Dictionary* dict, int entry,
3406 PropertyDetails value);
3408 template <typename Dictionary>
3409 static bool IsDeleted(Dictionary* dict, int entry);
3411 template <typename Dictionary>
3412 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3413 Handle<Object> value, PropertyDetails details);
3417 class GlobalDictionary
3418 : public NameDictionaryBase<GlobalDictionary, GlobalDictionaryShape> {
3420 DECLARE_CAST(GlobalDictionary)
3424 class NumberDictionaryShape : public BaseDictionaryShape<uint32_t> {
3426 static inline bool IsMatch(uint32_t key, Object* other);
3427 static inline Handle<Object> AsHandle(Isolate* isolate, uint32_t key);
3428 static const int kEntrySize = 3;
3429 static const bool kIsEnumerable = false;
3433 class SeededNumberDictionaryShape : public NumberDictionaryShape {
3435 static const bool UsesSeed = true;
3436 static const int kPrefixSize = 2;
3438 static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
3439 static inline uint32_t SeededHashForObject(uint32_t key,
3445 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
3447 static const int kPrefixSize = 0;
3449 static inline uint32_t Hash(uint32_t key);
3450 static inline uint32_t HashForObject(uint32_t key, Object* object);
3454 class SeededNumberDictionary
3455 : public Dictionary<SeededNumberDictionary,
3456 SeededNumberDictionaryShape,
3459 DECLARE_CAST(SeededNumberDictionary)
3461 // Type specific at put (default NONE attributes is used when adding).
3462 MUST_USE_RESULT static Handle<SeededNumberDictionary> AtNumberPut(
3463 Handle<SeededNumberDictionary> dictionary,
3465 Handle<Object> value);
3466 MUST_USE_RESULT static Handle<SeededNumberDictionary> AddNumberEntry(
3467 Handle<SeededNumberDictionary> dictionary,
3469 Handle<Object> value,
3470 PropertyDetails details);
3472 // Set an existing entry or add a new one if needed.
3473 // Return the updated dictionary.
3474 MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
3475 Handle<SeededNumberDictionary> dictionary,
3477 Handle<Object> value,
3478 PropertyDetails details);
3480 void UpdateMaxNumberKey(uint32_t key);
3482 // If slow elements are required we will never go back to fast-case
3483 // for the elements kept in this dictionary. We require slow
3484 // elements if an element has been added at an index larger than
3485 // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
3486 // when defining a getter or setter with a number key.
3487 inline bool requires_slow_elements();
3488 inline void set_requires_slow_elements();
3490 // Get the value of the max number key that has been added to this
3491 // dictionary. max_number_key can only be called if
3492 // requires_slow_elements returns false.
3493 inline uint32_t max_number_key();
3496 static const int kRequiresSlowElementsMask = 1;
3497 static const int kRequiresSlowElementsTagSize = 1;
3498 static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
3502 class UnseededNumberDictionary
3503 : public Dictionary<UnseededNumberDictionary,
3504 UnseededNumberDictionaryShape,
3507 DECLARE_CAST(UnseededNumberDictionary)
3509 // Type specific at put (default NONE attributes is used when adding).
3510 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AtNumberPut(
3511 Handle<UnseededNumberDictionary> dictionary,
3513 Handle<Object> value);
3514 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AddNumberEntry(
3515 Handle<UnseededNumberDictionary> dictionary,
3517 Handle<Object> value);
3519 // Set an existing entry or add a new one if needed.
3520 // Return the updated dictionary.
3521 MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
3522 Handle<UnseededNumberDictionary> dictionary,
3524 Handle<Object> value);
3528 class ObjectHashTableShape : public BaseShape<Handle<Object> > {
3530 static inline bool IsMatch(Handle<Object> key, Object* other);
3531 static inline uint32_t Hash(Handle<Object> key);
3532 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3533 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3534 static const int kPrefixSize = 0;
3535 static const int kEntrySize = 2;
3539 // ObjectHashTable maps keys that are arbitrary objects to object values by
3540 // using the identity hash of the key for hashing purposes.
3541 class ObjectHashTable: public HashTable<ObjectHashTable,
3542 ObjectHashTableShape,
3545 ObjectHashTable, ObjectHashTableShape, Handle<Object> > DerivedHashTable;
3547 DECLARE_CAST(ObjectHashTable)
3549 // Attempt to shrink hash table after removal of key.
3550 MUST_USE_RESULT static inline Handle<ObjectHashTable> Shrink(
3551 Handle<ObjectHashTable> table,
3552 Handle<Object> key);
3554 // Looks up the value associated with the given key. The hole value is
3555 // returned in case the key is not present.
3556 Object* Lookup(Handle<Object> key);
3557 Object* Lookup(Handle<Object> key, int32_t hash);
3558 Object* Lookup(Isolate* isolate, Handle<Object> key, int32_t hash);
3560 // Adds (or overwrites) the value associated with the given key.
3561 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3563 Handle<Object> value);
3564 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3565 Handle<Object> key, Handle<Object> value,
3568 // Returns an ObjectHashTable (possibly |table|) where |key| has been removed.
3569 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3572 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3573 Handle<Object> key, bool* was_present,
3577 friend class MarkCompactCollector;
3579 void AddEntry(int entry, Object* key, Object* value);
3580 void RemoveEntry(int entry);
3582 // Returns the index to the value of an entry.
3583 static inline int EntryToValueIndex(int entry) {
3584 return EntryToIndex(entry) + 1;
3589 // OrderedHashTable is a HashTable with Object keys that preserves
3590 // insertion order. There are Map and Set interfaces (OrderedHashMap
3591 // and OrderedHashTable, below). It is meant to be used by JSMap/JSSet.
3593 // Only Object* keys are supported, with Object::SameValueZero() used as the
3594 // equality operator and Object::GetHash() for the hash function.
3596 // Based on the "Deterministic Hash Table" as described by Jason Orendorff at
3597 // https://wiki.mozilla.org/User:Jorend/Deterministic_hash_tables
3598 // Originally attributed to Tyler Close.
3601 // [0]: bucket count
3602 // [1]: element count
3603 // [2]: deleted element count
3604 // [3..(3 + NumberOfBuckets() - 1)]: "hash table", where each item is an
3605 // offset into the data table (see below) where the
3606 // first item in this bucket is stored.
3607 // [3 + NumberOfBuckets()..length]: "data table", an array of length
3608 // Capacity() * kEntrySize, where the first entrysize
3609 // items are handled by the derived class and the
3610 // item at kChainOffset is another entry into the
3611 // data table indicating the next entry in this hash
3614 // When we transition the table to a new version we obsolete it and reuse parts
3615 // of the memory to store information how to transition an iterator to the new
3618 // Memory layout for obsolete table:
3619 // [0]: bucket count
3620 // [1]: Next newer table
3621 // [2]: Number of removed holes or -1 when the table was cleared.
3622 // [3..(3 + NumberOfRemovedHoles() - 1)]: The indexes of the removed holes.
3623 // [3 + NumberOfRemovedHoles()..length]: Not used
3625 template<class Derived, class Iterator, int entrysize>
3626 class OrderedHashTable: public FixedArray {
3628 // Returns an OrderedHashTable with a capacity of at least |capacity|.
3629 static Handle<Derived> Allocate(
3630 Isolate* isolate, int capacity, PretenureFlag pretenure = NOT_TENURED);
3632 // Returns an OrderedHashTable (possibly |table|) with enough space
3633 // to add at least one new element.
3634 static Handle<Derived> EnsureGrowable(Handle<Derived> table);
3636 // Returns an OrderedHashTable (possibly |table|) that's shrunken
3638 static Handle<Derived> Shrink(Handle<Derived> table);
3640 // Returns a new empty OrderedHashTable and records the clearing so that
3641 // exisiting iterators can be updated.
3642 static Handle<Derived> Clear(Handle<Derived> table);
3644 int NumberOfElements() {
3645 return Smi::cast(get(kNumberOfElementsIndex))->value();
3648 int NumberOfDeletedElements() {
3649 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3652 int UsedCapacity() { return NumberOfElements() + NumberOfDeletedElements(); }
3654 int NumberOfBuckets() {
3655 return Smi::cast(get(kNumberOfBucketsIndex))->value();
3658 // Returns an index into |this| for the given entry.
3659 int EntryToIndex(int entry) {
3660 return kHashTableStartIndex + NumberOfBuckets() + (entry * kEntrySize);
3663 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3666 return !get(kNextTableIndex)->IsSmi();
3669 // The next newer table. This is only valid if the table is obsolete.
3670 Derived* NextTable() {
3671 return Derived::cast(get(kNextTableIndex));
3674 // When the table is obsolete we store the indexes of the removed holes.
3675 int RemovedIndexAt(int index) {
3676 return Smi::cast(get(kRemovedHolesIndex + index))->value();
3679 static const int kNotFound = -1;
3680 static const int kMinCapacity = 4;
3682 static const int kNumberOfBucketsIndex = 0;
3683 static const int kNumberOfElementsIndex = kNumberOfBucketsIndex + 1;
3684 static const int kNumberOfDeletedElementsIndex = kNumberOfElementsIndex + 1;
3685 static const int kHashTableStartIndex = kNumberOfDeletedElementsIndex + 1;
3686 static const int kNextTableIndex = kNumberOfElementsIndex;
3688 static const int kNumberOfBucketsOffset =
3689 kHeaderSize + kNumberOfBucketsIndex * kPointerSize;
3690 static const int kNumberOfElementsOffset =
3691 kHeaderSize + kNumberOfElementsIndex * kPointerSize;
3692 static const int kNumberOfDeletedElementsOffset =
3693 kHeaderSize + kNumberOfDeletedElementsIndex * kPointerSize;
3694 static const int kHashTableStartOffset =
3695 kHeaderSize + kHashTableStartIndex * kPointerSize;
3696 static const int kNextTableOffset =
3697 kHeaderSize + kNextTableIndex * kPointerSize;
3699 static const int kEntrySize = entrysize + 1;
3700 static const int kChainOffset = entrysize;
3702 static const int kLoadFactor = 2;
3704 // NumberOfDeletedElements is set to kClearedTableSentinel when
3705 // the table is cleared, which allows iterator transitions to
3706 // optimize that case.
3707 static const int kClearedTableSentinel = -1;
3710 static Handle<Derived> Rehash(Handle<Derived> table, int new_capacity);
3712 void SetNumberOfBuckets(int num) {
3713 set(kNumberOfBucketsIndex, Smi::FromInt(num));
3716 void SetNumberOfElements(int num) {
3717 set(kNumberOfElementsIndex, Smi::FromInt(num));
3720 void SetNumberOfDeletedElements(int num) {
3721 set(kNumberOfDeletedElementsIndex, Smi::FromInt(num));
3725 return NumberOfBuckets() * kLoadFactor;
3728 void SetNextTable(Derived* next_table) {
3729 set(kNextTableIndex, next_table);
3732 void SetRemovedIndexAt(int index, int removed_index) {
3733 return set(kRemovedHolesIndex + index, Smi::FromInt(removed_index));
3736 static const int kRemovedHolesIndex = kHashTableStartIndex;
3738 static const int kMaxCapacity =
3739 (FixedArray::kMaxLength - kHashTableStartIndex)
3740 / (1 + (kEntrySize * kLoadFactor));
3744 class JSSetIterator;
3747 class OrderedHashSet: public OrderedHashTable<
3748 OrderedHashSet, JSSetIterator, 1> {
3750 DECLARE_CAST(OrderedHashSet)
3754 class JSMapIterator;
3757 class OrderedHashMap
3758 : public OrderedHashTable<OrderedHashMap, JSMapIterator, 2> {
3760 DECLARE_CAST(OrderedHashMap)
3762 Object* ValueAt(int entry) {
3763 return get(EntryToIndex(entry) + kValueOffset);
3766 static const int kValueOffset = 1;
3770 template <int entrysize>
3771 class WeakHashTableShape : public BaseShape<Handle<Object> > {
3773 static inline bool IsMatch(Handle<Object> key, Object* other);
3774 static inline uint32_t Hash(Handle<Object> key);
3775 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3776 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3777 static const int kPrefixSize = 0;
3778 static const int kEntrySize = entrysize;
3782 // WeakHashTable maps keys that are arbitrary heap objects to heap object
3783 // values. The table wraps the keys in weak cells and store values directly.
3784 // Thus it references keys weakly and values strongly.
3785 class WeakHashTable: public HashTable<WeakHashTable,
3786 WeakHashTableShape<2>,
3789 WeakHashTable, WeakHashTableShape<2>, Handle<Object> > DerivedHashTable;
3791 DECLARE_CAST(WeakHashTable)
3793 // Looks up the value associated with the given key. The hole value is
3794 // returned in case the key is not present.
3795 Object* Lookup(Handle<HeapObject> key);
3797 // Adds (or overwrites) the value associated with the given key. Mapping a
3798 // key to the hole value causes removal of the whole entry.
3799 MUST_USE_RESULT static Handle<WeakHashTable> Put(Handle<WeakHashTable> table,
3800 Handle<HeapObject> key,
3801 Handle<HeapObject> value);
3803 static Handle<FixedArray> GetValues(Handle<WeakHashTable> table);
3806 friend class MarkCompactCollector;
3808 void AddEntry(int entry, Handle<WeakCell> key, Handle<HeapObject> value);
3810 // Returns the index to the value of an entry.
3811 static inline int EntryToValueIndex(int entry) {
3812 return EntryToIndex(entry) + 1;
3817 class WeakValueHashTable : public ObjectHashTable {
3819 DECLARE_CAST(WeakValueHashTable)
3822 // Looks up the value associated with the given key. The hole value is
3823 // returned in case the key is not present.
3824 Object* LookupWeak(Handle<Object> key);
3827 // Adds (or overwrites) the value associated with the given key. Mapping a
3828 // key to the hole value causes removal of the whole entry.
3829 MUST_USE_RESULT static Handle<WeakValueHashTable> PutWeak(
3830 Handle<WeakValueHashTable> table, Handle<Object> key,
3831 Handle<HeapObject> value);
3833 static Handle<FixedArray> GetWeakValues(Handle<WeakValueHashTable> table);
3837 // JSFunctionResultCache caches results of some JSFunction invocation.
3838 // It is a fixed array with fixed structure:
3839 // [0]: factory function
3840 // [1]: finger index
3841 // [2]: current cache size
3842 // [3]: dummy field.
3843 // The rest of array are key/value pairs.
3844 class JSFunctionResultCache : public FixedArray {
3846 static const int kFactoryIndex = 0;
3847 static const int kFingerIndex = kFactoryIndex + 1;
3848 static const int kCacheSizeIndex = kFingerIndex + 1;
3849 static const int kDummyIndex = kCacheSizeIndex + 1;
3850 static const int kEntriesIndex = kDummyIndex + 1;
3852 static const int kEntrySize = 2; // key + value
3854 static const int kFactoryOffset = kHeaderSize;
3855 static const int kFingerOffset = kFactoryOffset + kPointerSize;
3856 static const int kCacheSizeOffset = kFingerOffset + kPointerSize;
3858 inline void MakeZeroSize();
3859 inline void Clear();
3862 inline void set_size(int size);
3863 inline int finger_index();
3864 inline void set_finger_index(int finger_index);
3866 DECLARE_CAST(JSFunctionResultCache)
3868 DECLARE_VERIFIER(JSFunctionResultCache)
3872 // ScopeInfo represents information about different scopes of a source
3873 // program and the allocation of the scope's variables. Scope information
3874 // is stored in a compressed form in ScopeInfo objects and is used
3875 // at runtime (stack dumps, deoptimization, etc.).
3877 // This object provides quick access to scope info details for runtime
3879 class ScopeInfo : public FixedArray {
3881 DECLARE_CAST(ScopeInfo)
3883 // Return the type of this scope.
3884 ScopeType scope_type();
3886 // Does this scope call eval?
3889 // Return the language mode of this scope.
3890 LanguageMode language_mode();
3892 // Does this scope make a sloppy eval call?
3893 bool CallsSloppyEval() { return CallsEval() && is_sloppy(language_mode()); }
3895 // Return the total number of locals allocated on the stack and in the
3896 // context. This includes the parameters that are allocated in the context.
3899 // Return the number of stack slots for code. This number consists of two
3901 // 1. One stack slot per stack allocated local.
3902 // 2. One stack slot for the function name if it is stack allocated.
3903 int StackSlotCount();
3905 // Return the number of context slots for code if a context is allocated. This
3906 // number consists of three parts:
3907 // 1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
3908 // 2. One context slot per context allocated local.
3909 // 3. One context slot for the function name if it is context allocated.
3910 // Parameters allocated in the context count as context allocated locals. If
3911 // no contexts are allocated for this scope ContextLength returns 0.
3912 int ContextLength();
3914 // Does this scope declare a "this" binding?
3917 // Does this scope declare a "this" binding, and the "this" binding is stack-
3918 // or context-allocated?
3919 bool HasAllocatedReceiver();
3921 // Is this scope the scope of a named function expression?
3922 bool HasFunctionName();
3924 // Return if this has context allocated locals.
3925 bool HasHeapAllocatedLocals();
3927 // Return if contexts are allocated for this scope.
3930 // Return if this is a function scope with "use asm".
3931 bool IsAsmModule() { return AsmModuleField::decode(Flags()); }
3933 // Return if this is a nested function within an asm module scope.
3934 bool IsAsmFunction() { return AsmFunctionField::decode(Flags()); }
3936 bool IsSimpleParameterList() {
3937 return IsSimpleParameterListField::decode(Flags());
3940 // Return the function_name if present.
3941 String* FunctionName();
3943 // Return the name of the given parameter.
3944 String* ParameterName(int var);
3946 // Return the name of the given local.
3947 String* LocalName(int var);
3949 // Return the name of the given stack local.
3950 String* StackLocalName(int var);
3952 // Return the name of the given stack local.
3953 int StackLocalIndex(int var);
3955 // Return the name of the given context local.
3956 String* ContextLocalName(int var);
3958 // Return the mode of the given context local.
3959 VariableMode ContextLocalMode(int var);
3961 // Return the initialization flag of the given context local.
3962 InitializationFlag ContextLocalInitFlag(int var);
3964 // Return the initialization flag of the given context local.
3965 MaybeAssignedFlag ContextLocalMaybeAssignedFlag(int var);
3967 // Return true if this local was introduced by the compiler, and should not be
3968 // exposed to the user in a debugger.
3969 bool LocalIsSynthetic(int var);
3971 String* StrongModeFreeVariableName(int var);
3972 int StrongModeFreeVariableStartPosition(int var);
3973 int StrongModeFreeVariableEndPosition(int var);
3975 // Lookup support for serialized scope info. Returns the
3976 // the stack slot index for a given slot name if the slot is
3977 // present; otherwise returns a value < 0. The name must be an internalized
3979 int StackSlotIndex(String* name);
3981 // Lookup support for serialized scope info. Returns the
3982 // context slot index for a given slot name if the slot is present; otherwise
3983 // returns a value < 0. The name must be an internalized string.
3984 // If the slot is present and mode != NULL, sets *mode to the corresponding
3985 // mode for that variable.
3986 static int ContextSlotIndex(Handle<ScopeInfo> scope_info, Handle<String> name,
3987 VariableMode* mode, VariableLocation* location,
3988 InitializationFlag* init_flag,
3989 MaybeAssignedFlag* maybe_assigned_flag);
3991 // Lookup support for serialized scope info. Returns the
3992 // parameter index for a given parameter name if the parameter is present;
3993 // otherwise returns a value < 0. The name must be an internalized string.
3994 int ParameterIndex(String* name);
3996 // Lookup support for serialized scope info. Returns the function context
3997 // slot index if the function name is present and context-allocated (named
3998 // function expressions, only), otherwise returns a value < 0. The name
3999 // must be an internalized string.
4000 int FunctionContextSlotIndex(String* name, VariableMode* mode);
4002 // Lookup support for serialized scope info. Returns the receiver context
4003 // slot index if scope has a "this" binding, and the binding is
4004 // context-allocated. Otherwise returns a value < 0.
4005 int ReceiverContextSlotIndex();
4007 FunctionKind function_kind();
4009 // Copies all the context locals into an object used to materialize a scope.
4010 static void CopyContextLocalsToScopeObject(Handle<ScopeInfo> scope_info,
4011 Handle<Context> context,
4012 Handle<JSObject> scope_object);
4015 static Handle<ScopeInfo> Create(Isolate* isolate, Zone* zone, Scope* scope);
4016 static Handle<ScopeInfo> CreateGlobalThisBinding(Isolate* isolate);
4018 // Serializes empty scope info.
4019 static ScopeInfo* Empty(Isolate* isolate);
4025 // The layout of the static part of a ScopeInfo is as follows. Each entry is
4026 // numeric and occupies one array slot.
4027 // 1. A set of properties of the scope
4028 // 2. The number of parameters. This only applies to function scopes. For
4029 // non-function scopes this is 0.
4030 // 3. The number of non-parameter variables allocated on the stack.
4031 // 4. The number of non-parameter and parameter variables allocated in the
4033 #define FOR_EACH_NUMERIC_FIELD(V) \
4036 V(StackLocalCount) \
4037 V(ContextLocalCount) \
4038 V(ContextGlobalCount) \
4039 V(StrongModeFreeVariableCount)
4041 #define FIELD_ACCESSORS(name) \
4042 void Set##name(int value) { \
4043 set(k##name, Smi::FromInt(value)); \
4046 if (length() > 0) { \
4047 return Smi::cast(get(k##name))->value(); \
4052 FOR_EACH_NUMERIC_FIELD(FIELD_ACCESSORS)
4053 #undef FIELD_ACCESSORS
4057 #define DECL_INDEX(name) k##name,
4058 FOR_EACH_NUMERIC_FIELD(DECL_INDEX)
4060 #undef FOR_EACH_NUMERIC_FIELD
4064 // The layout of the variable part of a ScopeInfo is as follows:
4065 // 1. ParameterEntries:
4066 // This part stores the names of the parameters for function scopes. One
4067 // slot is used per parameter, so in total this part occupies
4068 // ParameterCount() slots in the array. For other scopes than function
4069 // scopes ParameterCount() is 0.
4070 // 2. StackLocalFirstSlot:
4071 // Index of a first stack slot for stack local. Stack locals belonging to
4072 // this scope are located on a stack at slots starting from this index.
4073 // 3. StackLocalEntries:
4074 // Contains the names of local variables that are allocated on the stack,
4075 // in increasing order of the stack slot index. First local variable has
4076 // a stack slot index defined in StackLocalFirstSlot (point 2 above).
4077 // One slot is used per stack local, so in total this part occupies
4078 // StackLocalCount() slots in the array.
4079 // 4. ContextLocalNameEntries:
4080 // Contains the names of local variables and parameters that are allocated
4081 // in the context. They are stored in increasing order of the context slot
4082 // index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
4083 // context local, so in total this part occupies ContextLocalCount() slots
4085 // 5. ContextLocalInfoEntries:
4086 // Contains the variable modes and initialization flags corresponding to
4087 // the context locals in ContextLocalNameEntries. One slot is used per
4088 // context local, so in total this part occupies ContextLocalCount()
4089 // slots in the array.
4090 // 6. StrongModeFreeVariableNameEntries:
4091 // Stores the names of strong mode free variables.
4092 // 7. StrongModeFreeVariablePositionEntries:
4093 // Stores the locations (start and end position) of strong mode free
4095 // 8. RecieverEntryIndex:
4096 // If the scope binds a "this" value, one slot is reserved to hold the
4097 // context or stack slot index for the variable.
4098 // 9. FunctionNameEntryIndex:
4099 // If the scope belongs to a named function expression this part contains
4100 // information about the function variable. It always occupies two array
4101 // slots: a. The name of the function variable.
4102 // b. The context or stack slot index for the variable.
4103 int ParameterEntriesIndex();
4104 int StackLocalFirstSlotIndex();
4105 int StackLocalEntriesIndex();
4106 int ContextLocalNameEntriesIndex();
4107 int ContextGlobalNameEntriesIndex();
4108 int ContextLocalInfoEntriesIndex();
4109 int ContextGlobalInfoEntriesIndex();
4110 int StrongModeFreeVariableNameEntriesIndex();
4111 int StrongModeFreeVariablePositionEntriesIndex();
4112 int ReceiverEntryIndex();
4113 int FunctionNameEntryIndex();
4115 int Lookup(Handle<String> name, int start, int end, VariableMode* mode,
4116 VariableLocation* location, InitializationFlag* init_flag,
4117 MaybeAssignedFlag* maybe_assigned_flag);
4119 // Used for the function name variable for named function expressions, and for
4121 enum VariableAllocationInfo { NONE, STACK, CONTEXT, UNUSED };
4123 // Properties of scopes.
4124 class ScopeTypeField : public BitField<ScopeType, 0, 4> {};
4125 class CallsEvalField : public BitField<bool, ScopeTypeField::kNext, 1> {};
4126 STATIC_ASSERT(LANGUAGE_END == 3);
4127 class LanguageModeField
4128 : public BitField<LanguageMode, CallsEvalField::kNext, 2> {};
4129 class ReceiverVariableField
4130 : public BitField<VariableAllocationInfo, LanguageModeField::kNext, 2> {};
4131 class FunctionVariableField
4132 : public BitField<VariableAllocationInfo, ReceiverVariableField::kNext,
4134 class FunctionVariableMode
4135 : public BitField<VariableMode, FunctionVariableField::kNext, 3> {};
4136 class AsmModuleField : public BitField<bool, FunctionVariableMode::kNext, 1> {
4138 class AsmFunctionField : public BitField<bool, AsmModuleField::kNext, 1> {};
4139 class IsSimpleParameterListField
4140 : public BitField<bool, AsmFunctionField::kNext, 1> {};
4141 class FunctionKindField
4142 : public BitField<FunctionKind, IsSimpleParameterListField::kNext, 8> {};
4144 // BitFields representing the encoded information for context locals in the
4145 // ContextLocalInfoEntries part.
4146 class ContextLocalMode: public BitField<VariableMode, 0, 3> {};
4147 class ContextLocalInitFlag: public BitField<InitializationFlag, 3, 1> {};
4148 class ContextLocalMaybeAssignedFlag
4149 : public BitField<MaybeAssignedFlag, 4, 1> {};
4153 // The cache for maps used by normalized (dictionary mode) objects.
4154 // Such maps do not have property descriptors, so a typical program
4155 // needs very limited number of distinct normalized maps.
4156 class NormalizedMapCache: public FixedArray {
4158 static Handle<NormalizedMapCache> New(Isolate* isolate);
4160 MUST_USE_RESULT MaybeHandle<Map> Get(Handle<Map> fast_map,
4161 PropertyNormalizationMode mode);
4162 void Set(Handle<Map> fast_map, Handle<Map> normalized_map);
4166 DECLARE_CAST(NormalizedMapCache)
4168 static inline bool IsNormalizedMapCache(const Object* obj);
4170 DECLARE_VERIFIER(NormalizedMapCache)
4172 static const int kEntries = 64;
4174 static inline int GetIndex(Handle<Map> map);
4176 // The following declarations hide base class methods.
4177 Object* get(int index);
4178 void set(int index, Object* value);
4182 // ByteArray represents fixed sized byte arrays. Used for the relocation info
4183 // that is attached to code objects.
4184 class ByteArray: public FixedArrayBase {
4186 inline int Size() { return RoundUp(length() + kHeaderSize, kPointerSize); }
4188 // Setter and getter.
4189 inline byte get(int index);
4190 inline void set(int index, byte value);
4192 // Treat contents as an int array.
4193 inline int get_int(int index);
4195 static int SizeFor(int length) {
4196 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4198 // We use byte arrays for free blocks in the heap. Given a desired size in
4199 // bytes that is a multiple of the word size and big enough to hold a byte
4200 // array, this function returns the number of elements a byte array should
4202 static int LengthFor(int size_in_bytes) {
4203 DCHECK(IsAligned(size_in_bytes, kPointerSize));
4204 DCHECK(size_in_bytes >= kHeaderSize);
4205 return size_in_bytes - kHeaderSize;
4208 // Returns data start address.
4209 inline Address GetDataStartAddress();
4211 // Returns a pointer to the ByteArray object for a given data start address.
4212 static inline ByteArray* FromDataStartAddress(Address address);
4214 DECLARE_CAST(ByteArray)
4216 // Dispatched behavior.
4217 inline int ByteArraySize() {
4218 return SizeFor(this->length());
4220 DECLARE_PRINTER(ByteArray)
4221 DECLARE_VERIFIER(ByteArray)
4223 // Layout description.
4224 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4226 // Maximal memory consumption for a single ByteArray.
4227 static const int kMaxSize = 512 * MB;
4228 // Maximal length of a single ByteArray.
4229 static const int kMaxLength = kMaxSize - kHeaderSize;
4232 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4236 // FreeSpace are fixed-size free memory blocks used by the heap and GC.
4237 // They look like heap objects (are heap object tagged and have a map) so that
4238 // the heap remains iterable. They have a size and a next pointer.
4239 // The next pointer is the raw address of the next FreeSpace object (or NULL)
4240 // in the free list.
4241 class FreeSpace: public HeapObject {
4243 // [size]: size of the free space including the header.
4244 inline int size() const;
4245 inline void set_size(int value);
4247 inline int nobarrier_size() const;
4248 inline void nobarrier_set_size(int value);
4250 inline int Size() { return size(); }
4252 // Accessors for the next field.
4253 inline FreeSpace* next();
4254 inline FreeSpace** next_address();
4255 inline void set_next(FreeSpace* next);
4257 inline static FreeSpace* cast(HeapObject* obj);
4259 // Dispatched behavior.
4260 DECLARE_PRINTER(FreeSpace)
4261 DECLARE_VERIFIER(FreeSpace)
4263 // Layout description.
4264 // Size is smi tagged when it is stored.
4265 static const int kSizeOffset = HeapObject::kHeaderSize;
4266 static const int kNextOffset = POINTER_SIZE_ALIGN(kSizeOffset + kPointerSize);
4269 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
4273 // V has parameters (Type, type, TYPE, C type, element_size)
4274 #define TYPED_ARRAYS(V) \
4275 V(Uint8, uint8, UINT8, uint8_t, 1) \
4276 V(Int8, int8, INT8, int8_t, 1) \
4277 V(Uint16, uint16, UINT16, uint16_t, 2) \
4278 V(Int16, int16, INT16, int16_t, 2) \
4279 V(Uint32, uint32, UINT32, uint32_t, 4) \
4280 V(Int32, int32, INT32, int32_t, 4) \
4281 V(Float32, float32, FLOAT32, float, 4) \
4282 V(Float64, float64, FLOAT64, double, 8) \
4283 V(Uint8Clamped, uint8_clamped, UINT8_CLAMPED, uint8_t, 1)
4287 // An ExternalArray represents a fixed-size array of primitive values
4288 // which live outside the JavaScript heap. Its subclasses are used to
4289 // implement the CanvasArray types being defined in the WebGL
4290 // specification. As of this writing the first public draft is not yet
4291 // available, but Khronos members can access the draft at:
4292 // https://cvs.khronos.org/svn/repos/3dweb/trunk/doc/spec/WebGL-spec.html
4294 // The semantics of these arrays differ from CanvasPixelArray.
4295 // Out-of-range values passed to the setter are converted via a C
4296 // cast, not clamping. Out-of-range indices cause exceptions to be
4297 // raised rather than being silently ignored.
4298 class ExternalArray: public FixedArrayBase {
4300 inline bool is_the_hole(int index) { return false; }
4302 // [external_pointer]: The pointer to the external memory area backing this
4304 DECL_ACCESSORS(external_pointer, void) // Pointer to the data store.
4306 DECLARE_CAST(ExternalArray)
4308 // Maximal acceptable length for an external array.
4309 static const int kMaxLength = 0x3fffffff;
4311 // ExternalArray headers are not quadword aligned.
4312 static const int kExternalPointerOffset =
4313 POINTER_SIZE_ALIGN(FixedArrayBase::kLengthOffset + kPointerSize);
4314 static const int kSize = kExternalPointerOffset + kPointerSize;
4317 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalArray);
4321 // A ExternalUint8ClampedArray represents a fixed-size byte array with special
4322 // semantics used for implementing the CanvasPixelArray object. Please see the
4323 // specification at:
4325 // http://www.whatwg.org/specs/web-apps/current-work/
4326 // multipage/the-canvas-element.html#canvaspixelarray
4327 // In particular, write access clamps the value written to 0 or 255 if the
4328 // value written is outside this range.
4329 class ExternalUint8ClampedArray: public ExternalArray {
4331 inline uint8_t* external_uint8_clamped_pointer();
4333 // Setter and getter.
4334 inline uint8_t get_scalar(int index);
4335 static inline Handle<Object> get(Handle<ExternalUint8ClampedArray> array,
4337 inline void set(int index, uint8_t value);
4339 // This accessor applies the correct conversion from Smi, HeapNumber
4340 // and undefined and clamps the converted value between 0 and 255.
4341 void SetValue(uint32_t index, Object* value);
4343 DECLARE_CAST(ExternalUint8ClampedArray)
4345 // Dispatched behavior.
4346 DECLARE_PRINTER(ExternalUint8ClampedArray)
4347 DECLARE_VERIFIER(ExternalUint8ClampedArray)
4350 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint8ClampedArray);
4354 class ExternalInt8Array: public ExternalArray {
4356 // Setter and getter.
4357 inline int8_t get_scalar(int index);
4358 static inline Handle<Object> get(Handle<ExternalInt8Array> array, int index);
4359 inline void set(int index, int8_t value);
4361 // This accessor applies the correct conversion from Smi, HeapNumber
4363 void SetValue(uint32_t index, Object* value);
4365 DECLARE_CAST(ExternalInt8Array)
4367 // Dispatched behavior.
4368 DECLARE_PRINTER(ExternalInt8Array)
4369 DECLARE_VERIFIER(ExternalInt8Array)
4372 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt8Array);
4376 class ExternalUint8Array: public ExternalArray {
4378 // Setter and getter.
4379 inline uint8_t get_scalar(int index);
4380 static inline Handle<Object> get(Handle<ExternalUint8Array> array, int index);
4381 inline void set(int index, uint8_t value);
4383 // This accessor applies the correct conversion from Smi, HeapNumber
4385 void SetValue(uint32_t index, Object* value);
4387 DECLARE_CAST(ExternalUint8Array)
4389 // Dispatched behavior.
4390 DECLARE_PRINTER(ExternalUint8Array)
4391 DECLARE_VERIFIER(ExternalUint8Array)
4394 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint8Array);
4398 class ExternalInt16Array: public ExternalArray {
4400 // Setter and getter.
4401 inline int16_t get_scalar(int index);
4402 static inline Handle<Object> get(Handle<ExternalInt16Array> array, int index);
4403 inline void set(int index, int16_t value);
4405 // This accessor applies the correct conversion from Smi, HeapNumber
4407 void SetValue(uint32_t index, Object* value);
4409 DECLARE_CAST(ExternalInt16Array)
4411 // Dispatched behavior.
4412 DECLARE_PRINTER(ExternalInt16Array)
4413 DECLARE_VERIFIER(ExternalInt16Array)
4416 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt16Array);
4420 class ExternalUint16Array: public ExternalArray {
4422 // Setter and getter.
4423 inline uint16_t get_scalar(int index);
4424 static inline Handle<Object> get(Handle<ExternalUint16Array> array,
4426 inline void set(int index, uint16_t value);
4428 // This accessor applies the correct conversion from Smi, HeapNumber
4430 void SetValue(uint32_t index, Object* value);
4432 DECLARE_CAST(ExternalUint16Array)
4434 // Dispatched behavior.
4435 DECLARE_PRINTER(ExternalUint16Array)
4436 DECLARE_VERIFIER(ExternalUint16Array)
4439 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint16Array);
4443 class ExternalInt32Array: public ExternalArray {
4445 // Setter and getter.
4446 inline int32_t get_scalar(int index);
4447 static inline Handle<Object> get(Handle<ExternalInt32Array> array, int index);
4448 inline void set(int index, int32_t value);
4450 // This accessor applies the correct conversion from Smi, HeapNumber
4452 void SetValue(uint32_t index, Object* value);
4454 DECLARE_CAST(ExternalInt32Array)
4456 // Dispatched behavior.
4457 DECLARE_PRINTER(ExternalInt32Array)
4458 DECLARE_VERIFIER(ExternalInt32Array)
4461 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt32Array);
4465 class ExternalUint32Array: public ExternalArray {
4467 // Setter and getter.
4468 inline uint32_t get_scalar(int index);
4469 static inline Handle<Object> get(Handle<ExternalUint32Array> array,
4471 inline void set(int index, uint32_t value);
4473 // This accessor applies the correct conversion from Smi, HeapNumber
4475 void SetValue(uint32_t index, Object* value);
4477 DECLARE_CAST(ExternalUint32Array)
4479 // Dispatched behavior.
4480 DECLARE_PRINTER(ExternalUint32Array)
4481 DECLARE_VERIFIER(ExternalUint32Array)
4484 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint32Array);
4488 class ExternalFloat32Array: public ExternalArray {
4490 // Setter and getter.
4491 inline float get_scalar(int index);
4492 static inline Handle<Object> get(Handle<ExternalFloat32Array> array,
4494 inline void set(int index, float value);
4496 // This accessor applies the correct conversion from Smi, HeapNumber
4498 void SetValue(uint32_t index, Object* value);
4500 DECLARE_CAST(ExternalFloat32Array)
4502 // Dispatched behavior.
4503 DECLARE_PRINTER(ExternalFloat32Array)
4504 DECLARE_VERIFIER(ExternalFloat32Array)
4507 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalFloat32Array);
4511 class ExternalFloat64Array: public ExternalArray {
4513 // Setter and getter.
4514 inline double get_scalar(int index);
4515 static inline Handle<Object> get(Handle<ExternalFloat64Array> array,
4517 inline void set(int index, double value);
4519 // This accessor applies the correct conversion from Smi, HeapNumber
4521 void SetValue(uint32_t index, Object* value);
4523 DECLARE_CAST(ExternalFloat64Array)
4525 // Dispatched behavior.
4526 DECLARE_PRINTER(ExternalFloat64Array)
4527 DECLARE_VERIFIER(ExternalFloat64Array)
4530 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalFloat64Array);
4534 class FixedTypedArrayBase: public FixedArrayBase {
4536 // [base_pointer]: For now, points to the FixedTypedArrayBase itself.
4537 DECL_ACCESSORS(base_pointer, Object)
4539 // Dispatched behavior.
4540 inline void FixedTypedArrayBaseIterateBody(ObjectVisitor* v);
4542 template <typename StaticVisitor>
4543 inline void FixedTypedArrayBaseIterateBody();
4545 DECLARE_CAST(FixedTypedArrayBase)
4547 static const int kBasePointerOffset =
4548 FixedArrayBase::kHeaderSize + kPointerSize;
4549 static const int kHeaderSize = kBasePointerOffset + kPointerSize;
4551 static const int kDataOffset = DOUBLE_POINTER_ALIGN(kHeaderSize);
4555 static inline int TypedArraySize(InstanceType type, int length);
4556 inline int TypedArraySize(InstanceType type);
4558 // Use with care: returns raw pointer into heap.
4559 inline void* DataPtr();
4561 inline int DataSize();
4564 static inline int ElementSize(InstanceType type);
4566 inline int DataSize(InstanceType type);
4568 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
4572 template <class Traits>
4573 class FixedTypedArray: public FixedTypedArrayBase {
4575 typedef typename Traits::ElementType ElementType;
4576 static const InstanceType kInstanceType = Traits::kInstanceType;
4578 DECLARE_CAST(FixedTypedArray<Traits>)
4580 inline ElementType get_scalar(int index);
4581 static inline Handle<Object> get(Handle<FixedTypedArray> array, int index);
4582 inline void set(int index, ElementType value);
4584 static inline ElementType from_int(int value);
4585 static inline ElementType from_double(double value);
4587 // This accessor applies the correct conversion from Smi, HeapNumber
4589 void SetValue(uint32_t index, Object* value);
4591 DECLARE_PRINTER(FixedTypedArray)
4592 DECLARE_VERIFIER(FixedTypedArray)
4595 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
4598 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size) \
4599 class Type##ArrayTraits { \
4600 public: /* NOLINT */ \
4601 typedef elementType ElementType; \
4602 static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE; \
4603 static const char* Designator() { return #type " array"; } \
4604 static inline Handle<Object> ToHandle(Isolate* isolate, \
4605 elementType scalar); \
4606 static inline elementType defaultValue(); \
4609 typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
4611 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
4613 #undef FIXED_TYPED_ARRAY_TRAITS
4616 // DeoptimizationInputData is a fixed array used to hold the deoptimization
4617 // data for code generated by the Hydrogen/Lithium compiler. It also
4618 // contains information about functions that were inlined. If N different
4619 // functions were inlined then first N elements of the literal array will
4620 // contain these functions.
4623 class DeoptimizationInputData: public FixedArray {
4625 // Layout description. Indices in the array.
4626 static const int kTranslationByteArrayIndex = 0;
4627 static const int kInlinedFunctionCountIndex = 1;
4628 static const int kLiteralArrayIndex = 2;
4629 static const int kOsrAstIdIndex = 3;
4630 static const int kOsrPcOffsetIndex = 4;
4631 static const int kOptimizationIdIndex = 5;
4632 static const int kSharedFunctionInfoIndex = 6;
4633 static const int kWeakCellCacheIndex = 7;
4634 static const int kFirstDeoptEntryIndex = 8;
4636 // Offsets of deopt entry elements relative to the start of the entry.
4637 static const int kAstIdRawOffset = 0;
4638 static const int kTranslationIndexOffset = 1;
4639 static const int kArgumentsStackHeightOffset = 2;
4640 static const int kPcOffset = 3;
4641 static const int kDeoptEntrySize = 4;
4643 // Simple element accessors.
4644 #define DEFINE_ELEMENT_ACCESSORS(name, type) \
4646 return type::cast(get(k##name##Index)); \
4648 void Set##name(type* value) { \
4649 set(k##name##Index, value); \
4652 DEFINE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
4653 DEFINE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
4654 DEFINE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
4655 DEFINE_ELEMENT_ACCESSORS(OsrAstId, Smi)
4656 DEFINE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
4657 DEFINE_ELEMENT_ACCESSORS(OptimizationId, Smi)
4658 DEFINE_ELEMENT_ACCESSORS(SharedFunctionInfo, Object)
4659 DEFINE_ELEMENT_ACCESSORS(WeakCellCache, Object)
4661 #undef DEFINE_ELEMENT_ACCESSORS
4663 // Accessors for elements of the ith deoptimization entry.
4664 #define DEFINE_ENTRY_ACCESSORS(name, type) \
4665 type* name(int i) { \
4666 return type::cast(get(IndexForEntry(i) + k##name##Offset)); \
4668 void Set##name(int i, type* value) { \
4669 set(IndexForEntry(i) + k##name##Offset, value); \
4672 DEFINE_ENTRY_ACCESSORS(AstIdRaw, Smi)
4673 DEFINE_ENTRY_ACCESSORS(TranslationIndex, Smi)
4674 DEFINE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
4675 DEFINE_ENTRY_ACCESSORS(Pc, Smi)
4677 #undef DEFINE_DEOPT_ENTRY_ACCESSORS
4679 BailoutId AstId(int i) {
4680 return BailoutId(AstIdRaw(i)->value());
4683 void SetAstId(int i, BailoutId value) {
4684 SetAstIdRaw(i, Smi::FromInt(value.ToInt()));
4688 return (length() - kFirstDeoptEntryIndex) / kDeoptEntrySize;
4691 // Allocates a DeoptimizationInputData.
4692 static Handle<DeoptimizationInputData> New(Isolate* isolate,
4693 int deopt_entry_count,
4694 PretenureFlag pretenure);
4696 DECLARE_CAST(DeoptimizationInputData)
4698 #ifdef ENABLE_DISASSEMBLER
4699 void DeoptimizationInputDataPrint(std::ostream& os); // NOLINT
4703 static int IndexForEntry(int i) {
4704 return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
4708 static int LengthFor(int entry_count) { return IndexForEntry(entry_count); }
4712 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
4713 // data for code generated by the full compiler.
4714 // The format of the these objects is
4715 // [i * 2]: Ast ID for ith deoptimization.
4716 // [i * 2 + 1]: PC and state of ith deoptimization
4717 class DeoptimizationOutputData: public FixedArray {
4719 int DeoptPoints() { return length() / 2; }
4721 BailoutId AstId(int index) {
4722 return BailoutId(Smi::cast(get(index * 2))->value());
4725 void SetAstId(int index, BailoutId id) {
4726 set(index * 2, Smi::FromInt(id.ToInt()));
4729 Smi* PcAndState(int index) { return Smi::cast(get(1 + index * 2)); }
4730 void SetPcAndState(int index, Smi* offset) { set(1 + index * 2, offset); }
4732 static int LengthOfFixedArray(int deopt_points) {
4733 return deopt_points * 2;
4736 // Allocates a DeoptimizationOutputData.
4737 static Handle<DeoptimizationOutputData> New(Isolate* isolate,
4738 int number_of_deopt_points,
4739 PretenureFlag pretenure);
4741 DECLARE_CAST(DeoptimizationOutputData)
4743 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4744 void DeoptimizationOutputDataPrint(std::ostream& os); // NOLINT
4749 // HandlerTable is a fixed array containing entries for exception handlers in
4750 // the code object it is associated with. The tables comes in two flavors:
4751 // 1) Based on ranges: Used for unoptimized code. Contains one entry per
4752 // exception handler and a range representing the try-block covered by that
4753 // handler. Layout looks as follows:
4754 // [ range-start , range-end , handler-offset , stack-depth ]
4755 // 2) Based on return addresses: Used for turbofanned code. Contains one entry
4756 // per call-site that could throw an exception. Layout looks as follows:
4757 // [ return-address-offset , handler-offset ]
4758 class HandlerTable : public FixedArray {
4760 // Conservative prediction whether a given handler will locally catch an
4761 // exception or cause a re-throw to outside the code boundary. Since this is
4762 // undecidable it is merely an approximation (e.g. useful for debugger).
4763 enum CatchPrediction { UNCAUGHT, CAUGHT };
4765 // Accessors for handler table based on ranges.
4766 void SetRangeStart(int index, int value) {
4767 set(index * kRangeEntrySize + kRangeStartIndex, Smi::FromInt(value));
4769 void SetRangeEnd(int index, int value) {
4770 set(index * kRangeEntrySize + kRangeEndIndex, Smi::FromInt(value));
4772 void SetRangeHandler(int index, int offset, CatchPrediction prediction) {
4773 int value = HandlerOffsetField::encode(offset) |
4774 HandlerPredictionField::encode(prediction);
4775 set(index * kRangeEntrySize + kRangeHandlerIndex, Smi::FromInt(value));
4777 void SetRangeDepth(int index, int value) {
4778 set(index * kRangeEntrySize + kRangeDepthIndex, Smi::FromInt(value));
4781 // Accessors for handler table based on return addresses.
4782 void SetReturnOffset(int index, int value) {
4783 set(index * kReturnEntrySize + kReturnOffsetIndex, Smi::FromInt(value));
4785 void SetReturnHandler(int index, int offset, CatchPrediction prediction) {
4786 int value = HandlerOffsetField::encode(offset) |
4787 HandlerPredictionField::encode(prediction);
4788 set(index * kReturnEntrySize + kReturnHandlerIndex, Smi::FromInt(value));
4791 // Lookup handler in a table based on ranges.
4792 int LookupRange(int pc_offset, int* stack_depth, CatchPrediction* prediction);
4794 // Lookup handler in a table based on return addresses.
4795 int LookupReturn(int pc_offset, CatchPrediction* prediction);
4797 // Returns the required length of the underlying fixed array.
4798 static int LengthForRange(int entries) { return entries * kRangeEntrySize; }
4799 static int LengthForReturn(int entries) { return entries * kReturnEntrySize; }
4801 DECLARE_CAST(HandlerTable)
4803 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4804 void HandlerTableRangePrint(std::ostream& os); // NOLINT
4805 void HandlerTableReturnPrint(std::ostream& os); // NOLINT
4809 // Layout description for handler table based on ranges.
4810 static const int kRangeStartIndex = 0;
4811 static const int kRangeEndIndex = 1;
4812 static const int kRangeHandlerIndex = 2;
4813 static const int kRangeDepthIndex = 3;
4814 static const int kRangeEntrySize = 4;
4816 // Layout description for handler table based on return addresses.
4817 static const int kReturnOffsetIndex = 0;
4818 static const int kReturnHandlerIndex = 1;
4819 static const int kReturnEntrySize = 2;
4821 // Encoding of the {handler} field.
4822 class HandlerPredictionField : public BitField<CatchPrediction, 0, 1> {};
4823 class HandlerOffsetField : public BitField<int, 1, 30> {};
4827 // Code describes objects with on-the-fly generated machine code.
4828 class Code: public HeapObject {
4830 // Opaque data type for encapsulating code flags like kind, inline
4831 // cache state, and arguments count.
4832 typedef uint32_t Flags;
4834 #define NON_IC_KIND_LIST(V) \
4836 V(OPTIMIZED_FUNCTION) \
4842 #define IC_KIND_LIST(V) \
4853 #define CODE_KIND_LIST(V) \
4854 NON_IC_KIND_LIST(V) \
4858 #define DEFINE_CODE_KIND_ENUM(name) name,
4859 CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
4860 #undef DEFINE_CODE_KIND_ENUM
4864 // No more than 16 kinds. The value is currently encoded in four bits in
4866 STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
4868 static const char* Kind2String(Kind kind);
4876 static const int kPrologueOffsetNotSet = -1;
4878 #ifdef ENABLE_DISASSEMBLER
4880 static const char* ICState2String(InlineCacheState state);
4881 static const char* StubType2String(StubType type);
4882 static void PrintExtraICState(std::ostream& os, // NOLINT
4883 Kind kind, ExtraICState extra);
4884 void Disassemble(const char* name, std::ostream& os); // NOLINT
4885 #endif // ENABLE_DISASSEMBLER
4887 // [instruction_size]: Size of the native instructions
4888 inline int instruction_size() const;
4889 inline void set_instruction_size(int value);
4891 // [relocation_info]: Code relocation information
4892 DECL_ACCESSORS(relocation_info, ByteArray)
4893 void InvalidateRelocation();
4894 void InvalidateEmbeddedObjects();
4896 // [handler_table]: Fixed array containing offsets of exception handlers.
4897 DECL_ACCESSORS(handler_table, FixedArray)
4899 // [deoptimization_data]: Array containing data for deopt.
4900 DECL_ACCESSORS(deoptimization_data, FixedArray)
4902 // [raw_type_feedback_info]: This field stores various things, depending on
4903 // the kind of the code object.
4904 // FUNCTION => type feedback information.
4905 // STUB and ICs => major/minor key as Smi.
4906 DECL_ACCESSORS(raw_type_feedback_info, Object)
4907 inline Object* type_feedback_info();
4908 inline void set_type_feedback_info(
4909 Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
4910 inline uint32_t stub_key();
4911 inline void set_stub_key(uint32_t key);
4913 // [next_code_link]: Link for lists of optimized or deoptimized code.
4914 // Note that storage for this field is overlapped with typefeedback_info.
4915 DECL_ACCESSORS(next_code_link, Object)
4917 // [gc_metadata]: Field used to hold GC related metadata. The contents of this
4918 // field does not have to be traced during garbage collection since
4919 // it is only used by the garbage collector itself.
4920 DECL_ACCESSORS(gc_metadata, Object)
4922 // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
4923 // at the moment when this object was created.
4924 inline void set_ic_age(int count);
4925 inline int ic_age() const;
4927 // [prologue_offset]: Offset of the function prologue, used for aging
4928 // FUNCTIONs and OPTIMIZED_FUNCTIONs.
4929 inline int prologue_offset() const;
4930 inline void set_prologue_offset(int offset);
4932 // [constant_pool offset]: Offset of the constant pool.
4933 // Valid for FLAG_enable_embedded_constant_pool only
4934 inline int constant_pool_offset() const;
4935 inline void set_constant_pool_offset(int offset);
4937 // Unchecked accessors to be used during GC.
4938 inline ByteArray* unchecked_relocation_info();
4940 inline int relocation_size();
4942 // [flags]: Various code flags.
4943 inline Flags flags();
4944 inline void set_flags(Flags flags);
4946 // [flags]: Access to specific code flags.
4948 inline InlineCacheState ic_state(); // Only valid for IC stubs.
4949 inline ExtraICState extra_ic_state(); // Only valid for IC stubs.
4951 inline StubType type(); // Only valid for monomorphic IC stubs.
4953 // Testers for IC stub kinds.
4954 inline bool is_inline_cache_stub();
4955 inline bool is_debug_stub();
4956 inline bool is_handler() { return kind() == HANDLER; }
4957 inline bool is_load_stub() { return kind() == LOAD_IC; }
4958 inline bool is_keyed_load_stub() { return kind() == KEYED_LOAD_IC; }
4959 inline bool is_store_stub() { return kind() == STORE_IC; }
4960 inline bool is_keyed_store_stub() { return kind() == KEYED_STORE_IC; }
4961 inline bool is_call_stub() { return kind() == CALL_IC; }
4962 inline bool is_binary_op_stub() { return kind() == BINARY_OP_IC; }
4963 inline bool is_compare_ic_stub() { return kind() == COMPARE_IC; }
4964 inline bool is_compare_nil_ic_stub() { return kind() == COMPARE_NIL_IC; }
4965 inline bool is_to_boolean_ic_stub() { return kind() == TO_BOOLEAN_IC; }
4966 inline bool is_keyed_stub();
4967 inline bool is_optimized_code() { return kind() == OPTIMIZED_FUNCTION; }
4968 inline bool embeds_maps_weakly() {
4970 return (k == LOAD_IC || k == STORE_IC || k == KEYED_LOAD_IC ||
4971 k == KEYED_STORE_IC || k == COMPARE_NIL_IC) &&
4972 ic_state() == MONOMORPHIC;
4975 inline bool IsCodeStubOrIC();
4977 inline void set_raw_kind_specific_flags1(int value);
4978 inline void set_raw_kind_specific_flags2(int value);
4980 // [is_crankshafted]: For kind STUB or ICs, tells whether or not a code
4981 // object was generated by either the hydrogen or the TurboFan optimizing
4982 // compiler (but it may not be an optimized function).
4983 inline bool is_crankshafted();
4984 inline bool is_hydrogen_stub(); // Crankshafted, but not a function.
4985 inline void set_is_crankshafted(bool value);
4987 // [is_turbofanned]: For kind STUB or OPTIMIZED_FUNCTION, tells whether the
4988 // code object was generated by the TurboFan optimizing compiler.
4989 inline bool is_turbofanned();
4990 inline void set_is_turbofanned(bool value);
4992 // [can_have_weak_objects]: For kind OPTIMIZED_FUNCTION, tells whether the
4993 // embedded objects in code should be treated weakly.
4994 inline bool can_have_weak_objects();
4995 inline void set_can_have_weak_objects(bool value);
4997 // [has_deoptimization_support]: For FUNCTION kind, tells if it has
4998 // deoptimization support.
4999 inline bool has_deoptimization_support();
5000 inline void set_has_deoptimization_support(bool value);
5002 // [has_debug_break_slots]: For FUNCTION kind, tells if it has
5003 // been compiled with debug break slots.
5004 inline bool has_debug_break_slots();
5005 inline void set_has_debug_break_slots(bool value);
5007 // [compiled_with_optimizing]: For FUNCTION kind, tells if it has
5008 // been compiled with IsOptimizing set to true.
5009 inline bool is_compiled_optimizable();
5010 inline void set_compiled_optimizable(bool value);
5012 // [has_reloc_info_for_serialization]: For FUNCTION kind, tells if its
5013 // reloc info includes runtime and external references to support
5014 // serialization/deserialization.
5015 inline bool has_reloc_info_for_serialization();
5016 inline void set_has_reloc_info_for_serialization(bool value);
5018 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
5019 // how long the function has been marked for OSR and therefore which
5020 // level of loop nesting we are willing to do on-stack replacement
5022 inline void set_allow_osr_at_loop_nesting_level(int level);
5023 inline int allow_osr_at_loop_nesting_level();
5025 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
5026 // the code object was seen on the stack with no IC patching going on.
5027 inline int profiler_ticks();
5028 inline void set_profiler_ticks(int ticks);
5030 // [builtin_index]: For BUILTIN kind, tells which builtin index it has.
5031 // For builtins, tells which builtin index it has.
5032 // Note that builtins can have a code kind other than BUILTIN, which means
5033 // that for arbitrary code objects, this index value may be random garbage.
5034 // To verify in that case, compare the code object to the indexed builtin.
5035 inline int builtin_index();
5036 inline void set_builtin_index(int id);
5038 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
5039 // reserved in the code prologue.
5040 inline unsigned stack_slots();
5041 inline void set_stack_slots(unsigned slots);
5043 // [safepoint_table_start]: For kind OPTIMIZED_FUNCTION, the offset in
5044 // the instruction stream where the safepoint table starts.
5045 inline unsigned safepoint_table_offset();
5046 inline void set_safepoint_table_offset(unsigned offset);
5048 // [back_edge_table_start]: For kind FUNCTION, the offset in the
5049 // instruction stream where the back edge table starts.
5050 inline unsigned back_edge_table_offset();
5051 inline void set_back_edge_table_offset(unsigned offset);
5053 inline bool back_edges_patched_for_osr();
5055 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
5056 inline uint16_t to_boolean_state();
5058 // [has_function_cache]: For kind STUB tells whether there is a function
5059 // cache is passed to the stub.
5060 inline bool has_function_cache();
5061 inline void set_has_function_cache(bool flag);
5064 // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
5065 // the code is going to be deoptimized because of dead embedded maps.
5066 inline bool marked_for_deoptimization();
5067 inline void set_marked_for_deoptimization(bool flag);
5069 // [constant_pool]: The constant pool for this function.
5070 inline Address constant_pool();
5072 // Get the safepoint entry for the given pc.
5073 SafepointEntry GetSafepointEntry(Address pc);
5075 // Find an object in a stub with a specified map
5076 Object* FindNthObject(int n, Map* match_map);
5078 // Find the first allocation site in an IC stub.
5079 AllocationSite* FindFirstAllocationSite();
5081 // Find the first map in an IC stub.
5082 Map* FindFirstMap();
5083 void FindAllMaps(MapHandleList* maps);
5085 // Find the first handler in an IC stub.
5086 Code* FindFirstHandler();
5088 // Find |length| handlers and put them into |code_list|. Returns false if not
5089 // enough handlers can be found.
5090 bool FindHandlers(CodeHandleList* code_list, int length = -1);
5092 // Find the handler for |map|.
5093 MaybeHandle<Code> FindHandlerForMap(Map* map);
5095 // Find the first name in an IC stub.
5096 Name* FindFirstName();
5098 class FindAndReplacePattern;
5099 // For each (map-to-find, object-to-replace) pair in the pattern, this
5100 // function replaces the corresponding placeholder in the code with the
5101 // object-to-replace. The function assumes that pairs in the pattern come in
5102 // the same order as the placeholders in the code.
5103 // If the placeholder is a weak cell, then the value of weak cell is matched
5104 // against the map-to-find.
5105 void FindAndReplace(const FindAndReplacePattern& pattern);
5107 // The entire code object including its header is copied verbatim to the
5108 // snapshot so that it can be written in one, fast, memcpy during
5109 // deserialization. The deserializer will overwrite some pointers, rather
5110 // like a runtime linker, but the random allocation addresses used in the
5111 // mksnapshot process would still be present in the unlinked snapshot data,
5112 // which would make snapshot production non-reproducible. This method wipes
5113 // out the to-be-overwritten header data for reproducible snapshots.
5114 inline void WipeOutHeader();
5116 // Flags operations.
5117 static inline Flags ComputeFlags(
5118 Kind kind, InlineCacheState ic_state = UNINITIALIZED,
5119 ExtraICState extra_ic_state = kNoExtraICState, StubType type = NORMAL,
5120 CacheHolderFlag holder = kCacheOnReceiver);
5122 static inline Flags ComputeMonomorphicFlags(
5123 Kind kind, ExtraICState extra_ic_state = kNoExtraICState,
5124 CacheHolderFlag holder = kCacheOnReceiver, StubType type = NORMAL);
5126 static inline Flags ComputeHandlerFlags(
5127 Kind handler_kind, StubType type = NORMAL,
5128 CacheHolderFlag holder = kCacheOnReceiver);
5130 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
5131 static inline StubType ExtractTypeFromFlags(Flags flags);
5132 static inline CacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
5133 static inline Kind ExtractKindFromFlags(Flags flags);
5134 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
5136 static inline Flags RemoveTypeFromFlags(Flags flags);
5137 static inline Flags RemoveTypeAndHolderFromFlags(Flags flags);
5139 // Convert a target address into a code object.
5140 static inline Code* GetCodeFromTargetAddress(Address address);
5142 // Convert an entry address into an object.
5143 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
5145 // Returns the address of the first instruction.
5146 inline byte* instruction_start();
5148 // Returns the address right after the last instruction.
5149 inline byte* instruction_end();
5151 // Returns the size of the instructions, padding, and relocation information.
5152 inline int body_size();
5154 // Returns the address of the first relocation info (read backwards!).
5155 inline byte* relocation_start();
5157 // Code entry point.
5158 inline byte* entry();
5160 // Returns true if pc is inside this object's instructions.
5161 inline bool contains(byte* pc);
5163 // Relocate the code by delta bytes. Called to signal that this code
5164 // object has been moved by delta bytes.
5165 void Relocate(intptr_t delta);
5167 // Migrate code described by desc.
5168 void CopyFrom(const CodeDesc& desc);
5170 // Returns the object size for a given body (used for allocation).
5171 static int SizeFor(int body_size) {
5172 DCHECK_SIZE_TAG_ALIGNED(body_size);
5173 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
5176 // Calculate the size of the code object to report for log events. This takes
5177 // the layout of the code object into account.
5178 int ExecutableSize() {
5179 // Check that the assumptions about the layout of the code object holds.
5180 DCHECK_EQ(static_cast<int>(instruction_start() - address()),
5182 return instruction_size() + Code::kHeaderSize;
5185 // Locating source position.
5186 int SourcePosition(Address pc);
5187 int SourceStatementPosition(Address pc);
5191 // Dispatched behavior.
5192 int CodeSize() { return SizeFor(body_size()); }
5193 inline void CodeIterateBody(ObjectVisitor* v);
5195 template<typename StaticVisitor>
5196 inline void CodeIterateBody(Heap* heap);
5198 DECLARE_PRINTER(Code)
5199 DECLARE_VERIFIER(Code)
5201 void ClearInlineCaches();
5202 void ClearInlineCaches(Kind kind);
5204 BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
5205 uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
5207 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
5209 kToBeExecutedOnceCodeAge = -3,
5210 kNotExecutedCodeAge = -2,
5211 kExecutedOnceCodeAge = -1,
5213 CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
5215 kFirstCodeAge = kToBeExecutedOnceCodeAge,
5216 kLastCodeAge = kAfterLastCodeAge - 1,
5217 kCodeAgeCount = kAfterLastCodeAge - kFirstCodeAge - 1,
5218 kIsOldCodeAge = kSexagenarianCodeAge,
5219 kPreAgedCodeAge = kIsOldCodeAge - 1
5221 #undef DECLARE_CODE_AGE_ENUM
5223 // Code aging. Indicates how many full GCs this code has survived without
5224 // being entered through the prologue. Used to determine when it is
5225 // relatively safe to flush this code object and replace it with the lazy
5226 // compilation stub.
5227 static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
5228 static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
5229 void MakeYoung(Isolate* isolate);
5230 void MarkToBeExecutedOnce(Isolate* isolate);
5231 void MakeOlder(MarkingParity);
5232 static bool IsYoungSequence(Isolate* isolate, byte* sequence);
5235 static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
5236 return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
5239 void PrintDeoptLocation(FILE* out, Address pc);
5240 bool CanDeoptAt(Address pc);
5243 void VerifyEmbeddedObjectsDependency();
5247 enum VerifyMode { kNoContextSpecificPointers, kNoContextRetainingPointers };
5248 void VerifyEmbeddedObjects(VerifyMode mode = kNoContextRetainingPointers);
5251 inline bool CanContainWeakObjects() {
5252 // is_turbofanned() implies !can_have_weak_objects().
5253 DCHECK(!is_optimized_code() || !is_turbofanned() ||
5254 !can_have_weak_objects());
5255 return is_optimized_code() && can_have_weak_objects();
5258 inline bool IsWeakObject(Object* object) {
5259 return (CanContainWeakObjects() && IsWeakObjectInOptimizedCode(object));
5262 static inline bool IsWeakObjectInOptimizedCode(Object* object);
5264 static Handle<WeakCell> WeakCellFor(Handle<Code> code);
5265 WeakCell* CachedWeakCell();
5267 // Max loop nesting marker used to postpose OSR. We don't take loop
5268 // nesting that is deeper than 5 levels into account.
5269 static const int kMaxLoopNestingMarker = 6;
5271 static const int kConstantPoolSize =
5272 FLAG_enable_embedded_constant_pool ? kIntSize : 0;
5274 // Layout description.
5275 static const int kRelocationInfoOffset = HeapObject::kHeaderSize;
5276 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
5277 static const int kDeoptimizationDataOffset =
5278 kHandlerTableOffset + kPointerSize;
5279 // For FUNCTION kind, we store the type feedback info here.
5280 static const int kTypeFeedbackInfoOffset =
5281 kDeoptimizationDataOffset + kPointerSize;
5282 static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
5283 static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
5284 static const int kInstructionSizeOffset = kGCMetadataOffset + kPointerSize;
5285 static const int kICAgeOffset = kInstructionSizeOffset + kIntSize;
5286 static const int kFlagsOffset = kICAgeOffset + kIntSize;
5287 static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
5288 static const int kKindSpecificFlags2Offset =
5289 kKindSpecificFlags1Offset + kIntSize;
5290 // Note: We might be able to squeeze this into the flags above.
5291 static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
5292 static const int kConstantPoolOffset = kPrologueOffset + kIntSize;
5293 static const int kHeaderPaddingStart =
5294 kConstantPoolOffset + kConstantPoolSize;
5296 // Add padding to align the instruction start following right after
5297 // the Code object header.
5298 static const int kHeaderSize =
5299 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
5301 // Byte offsets within kKindSpecificFlags1Offset.
5302 static const int kFullCodeFlags = kKindSpecificFlags1Offset;
5303 class FullCodeFlagsHasDeoptimizationSupportField:
5304 public BitField<bool, 0, 1> {}; // NOLINT
5305 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
5306 class FullCodeFlagsIsCompiledOptimizable: public BitField<bool, 2, 1> {};
5307 class FullCodeFlagsHasRelocInfoForSerialization
5308 : public BitField<bool, 3, 1> {};
5309 class ProfilerTicksField : public BitField<int, 4, 28> {};
5311 // Flags layout. BitField<type, shift, size>.
5312 class ICStateField : public BitField<InlineCacheState, 0, 4> {};
5313 class TypeField : public BitField<StubType, 4, 1> {};
5314 class CacheHolderField : public BitField<CacheHolderFlag, 5, 2> {};
5315 class KindField : public BitField<Kind, 7, 4> {};
5316 class ExtraICStateField: public BitField<ExtraICState, 11,
5317 PlatformSmiTagging::kSmiValueSize - 11 + 1> {}; // NOLINT
5319 // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
5320 static const int kStackSlotsFirstBit = 0;
5321 static const int kStackSlotsBitCount = 24;
5322 static const int kHasFunctionCacheBit =
5323 kStackSlotsFirstBit + kStackSlotsBitCount;
5324 static const int kMarkedForDeoptimizationBit = kHasFunctionCacheBit + 1;
5325 static const int kIsTurbofannedBit = kMarkedForDeoptimizationBit + 1;
5326 static const int kCanHaveWeakObjects = kIsTurbofannedBit + 1;
5328 STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
5329 STATIC_ASSERT(kCanHaveWeakObjects + 1 <= 32);
5331 class StackSlotsField: public BitField<int,
5332 kStackSlotsFirstBit, kStackSlotsBitCount> {}; // NOLINT
5333 class HasFunctionCacheField : public BitField<bool, kHasFunctionCacheBit, 1> {
5335 class MarkedForDeoptimizationField
5336 : public BitField<bool, kMarkedForDeoptimizationBit, 1> {}; // NOLINT
5337 class IsTurbofannedField : public BitField<bool, kIsTurbofannedBit, 1> {
5339 class CanHaveWeakObjectsField
5340 : public BitField<bool, kCanHaveWeakObjects, 1> {}; // NOLINT
5342 // KindSpecificFlags2 layout (ALL)
5343 static const int kIsCrankshaftedBit = 0;
5344 class IsCrankshaftedField: public BitField<bool,
5345 kIsCrankshaftedBit, 1> {}; // NOLINT
5347 // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
5348 static const int kSafepointTableOffsetFirstBit = kIsCrankshaftedBit + 1;
5349 static const int kSafepointTableOffsetBitCount = 24;
5351 STATIC_ASSERT(kSafepointTableOffsetFirstBit +
5352 kSafepointTableOffsetBitCount <= 32);
5353 STATIC_ASSERT(1 + kSafepointTableOffsetBitCount <= 32);
5355 class SafepointTableOffsetField: public BitField<int,
5356 kSafepointTableOffsetFirstBit,
5357 kSafepointTableOffsetBitCount> {}; // NOLINT
5359 // KindSpecificFlags2 layout (FUNCTION)
5360 class BackEdgeTableOffsetField: public BitField<int,
5361 kIsCrankshaftedBit + 1, 27> {}; // NOLINT
5362 class AllowOSRAtLoopNestingLevelField: public BitField<int,
5363 kIsCrankshaftedBit + 1 + 27, 4> {}; // NOLINT
5364 STATIC_ASSERT(AllowOSRAtLoopNestingLevelField::kMax >= kMaxLoopNestingMarker);
5366 static const int kArgumentsBits = 16;
5367 static const int kMaxArguments = (1 << kArgumentsBits) - 1;
5369 // This constant should be encodable in an ARM instruction.
5370 static const int kFlagsNotUsedInLookup =
5371 TypeField::kMask | CacheHolderField::kMask;
5374 friend class RelocIterator;
5375 friend class Deoptimizer; // For FindCodeAgeSequence.
5377 void ClearInlineCaches(Kind* kind);
5380 byte* FindCodeAgeSequence();
5381 static void GetCodeAgeAndParity(Code* code, Age* age,
5382 MarkingParity* parity);
5383 static void GetCodeAgeAndParity(Isolate* isolate, byte* sequence, Age* age,
5384 MarkingParity* parity);
5385 static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
5387 // Code aging -- platform-specific
5388 static void PatchPlatformCodeAge(Isolate* isolate,
5389 byte* sequence, Age age,
5390 MarkingParity parity);
5392 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5396 // This class describes the layout of dependent codes array of a map. The
5397 // array is partitioned into several groups of dependent codes. Each group
5398 // contains codes with the same dependency on the map. The array has the
5399 // following layout for n dependency groups:
5401 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5402 // | C1 | C2 | ... | Cn | group 1 | group 2 | ... | group n | undefined |
5403 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5405 // The first n elements are Smis, each of them specifies the number of codes
5406 // in the corresponding group. The subsequent elements contain grouped code
5407 // objects in weak cells. The suffix of the array can be filled with the
5408 // undefined value if the number of codes is less than the length of the
5409 // array. The order of the code objects within a group is not preserved.
5411 // All code indexes used in the class are counted starting from the first
5412 // code object of the first group. In other words, code index 0 corresponds
5413 // to array index n = kCodesStartIndex.
5415 class DependentCode: public FixedArray {
5417 enum DependencyGroup {
5418 // Group of code that weakly embed this map and depend on being
5419 // deoptimized when the map is garbage collected.
5421 // Group of code that embed a transition to this map, and depend on being
5422 // deoptimized when the transition is replaced by a new version.
5424 // Group of code that omit run-time prototype checks for prototypes
5425 // described by this map. The group is deoptimized whenever an object
5426 // described by this map changes shape (and transitions to a new map),
5427 // possibly invalidating the assumptions embedded in the code.
5428 kPrototypeCheckGroup,
5429 // Group of code that depends on global property values in property cells
5430 // not being changed.
5431 kPropertyCellChangedGroup,
5432 // Group of code that omit run-time type checks for the field(s) introduced
5435 // Group of code that omit run-time type checks for initial maps of
5437 kInitialMapChangedGroup,
5438 // Group of code that depends on tenuring information in AllocationSites
5439 // not being changed.
5440 kAllocationSiteTenuringChangedGroup,
5441 // Group of code that depends on element transition information in
5442 // AllocationSites not being changed.
5443 kAllocationSiteTransitionChangedGroup
5446 static const int kGroupCount = kAllocationSiteTransitionChangedGroup + 1;
5448 // Array for holding the index of the first code object of each group.
5449 // The last element stores the total number of code objects.
5450 class GroupStartIndexes {
5452 explicit GroupStartIndexes(DependentCode* entries);
5453 void Recompute(DependentCode* entries);
5454 int at(int i) { return start_indexes_[i]; }
5455 int number_of_entries() { return start_indexes_[kGroupCount]; }
5457 int start_indexes_[kGroupCount + 1];
5460 bool Contains(DependencyGroup group, WeakCell* code_cell);
5462 static Handle<DependentCode> InsertCompilationDependencies(
5463 Handle<DependentCode> entries, DependencyGroup group,
5464 Handle<Foreign> info);
5466 static Handle<DependentCode> InsertWeakCode(Handle<DependentCode> entries,
5467 DependencyGroup group,
5468 Handle<WeakCell> code_cell);
5470 void UpdateToFinishedCode(DependencyGroup group, Foreign* info,
5471 WeakCell* code_cell);
5473 void RemoveCompilationDependencies(DependentCode::DependencyGroup group,
5476 void DeoptimizeDependentCodeGroup(Isolate* isolate,
5477 DependentCode::DependencyGroup group);
5479 bool MarkCodeForDeoptimization(Isolate* isolate,
5480 DependentCode::DependencyGroup group);
5482 // The following low-level accessors should only be used by this class
5483 // and the mark compact collector.
5484 inline int number_of_entries(DependencyGroup group);
5485 inline void set_number_of_entries(DependencyGroup group, int value);
5486 inline Object* object_at(int i);
5487 inline void set_object_at(int i, Object* object);
5488 inline void clear_at(int i);
5489 inline void copy(int from, int to);
5490 DECLARE_CAST(DependentCode)
5492 static const char* DependencyGroupName(DependencyGroup group);
5493 static void SetMarkedForDeoptimization(Code* code, DependencyGroup group);
5496 static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5497 DependencyGroup group,
5498 Handle<Object> object);
5499 static Handle<DependentCode> EnsureSpace(Handle<DependentCode> entries);
5500 // Make a room at the end of the given group by moving out the first
5501 // code objects of the subsequent groups.
5502 inline void ExtendGroup(DependencyGroup group);
5503 // Compact by removing cleared weak cells and return true if there was
5504 // any cleared weak cell.
5506 static int Grow(int number_of_entries) {
5507 if (number_of_entries < 5) return number_of_entries + 1;
5508 return number_of_entries * 5 / 4;
5510 static const int kCodesStartIndex = kGroupCount;
5514 class PrototypeInfo;
5517 // All heap objects have a Map that describes their structure.
5518 // A Map contains information about:
5519 // - Size information about the object
5520 // - How to iterate over an object (for garbage collection)
5521 class Map: public HeapObject {
5524 // Size in bytes or kVariableSizeSentinel if instances do not have
5526 inline int instance_size();
5527 inline void set_instance_size(int value);
5529 // Only to clear an unused byte, remove once byte is used.
5530 inline void clear_unused();
5532 // Count of properties allocated in the object.
5533 inline int inobject_properties();
5534 inline void set_inobject_properties(int value);
5537 inline InstanceType instance_type();
5538 inline void set_instance_type(InstanceType value);
5540 // Tells how many unused property fields are available in the
5541 // instance (only used for JSObject in fast mode).
5542 inline int unused_property_fields();
5543 inline void set_unused_property_fields(int value);
5546 inline byte bit_field() const;
5547 inline void set_bit_field(byte value);
5550 inline byte bit_field2() const;
5551 inline void set_bit_field2(byte value);
5554 inline uint32_t bit_field3() const;
5555 inline void set_bit_field3(uint32_t bits);
5557 class EnumLengthBits: public BitField<int,
5558 0, kDescriptorIndexBitCount> {}; // NOLINT
5559 class NumberOfOwnDescriptorsBits: public BitField<int,
5560 kDescriptorIndexBitCount, kDescriptorIndexBitCount> {}; // NOLINT
5561 STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
5562 class DictionaryMap : public BitField<bool, 20, 1> {};
5563 class OwnsDescriptors : public BitField<bool, 21, 1> {};
5564 class HasInstanceCallHandler : public BitField<bool, 22, 1> {};
5565 class Deprecated : public BitField<bool, 23, 1> {};
5566 class IsUnstable : public BitField<bool, 24, 1> {};
5567 class IsMigrationTarget : public BitField<bool, 25, 1> {};
5568 class IsStrong : public BitField<bool, 26, 1> {};
5571 // Keep this bit field at the very end for better code in
5572 // Builtins::kJSConstructStubGeneric stub.
5573 // This counter is used for in-object slack tracking and for map aging.
5574 // The in-object slack tracking is considered enabled when the counter is
5575 // in the range [kSlackTrackingCounterStart, kSlackTrackingCounterEnd].
5576 class Counter : public BitField<int, 28, 4> {};
5577 static const int kSlackTrackingCounterStart = 14;
5578 static const int kSlackTrackingCounterEnd = 8;
5579 static const int kRetainingCounterStart = kSlackTrackingCounterEnd - 1;
5580 static const int kRetainingCounterEnd = 0;
5582 // Tells whether the object in the prototype property will be used
5583 // for instances created from this function. If the prototype
5584 // property is set to a value that is not a JSObject, the prototype
5585 // property will not be used to create instances of the function.
5586 // See ECMA-262, 13.2.2.
5587 inline void set_non_instance_prototype(bool value);
5588 inline bool has_non_instance_prototype();
5590 // Tells whether function has special prototype property. If not, prototype
5591 // property will not be created when accessed (will return undefined),
5592 // and construction from this function will not be allowed.
5593 inline void set_function_with_prototype(bool value);
5594 inline bool function_with_prototype();
5596 // Tells whether the instance with this map should be ignored by the
5597 // Object.getPrototypeOf() function and the __proto__ accessor.
5598 inline void set_is_hidden_prototype() {
5599 set_bit_field(bit_field() | (1 << kIsHiddenPrototype));
5602 inline bool is_hidden_prototype() {
5603 return ((1 << kIsHiddenPrototype) & bit_field()) != 0;
5606 // Records and queries whether the instance has a named interceptor.
5607 inline void set_has_named_interceptor() {
5608 set_bit_field(bit_field() | (1 << kHasNamedInterceptor));
5611 inline bool has_named_interceptor() {
5612 return ((1 << kHasNamedInterceptor) & bit_field()) != 0;
5615 // Records and queries whether the instance has an indexed interceptor.
5616 inline void set_has_indexed_interceptor() {
5617 set_bit_field(bit_field() | (1 << kHasIndexedInterceptor));
5620 inline bool has_indexed_interceptor() {
5621 return ((1 << kHasIndexedInterceptor) & bit_field()) != 0;
5624 // Tells whether the instance is undetectable.
5625 // An undetectable object is a special class of JSObject: 'typeof' operator
5626 // returns undefined, ToBoolean returns false. Otherwise it behaves like
5627 // a normal JS object. It is useful for implementing undetectable
5628 // document.all in Firefox & Safari.
5629 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
5630 inline void set_is_undetectable() {
5631 set_bit_field(bit_field() | (1 << kIsUndetectable));
5634 inline bool is_undetectable() {
5635 return ((1 << kIsUndetectable) & bit_field()) != 0;
5638 // Tells whether the instance has a call-as-function handler.
5639 inline void set_is_observed() {
5640 set_bit_field(bit_field() | (1 << kIsObserved));
5643 inline bool is_observed() {
5644 return ((1 << kIsObserved) & bit_field()) != 0;
5647 inline void set_is_strong();
5648 inline bool is_strong();
5649 inline void set_is_extensible(bool value);
5650 inline bool is_extensible();
5651 inline void set_is_prototype_map(bool value);
5652 inline bool is_prototype_map() const;
5654 inline void set_elements_kind(ElementsKind elements_kind) {
5655 DCHECK(static_cast<int>(elements_kind) < kElementsKindCount);
5656 DCHECK(kElementsKindCount <= (1 << Map::ElementsKindBits::kSize));
5657 set_bit_field2(Map::ElementsKindBits::update(bit_field2(), elements_kind));
5658 DCHECK(this->elements_kind() == elements_kind);
5661 inline ElementsKind elements_kind() {
5662 return Map::ElementsKindBits::decode(bit_field2());
5665 // Tells whether the instance has fast elements that are only Smis.
5666 inline bool has_fast_smi_elements() {
5667 return IsFastSmiElementsKind(elements_kind());
5670 // Tells whether the instance has fast elements.
5671 inline bool has_fast_object_elements() {
5672 return IsFastObjectElementsKind(elements_kind());
5675 inline bool has_fast_smi_or_object_elements() {
5676 return IsFastSmiOrObjectElementsKind(elements_kind());
5679 inline bool has_fast_double_elements() {
5680 return IsFastDoubleElementsKind(elements_kind());
5683 inline bool has_fast_elements() {
5684 return IsFastElementsKind(elements_kind());
5687 inline bool has_sloppy_arguments_elements() {
5688 return IsSloppyArgumentsElements(elements_kind());
5691 inline bool has_external_array_elements() {
5692 return IsExternalArrayElementsKind(elements_kind());
5695 inline bool has_fixed_typed_array_elements() {
5696 return IsFixedTypedArrayElementsKind(elements_kind());
5699 inline bool has_dictionary_elements() {
5700 return IsDictionaryElementsKind(elements_kind());
5703 static bool IsValidElementsTransition(ElementsKind from_kind,
5704 ElementsKind to_kind);
5706 // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
5707 // map with DICTIONARY_ELEMENTS was found in the prototype chain.
5708 bool DictionaryElementsInPrototypeChainOnly();
5710 inline Map* ElementsTransitionMap();
5712 inline FixedArrayBase* GetInitialElements();
5714 // [raw_transitions]: Provides access to the transitions storage field.
5715 // Don't call set_raw_transitions() directly to overwrite transitions, use
5716 // the TransitionArray::ReplaceTransitions() wrapper instead!
5717 DECL_ACCESSORS(raw_transitions, Object)
5718 // [prototype_info]: Per-prototype metadata. Aliased with transitions
5719 // (which prototype maps don't have).
5720 DECL_ACCESSORS(prototype_info, Object)
5721 // PrototypeInfo is created lazily using this helper (which installs it on
5722 // the given prototype's map).
5723 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5724 Handle<JSObject> prototype, Isolate* isolate);
5726 // [prototype chain validity cell]: Associated with a prototype object,
5727 // stored in that object's map's PrototypeInfo, indicates that prototype
5728 // chains through this object are currently valid. The cell will be
5729 // invalidated and replaced when the prototype chain changes.
5730 static Handle<Cell> GetOrCreatePrototypeChainValidityCell(Handle<Map> map,
5732 static const int kPrototypeChainValid = 0;
5733 static const int kPrototypeChainInvalid = 1;
5736 Map* FindFieldOwner(int descriptor);
5738 inline int GetInObjectPropertyOffset(int index);
5740 int NumberOfFields();
5742 // TODO(ishell): candidate with JSObject::MigrateToMap().
5743 bool InstancesNeedRewriting(Map* target, int target_number_of_fields,
5744 int target_inobject, int target_unused,
5745 int* old_number_of_fields);
5746 // TODO(ishell): moveit!
5747 static Handle<Map> GeneralizeAllFieldRepresentations(Handle<Map> map);
5748 MUST_USE_RESULT static Handle<HeapType> GeneralizeFieldType(
5749 Handle<HeapType> type1,
5750 Handle<HeapType> type2,
5752 static void GeneralizeFieldType(Handle<Map> map, int modify_index,
5753 Representation new_representation,
5754 Handle<HeapType> new_field_type);
5755 static Handle<Map> ReconfigureProperty(Handle<Map> map, int modify_index,
5756 PropertyKind new_kind,
5757 PropertyAttributes new_attributes,
5758 Representation new_representation,
5759 Handle<HeapType> new_field_type,
5760 StoreMode store_mode);
5761 static Handle<Map> CopyGeneralizeAllRepresentations(
5762 Handle<Map> map, int modify_index, StoreMode store_mode,
5763 PropertyKind kind, PropertyAttributes attributes, const char* reason);
5765 static Handle<Map> PrepareForDataProperty(Handle<Map> old_map,
5766 int descriptor_number,
5767 Handle<Object> value);
5769 static Handle<Map> Normalize(Handle<Map> map, PropertyNormalizationMode mode,
5770 const char* reason);
5772 // Returns the constructor name (the name (possibly, inferred name) of the
5773 // function that was used to instantiate the object).
5774 String* constructor_name();
5776 // Tells whether the map is used for JSObjects in dictionary mode (ie
5777 // normalized objects, ie objects for which HasFastProperties returns false).
5778 // A map can never be used for both dictionary mode and fast mode JSObjects.
5779 // False by default and for HeapObjects that are not JSObjects.
5780 inline void set_dictionary_map(bool value);
5781 inline bool is_dictionary_map();
5783 // Tells whether the instance needs security checks when accessing its
5785 inline void set_is_access_check_needed(bool access_check_needed);
5786 inline bool is_access_check_needed();
5788 // Returns true if map has a non-empty stub code cache.
5789 inline bool has_code_cache();
5791 // [prototype]: implicit prototype object.
5792 DECL_ACCESSORS(prototype, Object)
5793 // TODO(jkummerow): make set_prototype private.
5794 static void SetPrototype(
5795 Handle<Map> map, Handle<Object> prototype,
5796 PrototypeOptimizationMode proto_mode = FAST_PROTOTYPE);
5798 // [constructor]: points back to the function responsible for this map.
5799 // The field overlaps with the back pointer. All maps in a transition tree
5800 // have the same constructor, so maps with back pointers can walk the
5801 // back pointer chain until they find the map holding their constructor.
5802 DECL_ACCESSORS(constructor_or_backpointer, Object)
5803 inline Object* GetConstructor() const;
5804 inline void SetConstructor(Object* constructor,
5805 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5806 // [back pointer]: points back to the parent map from which a transition
5807 // leads to this map. The field overlaps with the constructor (see above).
5808 inline Object* GetBackPointer();
5809 inline void SetBackPointer(Object* value,
5810 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5812 // [instance descriptors]: describes the object.
5813 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
5815 // [layout descriptor]: describes the object layout.
5816 DECL_ACCESSORS(layout_descriptor, LayoutDescriptor)
5817 // |layout descriptor| accessor which can be used from GC.
5818 inline LayoutDescriptor* layout_descriptor_gc_safe();
5819 inline bool HasFastPointerLayout() const;
5821 // |layout descriptor| accessor that is safe to call even when
5822 // FLAG_unbox_double_fields is disabled (in this case Map does not contain
5823 // |layout_descriptor| field at all).
5824 inline LayoutDescriptor* GetLayoutDescriptor();
5826 inline void UpdateDescriptors(DescriptorArray* descriptors,
5827 LayoutDescriptor* layout_descriptor);
5828 inline void InitializeDescriptors(DescriptorArray* descriptors,
5829 LayoutDescriptor* layout_descriptor);
5831 // [stub cache]: contains stubs compiled for this map.
5832 DECL_ACCESSORS(code_cache, Object)
5834 // [dependent code]: list of optimized codes that weakly embed this map.
5835 DECL_ACCESSORS(dependent_code, DependentCode)
5837 // [weak cell cache]: cache that stores a weak cell pointing to this map.
5838 DECL_ACCESSORS(weak_cell_cache, Object)
5840 inline PropertyDetails GetLastDescriptorDetails();
5843 int number_of_own_descriptors = NumberOfOwnDescriptors();
5844 DCHECK(number_of_own_descriptors > 0);
5845 return number_of_own_descriptors - 1;
5848 int NumberOfOwnDescriptors() {
5849 return NumberOfOwnDescriptorsBits::decode(bit_field3());
5852 void SetNumberOfOwnDescriptors(int number) {
5853 DCHECK(number <= instance_descriptors()->number_of_descriptors());
5854 set_bit_field3(NumberOfOwnDescriptorsBits::update(bit_field3(), number));
5857 inline Cell* RetrieveDescriptorsPointer();
5860 return EnumLengthBits::decode(bit_field3());
5863 void SetEnumLength(int length) {
5864 if (length != kInvalidEnumCacheSentinel) {
5865 DCHECK(length >= 0);
5866 DCHECK(length == 0 || instance_descriptors()->HasEnumCache());
5867 DCHECK(length <= NumberOfOwnDescriptors());
5869 set_bit_field3(EnumLengthBits::update(bit_field3(), length));
5872 inline bool owns_descriptors();
5873 inline void set_owns_descriptors(bool owns_descriptors);
5874 inline bool has_instance_call_handler();
5875 inline void set_has_instance_call_handler();
5876 inline void mark_unstable();
5877 inline bool is_stable();
5878 inline void set_migration_target(bool value);
5879 inline bool is_migration_target();
5880 inline void set_counter(int value);
5881 inline int counter();
5882 inline void deprecate();
5883 inline bool is_deprecated();
5884 inline bool CanBeDeprecated();
5885 // Returns a non-deprecated version of the input. If the input was not
5886 // deprecated, it is directly returned. Otherwise, the non-deprecated version
5887 // is found by re-transitioning from the root of the transition tree using the
5888 // descriptor array of the map. Returns MaybeHandle<Map>() if no updated map
5890 static MaybeHandle<Map> TryUpdate(Handle<Map> map) WARN_UNUSED_RESULT;
5892 // Returns a non-deprecated version of the input. This method may deprecate
5893 // existing maps along the way if encodings conflict. Not for use while
5894 // gathering type feedback. Use TryUpdate in those cases instead.
5895 static Handle<Map> Update(Handle<Map> map);
5897 static Handle<Map> CopyDropDescriptors(Handle<Map> map);
5898 static Handle<Map> CopyInsertDescriptor(Handle<Map> map,
5899 Descriptor* descriptor,
5900 TransitionFlag flag);
5902 MUST_USE_RESULT static MaybeHandle<Map> CopyWithField(
5905 Handle<HeapType> type,
5906 PropertyAttributes attributes,
5907 Representation representation,
5908 TransitionFlag flag);
5910 MUST_USE_RESULT static MaybeHandle<Map> CopyWithConstant(
5913 Handle<Object> constant,
5914 PropertyAttributes attributes,
5915 TransitionFlag flag);
5917 // Returns a new map with all transitions dropped from the given map and
5918 // the ElementsKind set.
5919 static Handle<Map> TransitionElementsTo(Handle<Map> map,
5920 ElementsKind to_kind);
5922 static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
5924 static Handle<Map> CopyAsElementsKind(Handle<Map> map,
5926 TransitionFlag flag);
5928 static Handle<Map> CopyForObserved(Handle<Map> map);
5930 static Handle<Map> CopyForPreventExtensions(Handle<Map> map,
5931 PropertyAttributes attrs_to_add,
5932 Handle<Symbol> transition_marker,
5933 const char* reason);
5935 static Handle<Map> FixProxy(Handle<Map> map, InstanceType type, int size);
5938 // Maximal number of fast properties. Used to restrict the number of map
5939 // transitions to avoid an explosion in the number of maps for objects used as
5941 inline bool TooManyFastProperties(StoreFromKeyed store_mode);
5942 static Handle<Map> TransitionToDataProperty(Handle<Map> map,
5944 Handle<Object> value,
5945 PropertyAttributes attributes,
5946 StoreFromKeyed store_mode);
5947 static Handle<Map> TransitionToAccessorProperty(
5948 Handle<Map> map, Handle<Name> name, AccessorComponent component,
5949 Handle<Object> accessor, PropertyAttributes attributes);
5950 static Handle<Map> ReconfigureExistingProperty(Handle<Map> map,
5953 PropertyAttributes attributes);
5955 inline void AppendDescriptor(Descriptor* desc);
5957 // Returns a copy of the map, prepared for inserting into the transition
5958 // tree (if the |map| owns descriptors then the new one will share
5959 // descriptors with |map|).
5960 static Handle<Map> CopyForTransition(Handle<Map> map, const char* reason);
5962 // Returns a copy of the map, with all transitions dropped from the
5963 // instance descriptors.
5964 static Handle<Map> Copy(Handle<Map> map, const char* reason);
5965 static Handle<Map> Create(Isolate* isolate, int inobject_properties);
5967 // Returns the next free property index (only valid for FAST MODE).
5968 int NextFreePropertyIndex();
5970 // Returns the number of properties described in instance_descriptors
5971 // filtering out properties with the specified attributes.
5972 int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
5973 PropertyAttributes filter = NONE);
5977 // Code cache operations.
5979 // Clears the code cache.
5980 inline void ClearCodeCache(Heap* heap);
5982 // Update code cache.
5983 static void UpdateCodeCache(Handle<Map> map,
5987 // Extend the descriptor array of the map with the list of descriptors.
5988 // In case of duplicates, the latest descriptor is used.
5989 static void AppendCallbackDescriptors(Handle<Map> map,
5990 Handle<Object> descriptors);
5992 static inline int SlackForArraySize(int old_size, int size_limit);
5994 static void EnsureDescriptorSlack(Handle<Map> map, int slack);
5996 // Returns the found code or undefined if absent.
5997 Object* FindInCodeCache(Name* name, Code::Flags flags);
5999 // Returns the non-negative index of the code object if it is in the
6000 // cache and -1 otherwise.
6001 int IndexInCodeCache(Object* name, Code* code);
6003 // Removes a code object from the code cache at the given index.
6004 void RemoveFromCodeCache(Name* name, Code* code, int index);
6006 // Computes a hash value for this map, to be used in HashTables and such.
6009 // Returns the map that this map transitions to if its elements_kind
6010 // is changed to |elements_kind|, or NULL if no such map is cached yet.
6011 // |safe_to_add_transitions| is set to false if adding transitions is not
6013 Map* LookupElementsTransitionMap(ElementsKind elements_kind);
6015 // Returns the transitioned map for this map with the most generic
6016 // elements_kind that's found in |candidates|, or null handle if no match is
6018 static Handle<Map> FindTransitionedMap(Handle<Map> map,
6019 MapHandleList* candidates);
6021 bool CanTransition() {
6022 // Only JSObject and subtypes have map transitions and back pointers.
6023 STATIC_ASSERT(LAST_TYPE == LAST_JS_OBJECT_TYPE);
6024 return instance_type() >= FIRST_JS_OBJECT_TYPE;
6027 bool IsJSObjectMap() {
6028 return instance_type() >= FIRST_JS_OBJECT_TYPE;
6030 bool IsJSArrayMap() { return instance_type() == JS_ARRAY_TYPE; }
6031 bool IsStringMap() { return instance_type() < FIRST_NONSTRING_TYPE; }
6032 bool IsJSProxyMap() {
6033 InstanceType type = instance_type();
6034 return FIRST_JS_PROXY_TYPE <= type && type <= LAST_JS_PROXY_TYPE;
6036 bool IsJSGlobalProxyMap() {
6037 return instance_type() == JS_GLOBAL_PROXY_TYPE;
6039 bool IsJSGlobalObjectMap() {
6040 return instance_type() == JS_GLOBAL_OBJECT_TYPE;
6042 bool IsGlobalObjectMap() {
6043 const InstanceType type = instance_type();
6044 return type == JS_GLOBAL_OBJECT_TYPE || type == JS_BUILTINS_OBJECT_TYPE;
6047 inline bool CanOmitMapChecks();
6049 static void AddDependentCode(Handle<Map> map,
6050 DependentCode::DependencyGroup group,
6053 bool IsMapInArrayPrototypeChain();
6055 static Handle<WeakCell> WeakCellForMap(Handle<Map> map);
6057 // Dispatched behavior.
6058 DECLARE_PRINTER(Map)
6059 DECLARE_VERIFIER(Map)
6062 void DictionaryMapVerify();
6063 void VerifyOmittedMapChecks();
6066 inline int visitor_id();
6067 inline void set_visitor_id(int visitor_id);
6069 static Handle<Map> TransitionToPrototype(Handle<Map> map,
6070 Handle<Object> prototype,
6071 PrototypeOptimizationMode mode);
6073 static const int kMaxPreAllocatedPropertyFields = 255;
6075 // Layout description.
6076 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
6077 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
6078 static const int kBitField3Offset = kInstanceAttributesOffset + kIntSize;
6079 static const int kPrototypeOffset = kBitField3Offset + kPointerSize;
6080 static const int kConstructorOrBackPointerOffset =
6081 kPrototypeOffset + kPointerSize;
6082 // When there is only one transition, it is stored directly in this field;
6083 // otherwise a transition array is used.
6084 // For prototype maps, this slot is used to store this map's PrototypeInfo
6086 static const int kTransitionsOrPrototypeInfoOffset =
6087 kConstructorOrBackPointerOffset + kPointerSize;
6088 static const int kDescriptorsOffset =
6089 kTransitionsOrPrototypeInfoOffset + kPointerSize;
6090 #if V8_DOUBLE_FIELDS_UNBOXING
6091 static const int kLayoutDecriptorOffset = kDescriptorsOffset + kPointerSize;
6092 static const int kCodeCacheOffset = kLayoutDecriptorOffset + kPointerSize;
6094 static const int kLayoutDecriptorOffset = 1; // Must not be ever accessed.
6095 static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
6097 static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
6098 static const int kWeakCellCacheOffset = kDependentCodeOffset + kPointerSize;
6099 static const int kSize = kWeakCellCacheOffset + kPointerSize;
6101 // Layout of pointer fields. Heap iteration code relies on them
6102 // being continuously allocated.
6103 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
6104 static const int kPointerFieldsEndOffset = kSize;
6106 // Byte offsets within kInstanceSizesOffset.
6107 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
6108 static const int kInObjectPropertiesByte = 1;
6109 static const int kInObjectPropertiesOffset =
6110 kInstanceSizesOffset + kInObjectPropertiesByte;
6111 // Note there is one byte available for use here.
6112 static const int kUnusedByte = 2;
6113 static const int kUnusedOffset = kInstanceSizesOffset + kUnusedByte;
6114 static const int kVisitorIdByte = 3;
6115 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
6117 // Byte offsets within kInstanceAttributesOffset attributes.
6118 #if V8_TARGET_LITTLE_ENDIAN
6119 // Order instance type and bit field together such that they can be loaded
6120 // together as a 16-bit word with instance type in the lower 8 bits regardless
6121 // of endianess. Also provide endian-independent offset to that 16-bit word.
6122 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
6123 static const int kBitFieldOffset = kInstanceAttributesOffset + 1;
6125 static const int kBitFieldOffset = kInstanceAttributesOffset + 0;
6126 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 1;
6128 static const int kInstanceTypeAndBitFieldOffset =
6129 kInstanceAttributesOffset + 0;
6130 static const int kBitField2Offset = kInstanceAttributesOffset + 2;
6131 static const int kUnusedPropertyFieldsByte = 3;
6132 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 3;
6134 STATIC_ASSERT(kInstanceTypeAndBitFieldOffset ==
6135 Internals::kMapInstanceTypeAndBitFieldOffset);
6137 // Bit positions for bit field.
6138 static const int kHasNonInstancePrototype = 0;
6139 static const int kIsHiddenPrototype = 1;
6140 static const int kHasNamedInterceptor = 2;
6141 static const int kHasIndexedInterceptor = 3;
6142 static const int kIsUndetectable = 4;
6143 static const int kIsObserved = 5;
6144 static const int kIsAccessCheckNeeded = 6;
6145 class FunctionWithPrototype: public BitField<bool, 7, 1> {};
6147 // Bit positions for bit field 2
6148 static const int kIsExtensible = 0;
6149 static const int kStringWrapperSafeForDefaultValueOf = 1;
6150 class IsPrototypeMapBits : public BitField<bool, 2, 1> {};
6151 class ElementsKindBits: public BitField<ElementsKind, 3, 5> {};
6153 // Derived values from bit field 2
6154 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
6155 (FAST_ELEMENTS + 1) << Map::ElementsKindBits::kShift) - 1;
6156 static const int8_t kMaximumBitField2FastSmiElementValue =
6157 static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
6158 Map::ElementsKindBits::kShift) - 1;
6159 static const int8_t kMaximumBitField2FastHoleyElementValue =
6160 static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
6161 Map::ElementsKindBits::kShift) - 1;
6162 static const int8_t kMaximumBitField2FastHoleySmiElementValue =
6163 static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
6164 Map::ElementsKindBits::kShift) - 1;
6166 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
6167 kPointerFieldsEndOffset,
6168 kSize> BodyDescriptor;
6170 // Compares this map to another to see if they describe equivalent objects.
6171 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
6172 // it had exactly zero inobject properties.
6173 // The "shared" flags of both this map and |other| are ignored.
6174 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
6176 // Returns true if given field is unboxed double.
6177 inline bool IsUnboxedDoubleField(FieldIndex index);
6180 static void TraceTransition(const char* what, Map* from, Map* to, Name* name);
6181 static void TraceAllTransitions(Map* map);
6184 static inline Handle<Map> CopyInstallDescriptorsForTesting(
6185 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
6186 Handle<LayoutDescriptor> layout_descriptor);
6189 static void ConnectTransition(Handle<Map> parent, Handle<Map> child,
6190 Handle<Name> name, SimpleTransitionFlag flag);
6192 bool EquivalentToForTransition(Map* other);
6193 static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
6194 static Handle<Map> ShareDescriptor(Handle<Map> map,
6195 Handle<DescriptorArray> descriptors,
6196 Descriptor* descriptor);
6197 static Handle<Map> CopyInstallDescriptors(
6198 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
6199 Handle<LayoutDescriptor> layout_descriptor);
6200 static Handle<Map> CopyAddDescriptor(Handle<Map> map,
6201 Descriptor* descriptor,
6202 TransitionFlag flag);
6203 static Handle<Map> CopyReplaceDescriptors(
6204 Handle<Map> map, Handle<DescriptorArray> descriptors,
6205 Handle<LayoutDescriptor> layout_descriptor, TransitionFlag flag,
6206 MaybeHandle<Name> maybe_name, const char* reason,
6207 SimpleTransitionFlag simple_flag);
6209 static Handle<Map> CopyReplaceDescriptor(Handle<Map> map,
6210 Handle<DescriptorArray> descriptors,
6211 Descriptor* descriptor,
6213 TransitionFlag flag);
6214 static MUST_USE_RESULT MaybeHandle<Map> TryReconfigureExistingProperty(
6215 Handle<Map> map, int descriptor, PropertyKind kind,
6216 PropertyAttributes attributes, const char** reason);
6218 static Handle<Map> CopyNormalized(Handle<Map> map,
6219 PropertyNormalizationMode mode);
6221 // Fires when the layout of an object with a leaf map changes.
6222 // This includes adding transitions to the leaf map or changing
6223 // the descriptor array.
6224 inline void NotifyLeafMapLayoutChange();
6226 void DeprecateTransitionTree();
6227 bool DeprecateTarget(PropertyKind kind, Name* key,
6228 PropertyAttributes attributes,
6229 DescriptorArray* new_descriptors,
6230 LayoutDescriptor* new_layout_descriptor);
6232 Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
6234 // Update field type of the given descriptor to new representation and new
6235 // type. The type must be prepared for storing in descriptor array:
6236 // it must be either a simple type or a map wrapped in a weak cell.
6237 void UpdateFieldType(int descriptor_number, Handle<Name> name,
6238 Representation new_representation,
6239 Handle<Object> new_wrapped_type);
6241 void PrintReconfiguration(FILE* file, int modify_index, PropertyKind kind,
6242 PropertyAttributes attributes);
6243 void PrintGeneralization(FILE* file,
6248 bool constant_to_field,
6249 Representation old_representation,
6250 Representation new_representation,
6251 HeapType* old_field_type,
6252 HeapType* new_field_type);
6254 static const int kFastPropertiesSoftLimit = 12;
6255 static const int kMaxFastProperties = 128;
6257 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
6261 // An abstract superclass, a marker class really, for simple structure classes.
6262 // It doesn't carry much functionality but allows struct classes to be
6263 // identified in the type system.
6264 class Struct: public HeapObject {
6266 inline void InitializeBody(int object_size);
6267 DECLARE_CAST(Struct)
6271 // A simple one-element struct, useful where smis need to be boxed.
6272 class Box : public Struct {
6274 // [value]: the boxed contents.
6275 DECL_ACCESSORS(value, Object)
6279 // Dispatched behavior.
6280 DECLARE_PRINTER(Box)
6281 DECLARE_VERIFIER(Box)
6283 static const int kValueOffset = HeapObject::kHeaderSize;
6284 static const int kSize = kValueOffset + kPointerSize;
6287 DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
6291 // Container for metadata stored on each prototype map.
6292 class PrototypeInfo : public Struct {
6294 // [prototype_users]: WeakFixedArray containing maps using this prototype,
6295 // or Smi(0) if uninitialized.
6296 DECL_ACCESSORS(prototype_users, Object)
6297 // [validity_cell]: Cell containing the validity bit for prototype chains
6298 // going through this object, or Smi(0) if uninitialized.
6299 DECL_ACCESSORS(validity_cell, Object)
6300 // [constructor_name]: User-friendly name of the original constructor.
6301 DECL_ACCESSORS(constructor_name, Object)
6303 DECLARE_CAST(PrototypeInfo)
6305 // Dispatched behavior.
6306 DECLARE_PRINTER(PrototypeInfo)
6307 DECLARE_VERIFIER(PrototypeInfo)
6309 static const int kPrototypeUsersOffset = HeapObject::kHeaderSize;
6310 static const int kValidityCellOffset = kPrototypeUsersOffset + kPointerSize;
6311 static const int kConstructorNameOffset = kValidityCellOffset + kPointerSize;
6312 static const int kSize = kConstructorNameOffset + kPointerSize;
6315 DISALLOW_IMPLICIT_CONSTRUCTORS(PrototypeInfo);
6319 // Script describes a script which has been added to the VM.
6320 class Script: public Struct {
6329 // Script compilation types.
6330 enum CompilationType {
6331 COMPILATION_TYPE_HOST = 0,
6332 COMPILATION_TYPE_EVAL = 1
6335 // Script compilation state.
6336 enum CompilationState {
6337 COMPILATION_STATE_INITIAL = 0,
6338 COMPILATION_STATE_COMPILED = 1
6341 // [source]: the script source.
6342 DECL_ACCESSORS(source, Object)
6344 // [name]: the script name.
6345 DECL_ACCESSORS(name, Object)
6347 // [id]: the script id.
6348 DECL_ACCESSORS(id, Smi)
6350 // [line_offset]: script line offset in resource from where it was extracted.
6351 DECL_ACCESSORS(line_offset, Smi)
6353 // [column_offset]: script column offset in resource from where it was
6355 DECL_ACCESSORS(column_offset, Smi)
6357 // [context_data]: context data for the context this script was compiled in.
6358 DECL_ACCESSORS(context_data, Object)
6360 // [wrapper]: the wrapper cache. This is either undefined or a WeakCell.
6361 DECL_ACCESSORS(wrapper, HeapObject)
6363 // [type]: the script type.
6364 DECL_ACCESSORS(type, Smi)
6366 // [line_ends]: FixedArray of line ends positions.
6367 DECL_ACCESSORS(line_ends, Object)
6369 // [eval_from_shared]: for eval scripts the shared funcion info for the
6370 // function from which eval was called.
6371 DECL_ACCESSORS(eval_from_shared, Object)
6373 // [eval_from_instructions_offset]: the instruction offset in the code for the
6374 // function from which eval was called where eval was called.
6375 DECL_ACCESSORS(eval_from_instructions_offset, Smi)
6377 // [shared_function_infos]: weak fixed array containing all shared
6378 // function infos created from this script.
6379 DECL_ACCESSORS(shared_function_infos, Object)
6381 // [flags]: Holds an exciting bitfield.
6382 DECL_ACCESSORS(flags, Smi)
6384 // [source_url]: sourceURL from magic comment
6385 DECL_ACCESSORS(source_url, Object)
6387 // [source_url]: sourceMappingURL magic comment
6388 DECL_ACCESSORS(source_mapping_url, Object)
6390 // [compilation_type]: how the the script was compiled. Encoded in the
6392 inline CompilationType compilation_type();
6393 inline void set_compilation_type(CompilationType type);
6395 // [compilation_state]: determines whether the script has already been
6396 // compiled. Encoded in the 'flags' field.
6397 inline CompilationState compilation_state();
6398 inline void set_compilation_state(CompilationState state);
6400 // [origin_options]: optional attributes set by the embedder via ScriptOrigin,
6401 // and used by the embedder to make decisions about the script. V8 just passes
6402 // this through. Encoded in the 'flags' field.
6403 inline v8::ScriptOriginOptions origin_options();
6404 inline void set_origin_options(ScriptOriginOptions origin_options);
6406 DECLARE_CAST(Script)
6408 // If script source is an external string, check that the underlying
6409 // resource is accessible. Otherwise, always return true.
6410 inline bool HasValidSource();
6412 // Convert code position into column number.
6413 static int GetColumnNumber(Handle<Script> script, int code_pos);
6415 // Convert code position into (zero-based) line number.
6416 // The non-handlified version does not allocate, but may be much slower.
6417 static int GetLineNumber(Handle<Script> script, int code_pos);
6418 int GetLineNumber(int code_pos);
6420 static Handle<Object> GetNameOrSourceURL(Handle<Script> script);
6422 // Init line_ends array with code positions of line ends inside script source.
6423 static void InitLineEnds(Handle<Script> script);
6425 // Get the JS object wrapping the given script; create it if none exists.
6426 static Handle<JSObject> GetWrapper(Handle<Script> script);
6428 // Look through the list of existing shared function infos to find one
6429 // that matches the function literal. Return empty handle if not found.
6430 MaybeHandle<SharedFunctionInfo> FindSharedFunctionInfo(FunctionLiteral* fun);
6432 // Dispatched behavior.
6433 DECLARE_PRINTER(Script)
6434 DECLARE_VERIFIER(Script)
6436 static const int kSourceOffset = HeapObject::kHeaderSize;
6437 static const int kNameOffset = kSourceOffset + kPointerSize;
6438 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
6439 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
6440 static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
6441 static const int kWrapperOffset = kContextOffset + kPointerSize;
6442 static const int kTypeOffset = kWrapperOffset + kPointerSize;
6443 static const int kLineEndsOffset = kTypeOffset + kPointerSize;
6444 static const int kIdOffset = kLineEndsOffset + kPointerSize;
6445 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
6446 static const int kEvalFrominstructionsOffsetOffset =
6447 kEvalFromSharedOffset + kPointerSize;
6448 static const int kSharedFunctionInfosOffset =
6449 kEvalFrominstructionsOffsetOffset + kPointerSize;
6450 static const int kFlagsOffset = kSharedFunctionInfosOffset + kPointerSize;
6451 static const int kSourceUrlOffset = kFlagsOffset + kPointerSize;
6452 static const int kSourceMappingUrlOffset = kSourceUrlOffset + kPointerSize;
6453 static const int kSize = kSourceMappingUrlOffset + kPointerSize;
6456 int GetLineNumberWithArray(int code_pos);
6458 // Bit positions in the flags field.
6459 static const int kCompilationTypeBit = 0;
6460 static const int kCompilationStateBit = 1;
6461 static const int kOriginOptionsShift = 2;
6462 static const int kOriginOptionsSize = 3;
6463 static const int kOriginOptionsMask = ((1 << kOriginOptionsSize) - 1)
6464 << kOriginOptionsShift;
6466 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6470 // List of builtin functions we want to identify to improve code
6473 // Each entry has a name of a global object property holding an object
6474 // optionally followed by ".prototype", a name of a builtin function
6475 // on the object (the one the id is set for), and a label.
6477 // Installation of ids for the selected builtin functions is handled
6478 // by the bootstrapper.
6479 #define FUNCTIONS_WITH_ID_LIST(V) \
6480 V(Array.prototype, indexOf, ArrayIndexOf) \
6481 V(Array.prototype, lastIndexOf, ArrayLastIndexOf) \
6482 V(Array.prototype, push, ArrayPush) \
6483 V(Array.prototype, pop, ArrayPop) \
6484 V(Array.prototype, shift, ArrayShift) \
6485 V(Function.prototype, apply, FunctionApply) \
6486 V(Function.prototype, call, FunctionCall) \
6487 V(String.prototype, charCodeAt, StringCharCodeAt) \
6488 V(String.prototype, charAt, StringCharAt) \
6489 V(String, fromCharCode, StringFromCharCode) \
6490 V(Math, random, MathRandom) \
6491 V(Math, floor, MathFloor) \
6492 V(Math, round, MathRound) \
6493 V(Math, ceil, MathCeil) \
6494 V(Math, abs, MathAbs) \
6495 V(Math, log, MathLog) \
6496 V(Math, exp, MathExp) \
6497 V(Math, sqrt, MathSqrt) \
6498 V(Math, pow, MathPow) \
6499 V(Math, max, MathMax) \
6500 V(Math, min, MathMin) \
6501 V(Math, cos, MathCos) \
6502 V(Math, sin, MathSin) \
6503 V(Math, tan, MathTan) \
6504 V(Math, acos, MathAcos) \
6505 V(Math, asin, MathAsin) \
6506 V(Math, atan, MathAtan) \
6507 V(Math, atan2, MathAtan2) \
6508 V(Math, imul, MathImul) \
6509 V(Math, clz32, MathClz32) \
6510 V(Math, fround, MathFround)
6512 #define ATOMIC_FUNCTIONS_WITH_ID_LIST(V) \
6513 V(Atomics, load, AtomicsLoad) \
6514 V(Atomics, store, AtomicsStore)
6516 enum BuiltinFunctionId {
6518 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
6520 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6521 ATOMIC_FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6522 #undef DECLARE_FUNCTION_ID
6523 // Fake id for a special case of Math.pow. Note, it continues the
6524 // list of math functions.
6529 // Result of searching in an optimized code map of a SharedFunctionInfo. Note
6530 // that both {code} and {literals} can be NULL to pass search result status.
6531 struct CodeAndLiterals {
6532 Code* code; // Cached optimized code.
6533 FixedArray* literals; // Cached literals array.
6537 // SharedFunctionInfo describes the JSFunction information that can be
6538 // shared by multiple instances of the function.
6539 class SharedFunctionInfo: public HeapObject {
6541 // [name]: Function name.
6542 DECL_ACCESSORS(name, Object)
6544 // [code]: Function code.
6545 DECL_ACCESSORS(code, Code)
6546 inline void ReplaceCode(Code* code);
6548 // [optimized_code_map]: Map from native context to optimized code
6549 // and a shared literals array or Smi(0) if none.
6550 DECL_ACCESSORS(optimized_code_map, Object)
6552 // Returns entry from optimized code map for specified context and OSR entry.
6553 // Note that {code == nullptr} indicates no matching entry has been found,
6554 // whereas {literals == nullptr} indicates the code is context-independent.
6555 CodeAndLiterals SearchOptimizedCodeMap(Context* native_context,
6556 BailoutId osr_ast_id);
6558 // Clear optimized code map.
6559 void ClearOptimizedCodeMap();
6561 // Removed a specific optimized code object from the optimized code map.
6562 void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
6564 // Trims the optimized code map after entries have been removed.
6565 void TrimOptimizedCodeMap(int shrink_by);
6567 // Add a new entry to the optimized code map for context-independent code.
6568 static void AddSharedCodeToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6571 // Add a new entry to the optimized code map for context-dependent code.
6572 static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6573 Handle<Context> native_context,
6575 Handle<FixedArray> literals,
6576 BailoutId osr_ast_id);
6578 // Set up the link between shared function info and the script. The shared
6579 // function info is added to the list on the script.
6580 static void SetScript(Handle<SharedFunctionInfo> shared,
6581 Handle<Object> script_object);
6583 // Layout description of the optimized code map.
6584 static const int kNextMapIndex = 0;
6585 static const int kSharedCodeIndex = 1;
6586 static const int kEntriesStart = 2;
6587 static const int kContextOffset = 0;
6588 static const int kCachedCodeOffset = 1;
6589 static const int kLiteralsOffset = 2;
6590 static const int kOsrAstIdOffset = 3;
6591 static const int kEntryLength = 4;
6592 static const int kInitialLength = kEntriesStart + kEntryLength;
6594 // [scope_info]: Scope info.
6595 DECL_ACCESSORS(scope_info, ScopeInfo)
6597 // [construct stub]: Code stub for constructing instances of this function.
6598 DECL_ACCESSORS(construct_stub, Code)
6600 // Returns if this function has been compiled to native code yet.
6601 inline bool is_compiled();
6603 // [length]: The function length - usually the number of declared parameters.
6604 // Use up to 2^30 parameters.
6605 inline int length() const;
6606 inline void set_length(int value);
6608 // [internal formal parameter count]: The declared number of parameters.
6609 // For subclass constructors, also includes new.target.
6610 // The size of function's frame is internal_formal_parameter_count + 1.
6611 inline int internal_formal_parameter_count() const;
6612 inline void set_internal_formal_parameter_count(int value);
6614 // Set the formal parameter count so the function code will be
6615 // called without using argument adaptor frames.
6616 inline void DontAdaptArguments();
6618 // [expected_nof_properties]: Expected number of properties for the function.
6619 inline int expected_nof_properties() const;
6620 inline void set_expected_nof_properties(int value);
6622 // [feedback_vector] - accumulates ast node feedback from full-codegen and
6623 // (increasingly) from crankshafted code where sufficient feedback isn't
6625 DECL_ACCESSORS(feedback_vector, TypeFeedbackVector)
6627 // Unconditionally clear the type feedback vector (including vector ICs).
6628 void ClearTypeFeedbackInfo();
6630 // Clear the type feedback vector with a more subtle policy at GC time.
6631 void ClearTypeFeedbackInfoAtGCTime();
6634 // [unique_id] - For --trace-maps purposes, an identifier that's persistent
6635 // even if the GC moves this SharedFunctionInfo.
6636 inline int unique_id() const;
6637 inline void set_unique_id(int value);
6640 // [instance class name]: class name for instances.
6641 DECL_ACCESSORS(instance_class_name, Object)
6643 // [function data]: This field holds some additional data for function.
6644 // Currently it either has FunctionTemplateInfo to make benefit the API
6645 // or Smi identifying a builtin function.
6646 // In the long run we don't want all functions to have this field but
6647 // we can fix that when we have a better model for storing hidden data
6649 DECL_ACCESSORS(function_data, Object)
6651 inline bool IsApiFunction();
6652 inline FunctionTemplateInfo* get_api_func_data();
6653 inline bool HasBuiltinFunctionId();
6654 inline BuiltinFunctionId builtin_function_id();
6656 // [script info]: Script from which the function originates.
6657 DECL_ACCESSORS(script, Object)
6659 // [num_literals]: Number of literals used by this function.
6660 inline int num_literals() const;
6661 inline void set_num_literals(int value);
6663 // [start_position_and_type]: Field used to store both the source code
6664 // position, whether or not the function is a function expression,
6665 // and whether or not the function is a toplevel function. The two
6666 // least significants bit indicates whether the function is an
6667 // expression and the rest contains the source code position.
6668 inline int start_position_and_type() const;
6669 inline void set_start_position_and_type(int value);
6671 // [debug info]: Debug information.
6672 DECL_ACCESSORS(debug_info, Object)
6674 // [inferred name]: Name inferred from variable or property
6675 // assignment of this function. Used to facilitate debugging and
6676 // profiling of JavaScript code written in OO style, where almost
6677 // all functions are anonymous but are assigned to object
6679 DECL_ACCESSORS(inferred_name, String)
6681 // The function's name if it is non-empty, otherwise the inferred name.
6682 String* DebugName();
6684 // Position of the 'function' token in the script source.
6685 inline int function_token_position() const;
6686 inline void set_function_token_position(int function_token_position);
6688 // Position of this function in the script source.
6689 inline int start_position() const;
6690 inline void set_start_position(int start_position);
6692 // End position of this function in the script source.
6693 inline int end_position() const;
6694 inline void set_end_position(int end_position);
6696 // Is this function a function expression in the source code.
6697 DECL_BOOLEAN_ACCESSORS(is_expression)
6699 // Is this function a top-level function (scripts, evals).
6700 DECL_BOOLEAN_ACCESSORS(is_toplevel)
6702 // Bit field containing various information collected by the compiler to
6703 // drive optimization.
6704 inline int compiler_hints() const;
6705 inline void set_compiler_hints(int value);
6707 inline int ast_node_count() const;
6708 inline void set_ast_node_count(int count);
6710 inline int profiler_ticks() const;
6711 inline void set_profiler_ticks(int ticks);
6713 // Inline cache age is used to infer whether the function survived a context
6714 // disposal or not. In the former case we reset the opt_count.
6715 inline int ic_age();
6716 inline void set_ic_age(int age);
6718 // Indicates if this function can be lazy compiled.
6719 // This is used to determine if we can safely flush code from a function
6720 // when doing GC if we expect that the function will no longer be used.
6721 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
6723 // Indicates if this function can be lazy compiled without a context.
6724 // This is used to determine if we can force compilation without reaching
6725 // the function through program execution but through other means (e.g. heap
6726 // iteration by the debugger).
6727 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
6729 // Indicates whether optimizations have been disabled for this
6730 // shared function info. If a function is repeatedly optimized or if
6731 // we cannot optimize the function we disable optimization to avoid
6732 // spending time attempting to optimize it again.
6733 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
6735 // Indicates the language mode.
6736 inline LanguageMode language_mode();
6737 inline void set_language_mode(LanguageMode language_mode);
6739 // False if the function definitely does not allocate an arguments object.
6740 DECL_BOOLEAN_ACCESSORS(uses_arguments)
6742 // Indicates that this function uses a super property (or an eval that may
6743 // use a super property).
6744 // This is needed to set up the [[HomeObject]] on the function instance.
6745 DECL_BOOLEAN_ACCESSORS(needs_home_object)
6747 // True if the function has any duplicated parameter names.
6748 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
6750 // Indicates whether the function is a native function.
6751 // These needs special treatment in .call and .apply since
6752 // null passed as the receiver should not be translated to the
6754 DECL_BOOLEAN_ACCESSORS(native)
6756 // Indicate that this function should always be inlined in optimized code.
6757 DECL_BOOLEAN_ACCESSORS(force_inline)
6759 // Indicates that the function was created by the Function function.
6760 // Though it's anonymous, toString should treat it as if it had the name
6761 // "anonymous". We don't set the name itself so that the system does not
6762 // see a binding for it.
6763 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
6765 // Indicates whether the function is a bound function created using
6766 // the bind function.
6767 DECL_BOOLEAN_ACCESSORS(bound)
6769 // Indicates that the function is anonymous (the name field can be set
6770 // through the API, which does not change this flag).
6771 DECL_BOOLEAN_ACCESSORS(is_anonymous)
6773 // Is this a function or top-level/eval code.
6774 DECL_BOOLEAN_ACCESSORS(is_function)
6776 // Indicates that code for this function cannot be compiled with Crankshaft.
6777 DECL_BOOLEAN_ACCESSORS(dont_crankshaft)
6779 // Indicates that code for this function cannot be flushed.
6780 DECL_BOOLEAN_ACCESSORS(dont_flush)
6782 // Indicates that this function is a generator.
6783 DECL_BOOLEAN_ACCESSORS(is_generator)
6785 // Indicates that this function is an arrow function.
6786 DECL_BOOLEAN_ACCESSORS(is_arrow)
6788 // Indicates that this function is a concise method.
6789 DECL_BOOLEAN_ACCESSORS(is_concise_method)
6791 // Indicates that this function is an accessor (getter or setter).
6792 DECL_BOOLEAN_ACCESSORS(is_accessor_function)
6794 // Indicates that this function is a default constructor.
6795 DECL_BOOLEAN_ACCESSORS(is_default_constructor)
6797 // Indicates that this function is an asm function.
6798 DECL_BOOLEAN_ACCESSORS(asm_function)
6800 // Indicates that the the shared function info is deserialized from cache.
6801 DECL_BOOLEAN_ACCESSORS(deserialized)
6803 // Indicates that the the shared function info has never been compiled before.
6804 DECL_BOOLEAN_ACCESSORS(never_compiled)
6806 inline FunctionKind kind();
6807 inline void set_kind(FunctionKind kind);
6809 // Indicates whether or not the code in the shared function support
6811 inline bool has_deoptimization_support();
6813 // Enable deoptimization support through recompiled code.
6814 void EnableDeoptimizationSupport(Code* recompiled);
6816 // Disable (further) attempted optimization of all functions sharing this
6817 // shared function info.
6818 void DisableOptimization(BailoutReason reason);
6820 inline BailoutReason disable_optimization_reason();
6822 // Lookup the bailout ID and DCHECK that it exists in the non-optimized
6823 // code, returns whether it asserted (i.e., always true if assertions are
6825 bool VerifyBailoutId(BailoutId id);
6827 // [source code]: Source code for the function.
6828 bool HasSourceCode() const;
6829 Handle<Object> GetSourceCode();
6831 // Number of times the function was optimized.
6832 inline int opt_count();
6833 inline void set_opt_count(int opt_count);
6835 // Number of times the function was deoptimized.
6836 inline void set_deopt_count(int value);
6837 inline int deopt_count();
6838 inline void increment_deopt_count();
6840 // Number of time we tried to re-enable optimization after it
6841 // was disabled due to high number of deoptimizations.
6842 inline void set_opt_reenable_tries(int value);
6843 inline int opt_reenable_tries();
6845 inline void TryReenableOptimization();
6847 // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
6848 inline void set_counters(int value);
6849 inline int counters() const;
6851 // Stores opt_count and bailout_reason as bit-fields.
6852 inline void set_opt_count_and_bailout_reason(int value);
6853 inline int opt_count_and_bailout_reason() const;
6855 void set_disable_optimization_reason(BailoutReason reason) {
6856 set_opt_count_and_bailout_reason(
6857 DisabledOptimizationReasonBits::update(opt_count_and_bailout_reason(),
6861 // Tells whether this function should be subject to debugging.
6862 inline bool IsSubjectToDebugging();
6864 // Check whether or not this function is inlineable.
6865 bool IsInlineable();
6867 // Source size of this function.
6870 // Calculate the instance size.
6871 int CalculateInstanceSize();
6873 // Calculate the number of in-object properties.
6874 int CalculateInObjectProperties();
6876 inline bool is_simple_parameter_list();
6878 // Initialize a SharedFunctionInfo from a parsed function literal.
6879 static void InitFromFunctionLiteral(Handle<SharedFunctionInfo> shared_info,
6880 FunctionLiteral* lit);
6882 // Dispatched behavior.
6883 DECLARE_PRINTER(SharedFunctionInfo)
6884 DECLARE_VERIFIER(SharedFunctionInfo)
6886 void ResetForNewContext(int new_ic_age);
6888 DECLARE_CAST(SharedFunctionInfo)
6891 static const int kDontAdaptArgumentsSentinel = -1;
6893 // Layout description.
6895 static const int kNameOffset = HeapObject::kHeaderSize;
6896 static const int kCodeOffset = kNameOffset + kPointerSize;
6897 static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
6898 static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
6899 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
6900 static const int kInstanceClassNameOffset =
6901 kConstructStubOffset + kPointerSize;
6902 static const int kFunctionDataOffset =
6903 kInstanceClassNameOffset + kPointerSize;
6904 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
6905 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
6906 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
6907 static const int kFeedbackVectorOffset =
6908 kInferredNameOffset + kPointerSize;
6910 static const int kUniqueIdOffset = kFeedbackVectorOffset + kPointerSize;
6911 static const int kLastPointerFieldOffset = kUniqueIdOffset;
6913 // Just to not break the postmortrem support with conditional offsets
6914 static const int kUniqueIdOffset = kFeedbackVectorOffset;
6915 static const int kLastPointerFieldOffset = kFeedbackVectorOffset;
6918 #if V8_HOST_ARCH_32_BIT
6920 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6921 static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
6922 static const int kExpectedNofPropertiesOffset =
6923 kFormalParameterCountOffset + kPointerSize;
6924 static const int kNumLiteralsOffset =
6925 kExpectedNofPropertiesOffset + kPointerSize;
6926 static const int kStartPositionAndTypeOffset =
6927 kNumLiteralsOffset + kPointerSize;
6928 static const int kEndPositionOffset =
6929 kStartPositionAndTypeOffset + kPointerSize;
6930 static const int kFunctionTokenPositionOffset =
6931 kEndPositionOffset + kPointerSize;
6932 static const int kCompilerHintsOffset =
6933 kFunctionTokenPositionOffset + kPointerSize;
6934 static const int kOptCountAndBailoutReasonOffset =
6935 kCompilerHintsOffset + kPointerSize;
6936 static const int kCountersOffset =
6937 kOptCountAndBailoutReasonOffset + kPointerSize;
6938 static const int kAstNodeCountOffset =
6939 kCountersOffset + kPointerSize;
6940 static const int kProfilerTicksOffset =
6941 kAstNodeCountOffset + kPointerSize;
6944 static const int kSize = kProfilerTicksOffset + kPointerSize;
6946 // The only reason to use smi fields instead of int fields
6947 // is to allow iteration without maps decoding during
6948 // garbage collections.
6949 // To avoid wasting space on 64-bit architectures we use
6950 // the following trick: we group integer fields into pairs
6951 // The least significant integer in each pair is shifted left by 1.
6952 // By doing this we guarantee that LSB of each kPointerSize aligned
6953 // word is not set and thus this word cannot be treated as pointer
6954 // to HeapObject during old space traversal.
6955 #if V8_TARGET_LITTLE_ENDIAN
6956 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6957 static const int kFormalParameterCountOffset =
6958 kLengthOffset + kIntSize;
6960 static const int kExpectedNofPropertiesOffset =
6961 kFormalParameterCountOffset + kIntSize;
6962 static const int kNumLiteralsOffset =
6963 kExpectedNofPropertiesOffset + kIntSize;
6965 static const int kEndPositionOffset =
6966 kNumLiteralsOffset + kIntSize;
6967 static const int kStartPositionAndTypeOffset =
6968 kEndPositionOffset + kIntSize;
6970 static const int kFunctionTokenPositionOffset =
6971 kStartPositionAndTypeOffset + kIntSize;
6972 static const int kCompilerHintsOffset =
6973 kFunctionTokenPositionOffset + kIntSize;
6975 static const int kOptCountAndBailoutReasonOffset =
6976 kCompilerHintsOffset + kIntSize;
6977 static const int kCountersOffset =
6978 kOptCountAndBailoutReasonOffset + kIntSize;
6980 static const int kAstNodeCountOffset =
6981 kCountersOffset + kIntSize;
6982 static const int kProfilerTicksOffset =
6983 kAstNodeCountOffset + kIntSize;
6986 static const int kSize = kProfilerTicksOffset + kIntSize;
6988 #elif V8_TARGET_BIG_ENDIAN
6989 static const int kFormalParameterCountOffset =
6990 kLastPointerFieldOffset + kPointerSize;
6991 static const int kLengthOffset = kFormalParameterCountOffset + kIntSize;
6993 static const int kNumLiteralsOffset = kLengthOffset + kIntSize;
6994 static const int kExpectedNofPropertiesOffset = kNumLiteralsOffset + kIntSize;
6996 static const int kStartPositionAndTypeOffset =
6997 kExpectedNofPropertiesOffset + kIntSize;
6998 static const int kEndPositionOffset = kStartPositionAndTypeOffset + kIntSize;
7000 static const int kCompilerHintsOffset = kEndPositionOffset + kIntSize;
7001 static const int kFunctionTokenPositionOffset =
7002 kCompilerHintsOffset + kIntSize;
7004 static const int kCountersOffset = kFunctionTokenPositionOffset + kIntSize;
7005 static const int kOptCountAndBailoutReasonOffset = kCountersOffset + kIntSize;
7007 static const int kProfilerTicksOffset =
7008 kOptCountAndBailoutReasonOffset + kIntSize;
7009 static const int kAstNodeCountOffset = kProfilerTicksOffset + kIntSize;
7012 static const int kSize = kAstNodeCountOffset + kIntSize;
7015 #error Unknown byte ordering
7016 #endif // Big endian
7020 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
7022 typedef FixedBodyDescriptor<kNameOffset,
7023 kLastPointerFieldOffset + kPointerSize,
7024 kSize> BodyDescriptor;
7026 // Bit positions in start_position_and_type.
7027 // The source code start position is in the 30 most significant bits of
7028 // the start_position_and_type field.
7029 static const int kIsExpressionBit = 0;
7030 static const int kIsTopLevelBit = 1;
7031 static const int kStartPositionShift = 2;
7032 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
7034 // Bit positions in compiler_hints.
7035 enum CompilerHints {
7036 kAllowLazyCompilation,
7037 kAllowLazyCompilationWithoutContext,
7038 kOptimizationDisabled,
7039 kStrictModeFunction,
7040 kStrongModeFunction,
7043 kHasDuplicateParameters,
7048 kNameShouldPrintAsAnonymous,
7055 kIsAccessorFunction,
7056 kIsDefaultConstructor,
7057 kIsSubclassConstructor,
7063 kCompilerHintsCount // Pseudo entry
7065 // Add hints for other modes when they're added.
7066 STATIC_ASSERT(LANGUAGE_END == 3);
7068 class FunctionKindBits : public BitField<FunctionKind, kIsArrow, 8> {};
7070 class DeoptCountBits : public BitField<int, 0, 4> {};
7071 class OptReenableTriesBits : public BitField<int, 4, 18> {};
7072 class ICAgeBits : public BitField<int, 22, 8> {};
7074 class OptCountBits : public BitField<int, 0, 22> {};
7075 class DisabledOptimizationReasonBits : public BitField<int, 22, 8> {};
7078 #if V8_HOST_ARCH_32_BIT
7079 // On 32 bit platforms, compiler hints is a smi.
7080 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
7081 static const int kCompilerHintsSize = kPointerSize;
7083 // On 64 bit platforms, compiler hints is not a smi, see comment above.
7084 static const int kCompilerHintsSmiTagSize = 0;
7085 static const int kCompilerHintsSize = kIntSize;
7088 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
7089 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
7092 // Constants for optimizing codegen for strict mode function and
7094 // Allows to use byte-width instructions.
7095 static const int kStrictModeBitWithinByte =
7096 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
7097 static const int kStrongModeBitWithinByte =
7098 (kStrongModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
7100 static const int kNativeBitWithinByte =
7101 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
7103 #if defined(V8_TARGET_LITTLE_ENDIAN)
7104 static const int kStrictModeByteOffset = kCompilerHintsOffset +
7105 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
7106 static const int kStrongModeByteOffset =
7107 kCompilerHintsOffset +
7108 (kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
7109 static const int kNativeByteOffset = kCompilerHintsOffset +
7110 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
7111 #elif defined(V8_TARGET_BIG_ENDIAN)
7112 static const int kStrictModeByteOffset = kCompilerHintsOffset +
7113 (kCompilerHintsSize - 1) -
7114 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
7115 static const int kStrongModeByteOffset =
7116 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
7117 ((kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
7118 static const int kNativeByteOffset = kCompilerHintsOffset +
7119 (kCompilerHintsSize - 1) -
7120 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
7122 #error Unknown byte ordering
7126 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
7130 // Printing support.
7131 struct SourceCodeOf {
7132 explicit SourceCodeOf(SharedFunctionInfo* v, int max = -1)
7133 : value(v), max_length(max) {}
7134 const SharedFunctionInfo* value;
7139 std::ostream& operator<<(std::ostream& os, const SourceCodeOf& v);
7142 class JSGeneratorObject: public JSObject {
7144 // [function]: The function corresponding to this generator object.
7145 DECL_ACCESSORS(function, JSFunction)
7147 // [context]: The context of the suspended computation.
7148 DECL_ACCESSORS(context, Context)
7150 // [receiver]: The receiver of the suspended computation.
7151 DECL_ACCESSORS(receiver, Object)
7153 // [continuation]: Offset into code of continuation.
7155 // A positive offset indicates a suspended generator. The special
7156 // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
7157 // cannot be resumed.
7158 inline int continuation() const;
7159 inline void set_continuation(int continuation);
7160 inline bool is_closed();
7161 inline bool is_executing();
7162 inline bool is_suspended();
7164 // [operand_stack]: Saved operand stack.
7165 DECL_ACCESSORS(operand_stack, FixedArray)
7167 DECLARE_CAST(JSGeneratorObject)
7169 // Dispatched behavior.
7170 DECLARE_PRINTER(JSGeneratorObject)
7171 DECLARE_VERIFIER(JSGeneratorObject)
7173 // Magic sentinel values for the continuation.
7174 static const int kGeneratorExecuting = -1;
7175 static const int kGeneratorClosed = 0;
7177 // Layout description.
7178 static const int kFunctionOffset = JSObject::kHeaderSize;
7179 static const int kContextOffset = kFunctionOffset + kPointerSize;
7180 static const int kReceiverOffset = kContextOffset + kPointerSize;
7181 static const int kContinuationOffset = kReceiverOffset + kPointerSize;
7182 static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
7183 static const int kSize = kOperandStackOffset + kPointerSize;
7185 // Resume mode, for use by runtime functions.
7186 enum ResumeMode { NEXT, THROW };
7188 // Yielding from a generator returns an object with the following inobject
7189 // properties. See Context::iterator_result_map() for the map.
7190 static const int kResultValuePropertyIndex = 0;
7191 static const int kResultDonePropertyIndex = 1;
7192 static const int kResultPropertyCount = 2;
7194 static const int kResultValuePropertyOffset = JSObject::kHeaderSize;
7195 static const int kResultDonePropertyOffset =
7196 kResultValuePropertyOffset + kPointerSize;
7197 static const int kResultSize = kResultDonePropertyOffset + kPointerSize;
7200 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
7204 // Representation for module instance objects.
7205 class JSModule: public JSObject {
7207 // [context]: the context holding the module's locals, or undefined if none.
7208 DECL_ACCESSORS(context, Object)
7210 // [scope_info]: Scope info.
7211 DECL_ACCESSORS(scope_info, ScopeInfo)
7213 DECLARE_CAST(JSModule)
7215 // Dispatched behavior.
7216 DECLARE_PRINTER(JSModule)
7217 DECLARE_VERIFIER(JSModule)
7219 // Layout description.
7220 static const int kContextOffset = JSObject::kHeaderSize;
7221 static const int kScopeInfoOffset = kContextOffset + kPointerSize;
7222 static const int kSize = kScopeInfoOffset + kPointerSize;
7225 DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
7229 // JSFunction describes JavaScript functions.
7230 class JSFunction: public JSObject {
7232 // [prototype_or_initial_map]:
7233 DECL_ACCESSORS(prototype_or_initial_map, Object)
7235 // [shared]: The information about the function that
7236 // can be shared by instances.
7237 DECL_ACCESSORS(shared, SharedFunctionInfo)
7239 // [context]: The context for this function.
7240 inline Context* context();
7241 inline void set_context(Object* context);
7242 inline JSObject* global_proxy();
7244 // [code]: The generated code object for this function. Executed
7245 // when the function is invoked, e.g. foo() or new foo(). See
7246 // [[Call]] and [[Construct]] description in ECMA-262, section
7248 inline Code* code();
7249 inline void set_code(Code* code);
7250 inline void set_code_no_write_barrier(Code* code);
7251 inline void ReplaceCode(Code* code);
7253 // Tells whether this function is builtin.
7254 inline bool IsBuiltin();
7256 // Tells whether this function should be subject to debugging.
7257 inline bool IsSubjectToDebugging();
7259 // Tells whether or not the function needs arguments adaption.
7260 inline bool NeedsArgumentsAdaption();
7262 // Tells whether or not this function has been optimized.
7263 inline bool IsOptimized();
7265 // Mark this function for lazy recompilation. The function will be
7266 // recompiled the next time it is executed.
7267 void MarkForOptimization();
7268 void AttemptConcurrentOptimization();
7270 // Tells whether or not the function is already marked for lazy
7272 inline bool IsMarkedForOptimization();
7273 inline bool IsMarkedForConcurrentOptimization();
7275 // Tells whether or not the function is on the concurrent recompilation queue.
7276 inline bool IsInOptimizationQueue();
7278 // Inobject slack tracking is the way to reclaim unused inobject space.
7280 // The instance size is initially determined by adding some slack to
7281 // expected_nof_properties (to allow for a few extra properties added
7282 // after the constructor). There is no guarantee that the extra space
7283 // will not be wasted.
7285 // Here is the algorithm to reclaim the unused inobject space:
7286 // - Detect the first constructor call for this JSFunction.
7287 // When it happens enter the "in progress" state: initialize construction
7288 // counter in the initial_map.
7289 // - While the tracking is in progress create objects filled with
7290 // one_pointer_filler_map instead of undefined_value. This way they can be
7291 // resized quickly and safely.
7292 // - Once enough objects have been created compute the 'slack'
7293 // (traverse the map transition tree starting from the
7294 // initial_map and find the lowest value of unused_property_fields).
7295 // - Traverse the transition tree again and decrease the instance size
7296 // of every map. Existing objects will resize automatically (they are
7297 // filled with one_pointer_filler_map). All further allocations will
7298 // use the adjusted instance size.
7299 // - SharedFunctionInfo's expected_nof_properties left unmodified since
7300 // allocations made using different closures could actually create different
7301 // kind of objects (see prototype inheritance pattern).
7303 // Important: inobject slack tracking is not attempted during the snapshot
7306 // True if the initial_map is set and the object constructions countdown
7307 // counter is not zero.
7308 static const int kGenerousAllocationCount =
7309 Map::kSlackTrackingCounterStart - Map::kSlackTrackingCounterEnd + 1;
7310 inline bool IsInobjectSlackTrackingInProgress();
7312 // Starts the tracking.
7313 // Initializes object constructions countdown counter in the initial map.
7314 void StartInobjectSlackTracking();
7316 // Completes the tracking.
7317 void CompleteInobjectSlackTracking();
7319 // [literals_or_bindings]: Fixed array holding either
7320 // the materialized literals or the bindings of a bound function.
7322 // If the function contains object, regexp or array literals, the
7323 // literals array prefix contains the object, regexp, and array
7324 // function to be used when creating these literals. This is
7325 // necessary so that we do not dynamically lookup the object, regexp
7326 // or array functions. Performing a dynamic lookup, we might end up
7327 // using the functions from a new context that we should not have
7330 // On bound functions, the array is a (copy-on-write) fixed-array containing
7331 // the function that was bound, bound this-value and any bound
7332 // arguments. Bound functions never contain literals.
7333 DECL_ACCESSORS(literals_or_bindings, FixedArray)
7335 inline FixedArray* literals();
7336 inline void set_literals(FixedArray* literals);
7338 inline FixedArray* function_bindings();
7339 inline void set_function_bindings(FixedArray* bindings);
7341 // The initial map for an object created by this constructor.
7342 inline Map* initial_map();
7343 static void SetInitialMap(Handle<JSFunction> function, Handle<Map> map,
7344 Handle<Object> prototype);
7345 inline bool has_initial_map();
7346 static void EnsureHasInitialMap(Handle<JSFunction> function);
7348 // Get and set the prototype property on a JSFunction. If the
7349 // function has an initial map the prototype is set on the initial
7350 // map. Otherwise, the prototype is put in the initial map field
7351 // until an initial map is needed.
7352 inline bool has_prototype();
7353 inline bool has_instance_prototype();
7354 inline Object* prototype();
7355 inline Object* instance_prototype();
7356 static void SetPrototype(Handle<JSFunction> function,
7357 Handle<Object> value);
7358 static void SetInstancePrototype(Handle<JSFunction> function,
7359 Handle<Object> value);
7361 // Creates a new closure for the fucntion with the same bindings,
7362 // bound values, and prototype. An equivalent of spec operations
7363 // ``CloneMethod`` and ``CloneBoundFunction``.
7364 static Handle<JSFunction> CloneClosure(Handle<JSFunction> function);
7366 // After prototype is removed, it will not be created when accessed, and
7367 // [[Construct]] from this function will not be allowed.
7368 bool RemovePrototype();
7369 inline bool should_have_prototype();
7371 // Accessor for this function's initial map's [[class]]
7372 // property. This is primarily used by ECMA native functions. This
7373 // method sets the class_name field of this function's initial map
7374 // to a given value. It creates an initial map if this function does
7375 // not have one. Note that this method does not copy the initial map
7376 // if it has one already, but simply replaces it with the new value.
7377 // Instances created afterwards will have a map whose [[class]] is
7378 // set to 'value', but there is no guarantees on instances created
7380 void SetInstanceClassName(String* name);
7382 // Returns if this function has been compiled to native code yet.
7383 inline bool is_compiled();
7385 // Returns `false` if formal parameters include rest parameters, optional
7386 // parameters, or destructuring parameters.
7387 // TODO(caitp): make this a flag set during parsing
7388 inline bool is_simple_parameter_list();
7390 // [next_function_link]: Links functions into various lists, e.g. the list
7391 // of optimized functions hanging off the native_context. The CodeFlusher
7392 // uses this link to chain together flushing candidates. Treated weakly
7393 // by the garbage collector.
7394 DECL_ACCESSORS(next_function_link, Object)
7396 // Prints the name of the function using PrintF.
7397 void PrintName(FILE* out = stdout);
7399 DECLARE_CAST(JSFunction)
7401 // Iterates the objects, including code objects indirectly referenced
7402 // through pointers to the first instruction in the code object.
7403 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
7405 // Dispatched behavior.
7406 DECLARE_PRINTER(JSFunction)
7407 DECLARE_VERIFIER(JSFunction)
7409 // Returns the number of allocated literals.
7410 inline int NumberOfLiterals();
7412 // Used for flags such as --hydrogen-filter.
7413 bool PassesFilter(const char* raw_filter);
7415 // The function's name if it is configured, otherwise shared function info
7417 static Handle<String> GetDebugName(Handle<JSFunction> function);
7419 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
7420 // kSize) is weak and has special handling during garbage collection.
7421 static const int kCodeEntryOffset = JSObject::kHeaderSize;
7422 static const int kPrototypeOrInitialMapOffset =
7423 kCodeEntryOffset + kPointerSize;
7424 static const int kSharedFunctionInfoOffset =
7425 kPrototypeOrInitialMapOffset + kPointerSize;
7426 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
7427 static const int kLiteralsOffset = kContextOffset + kPointerSize;
7428 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
7429 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
7430 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
7432 // Layout of the bound-function binding array.
7433 static const int kBoundFunctionIndex = 0;
7434 static const int kBoundThisIndex = 1;
7435 static const int kBoundArgumentsStartIndex = 2;
7438 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7442 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7443 // and the prototype is hidden. JSGlobalProxy always delegates
7444 // property accesses to its prototype if the prototype is not null.
7446 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7448 // Accessing a JSGlobalProxy requires security check.
7450 class JSGlobalProxy : public JSObject {
7452 // [native_context]: the owner native context of this global proxy object.
7453 // It is null value if this object is not used by any context.
7454 DECL_ACCESSORS(native_context, Object)
7456 // [hash]: The hash code property (undefined if not initialized yet).
7457 DECL_ACCESSORS(hash, Object)
7459 DECLARE_CAST(JSGlobalProxy)
7461 inline bool IsDetachedFrom(GlobalObject* global) const;
7463 // Dispatched behavior.
7464 DECLARE_PRINTER(JSGlobalProxy)
7465 DECLARE_VERIFIER(JSGlobalProxy)
7467 // Layout description.
7468 static const int kNativeContextOffset = JSObject::kHeaderSize;
7469 static const int kHashOffset = kNativeContextOffset + kPointerSize;
7470 static const int kSize = kHashOffset + kPointerSize;
7473 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7477 // Common super class for JavaScript global objects and the special
7478 // builtins global objects.
7479 class GlobalObject: public JSObject {
7481 // [builtins]: the object holding the runtime routines written in JS.
7482 DECL_ACCESSORS(builtins, JSBuiltinsObject)
7484 // [native context]: the natives corresponding to this global object.
7485 DECL_ACCESSORS(native_context, Context)
7487 // [global proxy]: the global proxy object of the context
7488 DECL_ACCESSORS(global_proxy, JSObject)
7490 DECLARE_CAST(GlobalObject)
7492 static void InvalidatePropertyCell(Handle<GlobalObject> object,
7494 // Ensure that the global object has a cell for the given property name.
7495 static Handle<PropertyCell> EnsurePropertyCell(Handle<GlobalObject> global,
7498 // Layout description.
7499 static const int kBuiltinsOffset = JSObject::kHeaderSize;
7500 static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7501 static const int kGlobalProxyOffset = kNativeContextOffset + kPointerSize;
7502 static const int kHeaderSize = kGlobalProxyOffset + kPointerSize;
7505 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7509 // JavaScript global object.
7510 class JSGlobalObject: public GlobalObject {
7512 DECLARE_CAST(JSGlobalObject)
7514 inline bool IsDetached();
7516 // Dispatched behavior.
7517 DECLARE_PRINTER(JSGlobalObject)
7518 DECLARE_VERIFIER(JSGlobalObject)
7520 // Layout description.
7521 static const int kSize = GlobalObject::kHeaderSize;
7524 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7528 // Builtins global object which holds the runtime routines written in
7530 class JSBuiltinsObject: public GlobalObject {
7532 // Accessors for the runtime routines written in JavaScript.
7533 inline Object* javascript_builtin(Builtins::JavaScript id);
7534 inline void set_javascript_builtin(Builtins::JavaScript id, Object* value);
7536 DECLARE_CAST(JSBuiltinsObject)
7538 // Dispatched behavior.
7539 DECLARE_PRINTER(JSBuiltinsObject)
7540 DECLARE_VERIFIER(JSBuiltinsObject)
7542 // Layout description. The size of the builtins object includes
7543 // room for two pointers per runtime routine written in javascript
7544 // (function and code object).
7545 static const int kJSBuiltinsCount = Builtins::id_count;
7546 static const int kJSBuiltinsOffset = GlobalObject::kHeaderSize;
7547 static const int kSize =
7548 GlobalObject::kHeaderSize + (kJSBuiltinsCount * kPointerSize);
7550 static int OffsetOfFunctionWithId(Builtins::JavaScript id) {
7551 return kJSBuiltinsOffset + id * kPointerSize;
7555 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7559 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
7560 class JSValue: public JSObject {
7562 // [value]: the object being wrapped.
7563 DECL_ACCESSORS(value, Object)
7565 DECLARE_CAST(JSValue)
7567 // Dispatched behavior.
7568 DECLARE_PRINTER(JSValue)
7569 DECLARE_VERIFIER(JSValue)
7571 // Layout description.
7572 static const int kValueOffset = JSObject::kHeaderSize;
7573 static const int kSize = kValueOffset + kPointerSize;
7576 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
7582 // Representation for JS date objects.
7583 class JSDate: public JSObject {
7585 // If one component is NaN, all of them are, indicating a NaN time value.
7586 // [value]: the time value.
7587 DECL_ACCESSORS(value, Object)
7588 // [year]: caches year. Either undefined, smi, or NaN.
7589 DECL_ACCESSORS(year, Object)
7590 // [month]: caches month. Either undefined, smi, or NaN.
7591 DECL_ACCESSORS(month, Object)
7592 // [day]: caches day. Either undefined, smi, or NaN.
7593 DECL_ACCESSORS(day, Object)
7594 // [weekday]: caches day of week. Either undefined, smi, or NaN.
7595 DECL_ACCESSORS(weekday, Object)
7596 // [hour]: caches hours. Either undefined, smi, or NaN.
7597 DECL_ACCESSORS(hour, Object)
7598 // [min]: caches minutes. Either undefined, smi, or NaN.
7599 DECL_ACCESSORS(min, Object)
7600 // [sec]: caches seconds. Either undefined, smi, or NaN.
7601 DECL_ACCESSORS(sec, Object)
7602 // [cache stamp]: sample of the date cache stamp at the
7603 // moment when chached fields were cached.
7604 DECL_ACCESSORS(cache_stamp, Object)
7606 DECLARE_CAST(JSDate)
7608 // Returns the date field with the specified index.
7609 // See FieldIndex for the list of date fields.
7610 static Object* GetField(Object* date, Smi* index);
7612 void SetValue(Object* value, bool is_value_nan);
7615 // Dispatched behavior.
7616 DECLARE_PRINTER(JSDate)
7617 DECLARE_VERIFIER(JSDate)
7619 // The order is important. It must be kept in sync with date macros
7630 kFirstUncachedField,
7631 kMillisecond = kFirstUncachedField,
7635 kYearUTC = kFirstUTCField,
7648 // Layout description.
7649 static const int kValueOffset = JSObject::kHeaderSize;
7650 static const int kYearOffset = kValueOffset + kPointerSize;
7651 static const int kMonthOffset = kYearOffset + kPointerSize;
7652 static const int kDayOffset = kMonthOffset + kPointerSize;
7653 static const int kWeekdayOffset = kDayOffset + kPointerSize;
7654 static const int kHourOffset = kWeekdayOffset + kPointerSize;
7655 static const int kMinOffset = kHourOffset + kPointerSize;
7656 static const int kSecOffset = kMinOffset + kPointerSize;
7657 static const int kCacheStampOffset = kSecOffset + kPointerSize;
7658 static const int kSize = kCacheStampOffset + kPointerSize;
7661 inline Object* DoGetField(FieldIndex index);
7663 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
7665 // Computes and caches the cacheable fields of the date.
7666 inline void SetCachedFields(int64_t local_time_ms, DateCache* date_cache);
7669 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
7673 // Representation of message objects used for error reporting through
7674 // the API. The messages are formatted in JavaScript so this object is
7675 // a real JavaScript object. The information used for formatting the
7676 // error messages are not directly accessible from JavaScript to
7677 // prevent leaking information to user code called during error
7679 class JSMessageObject: public JSObject {
7681 // [type]: the type of error message.
7682 inline int type() const;
7683 inline void set_type(int value);
7685 // [arguments]: the arguments for formatting the error message.
7686 DECL_ACCESSORS(argument, Object)
7688 // [script]: the script from which the error message originated.
7689 DECL_ACCESSORS(script, Object)
7691 // [stack_frames]: an array of stack frames for this error object.
7692 DECL_ACCESSORS(stack_frames, Object)
7694 // [start_position]: the start position in the script for the error message.
7695 inline int start_position() const;
7696 inline void set_start_position(int value);
7698 // [end_position]: the end position in the script for the error message.
7699 inline int end_position() const;
7700 inline void set_end_position(int value);
7702 DECLARE_CAST(JSMessageObject)
7704 // Dispatched behavior.
7705 DECLARE_PRINTER(JSMessageObject)
7706 DECLARE_VERIFIER(JSMessageObject)
7708 // Layout description.
7709 static const int kTypeOffset = JSObject::kHeaderSize;
7710 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
7711 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
7712 static const int kStackFramesOffset = kScriptOffset + kPointerSize;
7713 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
7714 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
7715 static const int kSize = kEndPositionOffset + kPointerSize;
7717 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
7718 kStackFramesOffset + kPointerSize,
7719 kSize> BodyDescriptor;
7723 // Regular expressions
7724 // The regular expression holds a single reference to a FixedArray in
7725 // the kDataOffset field.
7726 // The FixedArray contains the following data:
7727 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
7728 // - reference to the original source string
7729 // - reference to the original flag string
7730 // If it is an atom regexp
7731 // - a reference to a literal string to search for
7732 // If it is an irregexp regexp:
7733 // - a reference to code for Latin1 inputs (bytecode or compiled), or a smi
7734 // used for tracking the last usage (used for code flushing).
7735 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
7736 // used for tracking the last usage (used for code flushing)..
7737 // - max number of registers used by irregexp implementations.
7738 // - number of capture registers (output values) of the regexp.
7739 class JSRegExp: public JSObject {
7742 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
7743 // ATOM: A simple string to match against using an indexOf operation.
7744 // IRREGEXP: Compiled with Irregexp.
7745 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
7746 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
7753 UNICODE_ESCAPES = 16
7758 explicit Flags(uint32_t value) : value_(value) { }
7759 bool is_global() { return (value_ & GLOBAL) != 0; }
7760 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
7761 bool is_multiline() { return (value_ & MULTILINE) != 0; }
7762 bool is_sticky() { return (value_ & STICKY) != 0; }
7763 bool is_unicode() { return (value_ & UNICODE_ESCAPES) != 0; }
7764 uint32_t value() { return value_; }
7769 DECL_ACCESSORS(data, Object)
7771 inline Type TypeTag();
7772 inline int CaptureCount();
7773 inline Flags GetFlags();
7774 inline String* Pattern();
7775 inline Object* DataAt(int index);
7776 // Set implementation data after the object has been prepared.
7777 inline void SetDataAt(int index, Object* value);
7779 static int code_index(bool is_latin1) {
7781 return kIrregexpLatin1CodeIndex;
7783 return kIrregexpUC16CodeIndex;
7787 static int saved_code_index(bool is_latin1) {
7789 return kIrregexpLatin1CodeSavedIndex;
7791 return kIrregexpUC16CodeSavedIndex;
7795 DECLARE_CAST(JSRegExp)
7797 // Dispatched behavior.
7798 DECLARE_VERIFIER(JSRegExp)
7800 static const int kDataOffset = JSObject::kHeaderSize;
7801 static const int kSize = kDataOffset + kPointerSize;
7803 // Indices in the data array.
7804 static const int kTagIndex = 0;
7805 static const int kSourceIndex = kTagIndex + 1;
7806 static const int kFlagsIndex = kSourceIndex + 1;
7807 static const int kDataIndex = kFlagsIndex + 1;
7808 // The data fields are used in different ways depending on the
7809 // value of the tag.
7810 // Atom regexps (literal strings).
7811 static const int kAtomPatternIndex = kDataIndex;
7813 static const int kAtomDataSize = kAtomPatternIndex + 1;
7815 // Irregexp compiled code or bytecode for Latin1. If compilation
7816 // fails, this fields hold an exception object that should be
7817 // thrown if the regexp is used again.
7818 static const int kIrregexpLatin1CodeIndex = kDataIndex;
7819 // Irregexp compiled code or bytecode for UC16. If compilation
7820 // fails, this fields hold an exception object that should be
7821 // thrown if the regexp is used again.
7822 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
7824 // Saved instance of Irregexp compiled code or bytecode for Latin1 that
7825 // is a potential candidate for flushing.
7826 static const int kIrregexpLatin1CodeSavedIndex = kDataIndex + 2;
7827 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
7828 // a potential candidate for flushing.
7829 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
7831 // Maximal number of registers used by either Latin1 or UC16.
7832 // Only used to check that there is enough stack space
7833 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
7834 // Number of captures in the compiled regexp.
7835 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
7837 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
7839 // Offsets directly into the data fixed array.
7840 static const int kDataTagOffset =
7841 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
7842 static const int kDataOneByteCodeOffset =
7843 FixedArray::kHeaderSize + kIrregexpLatin1CodeIndex * kPointerSize;
7844 static const int kDataUC16CodeOffset =
7845 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
7846 static const int kIrregexpCaptureCountOffset =
7847 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
7849 // In-object fields.
7850 static const int kSourceFieldIndex = 0;
7851 static const int kGlobalFieldIndex = 1;
7852 static const int kIgnoreCaseFieldIndex = 2;
7853 static const int kMultilineFieldIndex = 3;
7854 static const int kLastIndexFieldIndex = 4;
7855 static const int kInObjectFieldCount = 5;
7857 // The uninitialized value for a regexp code object.
7858 static const int kUninitializedValue = -1;
7860 // The compilation error value for the regexp code object. The real error
7861 // object is in the saved code field.
7862 static const int kCompilationErrorValue = -2;
7864 // When we store the sweep generation at which we moved the code from the
7865 // code index to the saved code index we mask it of to be in the [0:255]
7867 static const int kCodeAgeMask = 0xff;
7871 class CompilationCacheShape : public BaseShape<HashTableKey*> {
7873 static inline bool IsMatch(HashTableKey* key, Object* value) {
7874 return key->IsMatch(value);
7877 static inline uint32_t Hash(HashTableKey* key) {
7881 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7882 return key->HashForObject(object);
7885 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7887 static const int kPrefixSize = 0;
7888 static const int kEntrySize = 2;
7892 // This cache is used in two different variants. For regexp caching, it simply
7893 // maps identifying info of the regexp to the cached regexp object. Scripts and
7894 // eval code only gets cached after a second probe for the code object. To do
7895 // so, on first "put" only a hash identifying the source is entered into the
7896 // cache, mapping it to a lifetime count of the hash. On each call to Age all
7897 // such lifetimes get reduced, and removed once they reach zero. If a second put
7898 // is called while such a hash is live in the cache, the hash gets replaced by
7899 // an actual cache entry. Age also removes stale live entries from the cache.
7900 // Such entries are identified by SharedFunctionInfos pointing to either the
7901 // recompilation stub, or to "old" code. This avoids memory leaks due to
7902 // premature caching of scripts and eval strings that are never needed later.
7903 class CompilationCacheTable: public HashTable<CompilationCacheTable,
7904 CompilationCacheShape,
7907 // Find cached value for a string key, otherwise return null.
7908 Handle<Object> Lookup(
7909 Handle<String> src, Handle<Context> context, LanguageMode language_mode);
7910 Handle<Object> LookupEval(
7911 Handle<String> src, Handle<SharedFunctionInfo> shared,
7912 LanguageMode language_mode, int scope_position);
7913 Handle<Object> LookupRegExp(Handle<String> source, JSRegExp::Flags flags);
7914 static Handle<CompilationCacheTable> Put(
7915 Handle<CompilationCacheTable> cache, Handle<String> src,
7916 Handle<Context> context, LanguageMode language_mode,
7917 Handle<Object> value);
7918 static Handle<CompilationCacheTable> PutEval(
7919 Handle<CompilationCacheTable> cache, Handle<String> src,
7920 Handle<SharedFunctionInfo> context, Handle<SharedFunctionInfo> value,
7921 int scope_position);
7922 static Handle<CompilationCacheTable> PutRegExp(
7923 Handle<CompilationCacheTable> cache, Handle<String> src,
7924 JSRegExp::Flags flags, Handle<FixedArray> value);
7925 void Remove(Object* value);
7927 static const int kHashGenerations = 10;
7929 DECLARE_CAST(CompilationCacheTable)
7932 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
7936 class CodeCache: public Struct {
7938 DECL_ACCESSORS(default_cache, FixedArray)
7939 DECL_ACCESSORS(normal_type_cache, Object)
7941 // Add the code object to the cache.
7943 Handle<CodeCache> cache, Handle<Name> name, Handle<Code> code);
7945 // Lookup code object in the cache. Returns code object if found and undefined
7947 Object* Lookup(Name* name, Code::Flags flags);
7949 // Get the internal index of a code object in the cache. Returns -1 if the
7950 // code object is not in that cache. This index can be used to later call
7951 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
7953 int GetIndex(Object* name, Code* code);
7955 // Remove an object from the cache with the provided internal index.
7956 void RemoveByIndex(Object* name, Code* code, int index);
7958 DECLARE_CAST(CodeCache)
7960 // Dispatched behavior.
7961 DECLARE_PRINTER(CodeCache)
7962 DECLARE_VERIFIER(CodeCache)
7964 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
7965 static const int kNormalTypeCacheOffset =
7966 kDefaultCacheOffset + kPointerSize;
7967 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
7970 static void UpdateDefaultCache(
7971 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7972 static void UpdateNormalTypeCache(
7973 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7974 Object* LookupDefaultCache(Name* name, Code::Flags flags);
7975 Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
7977 // Code cache layout of the default cache. Elements are alternating name and
7978 // code objects for non normal load/store/call IC's.
7979 static const int kCodeCacheEntrySize = 2;
7980 static const int kCodeCacheEntryNameOffset = 0;
7981 static const int kCodeCacheEntryCodeOffset = 1;
7983 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
7987 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
7989 static inline bool IsMatch(HashTableKey* key, Object* value) {
7990 return key->IsMatch(value);
7993 static inline uint32_t Hash(HashTableKey* key) {
7997 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7998 return key->HashForObject(object);
8001 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
8003 static const int kPrefixSize = 0;
8004 static const int kEntrySize = 2;
8008 class CodeCacheHashTable: public HashTable<CodeCacheHashTable,
8009 CodeCacheHashTableShape,
8012 Object* Lookup(Name* name, Code::Flags flags);
8013 static Handle<CodeCacheHashTable> Put(
8014 Handle<CodeCacheHashTable> table,
8018 int GetIndex(Name* name, Code::Flags flags);
8019 void RemoveByIndex(int index);
8021 DECLARE_CAST(CodeCacheHashTable)
8023 // Initial size of the fixed array backing the hash table.
8024 static const int kInitialSize = 64;
8027 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
8031 class PolymorphicCodeCache: public Struct {
8033 DECL_ACCESSORS(cache, Object)
8035 static void Update(Handle<PolymorphicCodeCache> cache,
8036 MapHandleList* maps,
8041 // Returns an undefined value if the entry is not found.
8042 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
8044 DECLARE_CAST(PolymorphicCodeCache)
8046 // Dispatched behavior.
8047 DECLARE_PRINTER(PolymorphicCodeCache)
8048 DECLARE_VERIFIER(PolymorphicCodeCache)
8050 static const int kCacheOffset = HeapObject::kHeaderSize;
8051 static const int kSize = kCacheOffset + kPointerSize;
8054 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
8058 class PolymorphicCodeCacheHashTable
8059 : public HashTable<PolymorphicCodeCacheHashTable,
8060 CodeCacheHashTableShape,
8063 Object* Lookup(MapHandleList* maps, int code_kind);
8065 static Handle<PolymorphicCodeCacheHashTable> Put(
8066 Handle<PolymorphicCodeCacheHashTable> hash_table,
8067 MapHandleList* maps,
8071 DECLARE_CAST(PolymorphicCodeCacheHashTable)
8073 static const int kInitialSize = 64;
8075 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
8079 class TypeFeedbackInfo: public Struct {
8081 inline int ic_total_count();
8082 inline void set_ic_total_count(int count);
8084 inline int ic_with_type_info_count();
8085 inline void change_ic_with_type_info_count(int delta);
8087 inline int ic_generic_count();
8088 inline void change_ic_generic_count(int delta);
8090 inline void initialize_storage();
8092 inline void change_own_type_change_checksum();
8093 inline int own_type_change_checksum();
8095 inline void set_inlined_type_change_checksum(int checksum);
8096 inline bool matches_inlined_type_change_checksum(int checksum);
8098 DECLARE_CAST(TypeFeedbackInfo)
8100 // Dispatched behavior.
8101 DECLARE_PRINTER(TypeFeedbackInfo)
8102 DECLARE_VERIFIER(TypeFeedbackInfo)
8104 static const int kStorage1Offset = HeapObject::kHeaderSize;
8105 static const int kStorage2Offset = kStorage1Offset + kPointerSize;
8106 static const int kStorage3Offset = kStorage2Offset + kPointerSize;
8107 static const int kSize = kStorage3Offset + kPointerSize;
8110 static const int kTypeChangeChecksumBits = 7;
8112 class ICTotalCountField: public BitField<int, 0,
8113 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
8114 class OwnTypeChangeChecksum: public BitField<int,
8115 kSmiValueSize - kTypeChangeChecksumBits,
8116 kTypeChangeChecksumBits> {}; // NOLINT
8117 class ICsWithTypeInfoCountField: public BitField<int, 0,
8118 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
8119 class InlinedTypeChangeChecksum: public BitField<int,
8120 kSmiValueSize - kTypeChangeChecksumBits,
8121 kTypeChangeChecksumBits> {}; // NOLINT
8123 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
8127 enum AllocationSiteMode {
8128 DONT_TRACK_ALLOCATION_SITE,
8129 TRACK_ALLOCATION_SITE,
8130 LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
8134 class AllocationSite: public Struct {
8136 static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
8137 static const double kPretenureRatio;
8138 static const int kPretenureMinimumCreated = 100;
8140 // Values for pretenure decision field.
8141 enum PretenureDecision {
8147 kLastPretenureDecisionValue = kZombie
8150 const char* PretenureDecisionName(PretenureDecision decision);
8152 DECL_ACCESSORS(transition_info, Object)
8153 // nested_site threads a list of sites that represent nested literals
8154 // walked in a particular order. So [[1, 2], 1, 2] will have one
8155 // nested_site, but [[1, 2], 3, [4]] will have a list of two.
8156 DECL_ACCESSORS(nested_site, Object)
8157 DECL_ACCESSORS(pretenure_data, Smi)
8158 DECL_ACCESSORS(pretenure_create_count, Smi)
8159 DECL_ACCESSORS(dependent_code, DependentCode)
8160 DECL_ACCESSORS(weak_next, Object)
8162 inline void Initialize();
8164 // This method is expensive, it should only be called for reporting.
8165 bool IsNestedSite();
8167 // transition_info bitfields, for constructed array transition info.
8168 class ElementsKindBits: public BitField<ElementsKind, 0, 15> {};
8169 class UnusedBits: public BitField<int, 15, 14> {};
8170 class DoNotInlineBit: public BitField<bool, 29, 1> {};
8172 // Bitfields for pretenure_data
8173 class MementoFoundCountBits: public BitField<int, 0, 26> {};
8174 class PretenureDecisionBits: public BitField<PretenureDecision, 26, 3> {};
8175 class DeoptDependentCodeBit: public BitField<bool, 29, 1> {};
8176 STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
8178 // Increments the mementos found counter and returns true when the first
8179 // memento was found for a given allocation site.
8180 inline bool IncrementMementoFoundCount();
8182 inline void IncrementMementoCreateCount();
8184 PretenureFlag GetPretenureMode();
8186 void ResetPretenureDecision();
8188 PretenureDecision pretenure_decision() {
8189 int value = pretenure_data()->value();
8190 return PretenureDecisionBits::decode(value);
8193 void set_pretenure_decision(PretenureDecision decision) {
8194 int value = pretenure_data()->value();
8196 Smi::FromInt(PretenureDecisionBits::update(value, decision)),
8197 SKIP_WRITE_BARRIER);
8200 bool deopt_dependent_code() {
8201 int value = pretenure_data()->value();
8202 return DeoptDependentCodeBit::decode(value);
8205 void set_deopt_dependent_code(bool deopt) {
8206 int value = pretenure_data()->value();
8208 Smi::FromInt(DeoptDependentCodeBit::update(value, deopt)),
8209 SKIP_WRITE_BARRIER);
8212 int memento_found_count() {
8213 int value = pretenure_data()->value();
8214 return MementoFoundCountBits::decode(value);
8217 inline void set_memento_found_count(int count);
8219 int memento_create_count() {
8220 return pretenure_create_count()->value();
8223 void set_memento_create_count(int count) {
8224 set_pretenure_create_count(Smi::FromInt(count), SKIP_WRITE_BARRIER);
8227 // The pretenuring decision is made during gc, and the zombie state allows
8228 // us to recognize when an allocation site is just being kept alive because
8229 // a later traversal of new space may discover AllocationMementos that point
8230 // to this AllocationSite.
8232 return pretenure_decision() == kZombie;
8235 bool IsMaybeTenure() {
8236 return pretenure_decision() == kMaybeTenure;
8239 inline void MarkZombie();
8241 inline bool MakePretenureDecision(PretenureDecision current_decision,
8243 bool maximum_size_scavenge);
8245 inline bool DigestPretenuringFeedback(bool maximum_size_scavenge);
8247 ElementsKind GetElementsKind() {
8248 DCHECK(!SitePointsToLiteral());
8249 int value = Smi::cast(transition_info())->value();
8250 return ElementsKindBits::decode(value);
8253 void SetElementsKind(ElementsKind kind) {
8254 int value = Smi::cast(transition_info())->value();
8255 set_transition_info(Smi::FromInt(ElementsKindBits::update(value, kind)),
8256 SKIP_WRITE_BARRIER);
8259 bool CanInlineCall() {
8260 int value = Smi::cast(transition_info())->value();
8261 return DoNotInlineBit::decode(value) == 0;
8264 void SetDoNotInlineCall() {
8265 int value = Smi::cast(transition_info())->value();
8266 set_transition_info(Smi::FromInt(DoNotInlineBit::update(value, true)),
8267 SKIP_WRITE_BARRIER);
8270 bool SitePointsToLiteral() {
8271 // If transition_info is a smi, then it represents an ElementsKind
8272 // for a constructed array. Otherwise, it must be a boilerplate
8273 // for an object or array literal.
8274 return transition_info()->IsJSArray() || transition_info()->IsJSObject();
8277 static void DigestTransitionFeedback(Handle<AllocationSite> site,
8278 ElementsKind to_kind);
8280 DECLARE_PRINTER(AllocationSite)
8281 DECLARE_VERIFIER(AllocationSite)
8283 DECLARE_CAST(AllocationSite)
8284 static inline AllocationSiteMode GetMode(
8285 ElementsKind boilerplate_elements_kind);
8286 static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
8287 static inline bool CanTrack(InstanceType type);
8289 static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
8290 static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
8291 static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
8292 static const int kPretenureCreateCountOffset =
8293 kPretenureDataOffset + kPointerSize;
8294 static const int kDependentCodeOffset =
8295 kPretenureCreateCountOffset + kPointerSize;
8296 static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
8297 static const int kSize = kWeakNextOffset + kPointerSize;
8299 // During mark compact we need to take special care for the dependent code
8301 static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
8302 static const int kPointerFieldsEndOffset = kWeakNextOffset;
8304 // For other visitors, use the fixed body descriptor below.
8305 typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
8306 kDependentCodeOffset + kPointerSize,
8307 kSize> BodyDescriptor;
8310 bool PretenuringDecisionMade() {
8311 return pretenure_decision() != kUndecided;
8314 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
8318 class AllocationMemento: public Struct {
8320 static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
8321 static const int kSize = kAllocationSiteOffset + kPointerSize;
8323 DECL_ACCESSORS(allocation_site, Object)
8326 return allocation_site()->IsAllocationSite() &&
8327 !AllocationSite::cast(allocation_site())->IsZombie();
8329 AllocationSite* GetAllocationSite() {
8331 return AllocationSite::cast(allocation_site());
8334 DECLARE_PRINTER(AllocationMemento)
8335 DECLARE_VERIFIER(AllocationMemento)
8337 DECLARE_CAST(AllocationMemento)
8340 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
8344 // Representation of a slow alias as part of a sloppy arguments objects.
8345 // For fast aliases (if HasSloppyArgumentsElements()):
8346 // - the parameter map contains an index into the context
8347 // - all attributes of the element have default values
8348 // For slow aliases (if HasDictionaryArgumentsElements()):
8349 // - the parameter map contains no fast alias mapping (i.e. the hole)
8350 // - this struct (in the slow backing store) contains an index into the context
8351 // - all attributes are available as part if the property details
8352 class AliasedArgumentsEntry: public Struct {
8354 inline int aliased_context_slot() const;
8355 inline void set_aliased_context_slot(int count);
8357 DECLARE_CAST(AliasedArgumentsEntry)
8359 // Dispatched behavior.
8360 DECLARE_PRINTER(AliasedArgumentsEntry)
8361 DECLARE_VERIFIER(AliasedArgumentsEntry)
8363 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
8364 static const int kSize = kAliasedContextSlot + kPointerSize;
8367 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
8371 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
8372 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
8375 class StringHasher {
8377 explicit inline StringHasher(int length, uint32_t seed);
8379 template <typename schar>
8380 static inline uint32_t HashSequentialString(const schar* chars,
8384 // Reads all the data, even for long strings and computes the utf16 length.
8385 static uint32_t ComputeUtf8Hash(Vector<const char> chars,
8387 int* utf16_length_out);
8389 // Calculated hash value for a string consisting of 1 to
8390 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
8391 // value is represented decimal value.
8392 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
8394 // No string is allowed to have a hash of zero. That value is reserved
8395 // for internal properties. If the hash calculation yields zero then we
8397 static const int kZeroHash = 27;
8399 // Reusable parts of the hashing algorithm.
8400 INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
8401 INLINE(static uint32_t GetHashCore(uint32_t running_hash));
8402 INLINE(static uint32_t ComputeRunningHash(uint32_t running_hash,
8403 const uc16* chars, int length));
8404 INLINE(static uint32_t ComputeRunningHashOneByte(uint32_t running_hash,
8409 // Returns the value to store in the hash field of a string with
8410 // the given length and contents.
8411 uint32_t GetHashField();
8412 // Returns true if the hash of this string can be computed without
8413 // looking at the contents.
8414 inline bool has_trivial_hash();
8415 // Adds a block of characters to the hash.
8416 template<typename Char>
8417 inline void AddCharacters(const Char* chars, int len);
8420 // Add a character to the hash.
8421 inline void AddCharacter(uint16_t c);
8422 // Update index. Returns true if string is still an index.
8423 inline bool UpdateIndex(uint16_t c);
8426 uint32_t raw_running_hash_;
8427 uint32_t array_index_;
8428 bool is_array_index_;
8429 bool is_first_char_;
8430 DISALLOW_COPY_AND_ASSIGN(StringHasher);
8434 class IteratingStringHasher : public StringHasher {
8436 static inline uint32_t Hash(String* string, uint32_t seed);
8437 inline void VisitOneByteString(const uint8_t* chars, int length);
8438 inline void VisitTwoByteString(const uint16_t* chars, int length);
8441 inline IteratingStringHasher(int len, uint32_t seed)
8442 : StringHasher(len, seed) {}
8443 void VisitConsString(ConsString* cons_string);
8444 DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher);
8448 // The characteristics of a string are stored in its map. Retrieving these
8449 // few bits of information is moderately expensive, involving two memory
8450 // loads where the second is dependent on the first. To improve efficiency
8451 // the shape of the string is given its own class so that it can be retrieved
8452 // once and used for several string operations. A StringShape is small enough
8453 // to be passed by value and is immutable, but be aware that flattening a
8454 // string can potentially alter its shape. Also be aware that a GC caused by
8455 // something else can alter the shape of a string due to ConsString
8456 // shortcutting. Keeping these restrictions in mind has proven to be error-
8457 // prone and so we no longer put StringShapes in variables unless there is a
8458 // concrete performance benefit at that particular point in the code.
8459 class StringShape BASE_EMBEDDED {
8461 inline explicit StringShape(const String* s);
8462 inline explicit StringShape(Map* s);
8463 inline explicit StringShape(InstanceType t);
8464 inline bool IsSequential();
8465 inline bool IsExternal();
8466 inline bool IsCons();
8467 inline bool IsSliced();
8468 inline bool IsIndirect();
8469 inline bool IsExternalOneByte();
8470 inline bool IsExternalTwoByte();
8471 inline bool IsSequentialOneByte();
8472 inline bool IsSequentialTwoByte();
8473 inline bool IsInternalized();
8474 inline StringRepresentationTag representation_tag();
8475 inline uint32_t encoding_tag();
8476 inline uint32_t full_representation_tag();
8477 inline uint32_t size_tag();
8479 inline uint32_t type() { return type_; }
8480 inline void invalidate() { valid_ = false; }
8481 inline bool valid() { return valid_; }
8483 inline void invalidate() { }
8489 inline void set_valid() { valid_ = true; }
8492 inline void set_valid() { }
8497 // The Name abstract class captures anything that can be used as a property
8498 // name, i.e., strings and symbols. All names store a hash value.
8499 class Name: public HeapObject {
8501 // Get and set the hash field of the name.
8502 inline uint32_t hash_field();
8503 inline void set_hash_field(uint32_t value);
8505 // Tells whether the hash code has been computed.
8506 inline bool HasHashCode();
8508 // Returns a hash value used for the property table
8509 inline uint32_t Hash();
8511 // Equality operations.
8512 inline bool Equals(Name* other);
8513 inline static bool Equals(Handle<Name> one, Handle<Name> two);
8516 inline bool AsArrayIndex(uint32_t* index);
8518 // If the name is private, it can only name own properties.
8519 inline bool IsPrivate();
8521 // If the name is a non-flat string, this method returns a flat version of the
8522 // string. Otherwise it'll just return the input.
8523 static inline Handle<Name> Flatten(Handle<Name> name,
8524 PretenureFlag pretenure = NOT_TENURED);
8528 DECLARE_PRINTER(Name)
8530 void NameShortPrint();
8531 int NameShortPrint(Vector<char> str);
8534 // Layout description.
8535 static const int kHashFieldSlot = HeapObject::kHeaderSize;
8536 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
8537 static const int kHashFieldOffset = kHashFieldSlot;
8539 static const int kHashFieldOffset = kHashFieldSlot + kIntSize;
8541 static const int kSize = kHashFieldSlot + kPointerSize;
8543 // Mask constant for checking if a name has a computed hash code
8544 // and if it is a string that is an array index. The least significant bit
8545 // indicates whether a hash code has been computed. If the hash code has
8546 // been computed the 2nd bit tells whether the string can be used as an
8548 static const int kHashNotComputedMask = 1;
8549 static const int kIsNotArrayIndexMask = 1 << 1;
8550 static const int kNofHashBitFields = 2;
8552 // Shift constant retrieving hash code from hash field.
8553 static const int kHashShift = kNofHashBitFields;
8555 // Only these bits are relevant in the hash, since the top two are shifted
8557 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8559 // Array index strings this short can keep their index in the hash field.
8560 static const int kMaxCachedArrayIndexLength = 7;
8562 // For strings which are array indexes the hash value has the string length
8563 // mixed into the hash, mainly to avoid a hash value of zero which would be
8564 // the case for the string '0'. 24 bits are used for the array index value.
8565 static const int kArrayIndexValueBits = 24;
8566 static const int kArrayIndexLengthBits =
8567 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8569 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8571 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8572 kArrayIndexValueBits> {}; // NOLINT
8573 class ArrayIndexLengthBits : public BitField<unsigned int,
8574 kNofHashBitFields + kArrayIndexValueBits,
8575 kArrayIndexLengthBits> {}; // NOLINT
8577 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8578 // could use a mask to test if the length of string is less than or equal to
8579 // kMaxCachedArrayIndexLength.
8580 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8582 static const unsigned int kContainsCachedArrayIndexMask =
8583 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8584 << ArrayIndexLengthBits::kShift) |
8585 kIsNotArrayIndexMask;
8587 // Value of empty hash field indicating that the hash is not computed.
8588 static const int kEmptyHashField =
8589 kIsNotArrayIndexMask | kHashNotComputedMask;
8592 static inline bool IsHashFieldComputed(uint32_t field);
8595 DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8600 class Symbol: public Name {
8602 // [name]: The print name of a symbol, or undefined if none.
8603 DECL_ACCESSORS(name, Object)
8605 DECL_ACCESSORS(flags, Smi)
8607 // [is_private]: Whether this is a private symbol. Private symbols can only
8608 // be used to designate own properties of objects.
8609 DECL_BOOLEAN_ACCESSORS(is_private)
8611 DECLARE_CAST(Symbol)
8613 // Dispatched behavior.
8614 DECLARE_PRINTER(Symbol)
8615 DECLARE_VERIFIER(Symbol)
8617 // Layout description.
8618 static const int kNameOffset = Name::kSize;
8619 static const int kFlagsOffset = kNameOffset + kPointerSize;
8620 static const int kSize = kFlagsOffset + kPointerSize;
8622 typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
8624 void SymbolShortPrint(std::ostream& os);
8627 static const int kPrivateBit = 0;
8629 const char* PrivateSymbolToName() const;
8632 friend class Name; // For PrivateSymbolToName.
8635 DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
8641 // The String abstract class captures JavaScript string values:
8644 // 4.3.16 String Value
8645 // A string value is a member of the type String and is a finite
8646 // ordered sequence of zero or more 16-bit unsigned integer values.
8648 // All string values have a length field.
8649 class String: public Name {
8651 enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
8653 // Array index strings this short can keep their index in the hash field.
8654 static const int kMaxCachedArrayIndexLength = 7;
8656 // For strings which are array indexes the hash value has the string length
8657 // mixed into the hash, mainly to avoid a hash value of zero which would be
8658 // the case for the string '0'. 24 bits are used for the array index value.
8659 static const int kArrayIndexValueBits = 24;
8660 static const int kArrayIndexLengthBits =
8661 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8663 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8665 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8666 kArrayIndexValueBits> {}; // NOLINT
8667 class ArrayIndexLengthBits : public BitField<unsigned int,
8668 kNofHashBitFields + kArrayIndexValueBits,
8669 kArrayIndexLengthBits> {}; // NOLINT
8671 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8672 // could use a mask to test if the length of string is less than or equal to
8673 // kMaxCachedArrayIndexLength.
8674 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8676 static const unsigned int kContainsCachedArrayIndexMask =
8677 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8678 << ArrayIndexLengthBits::kShift) |
8679 kIsNotArrayIndexMask;
8681 class SubStringRange {
8683 explicit SubStringRange(String* string, int first = 0, int length = -1)
8686 length_(length == -1 ? string->length() : length) {}
8688 inline iterator begin();
8689 inline iterator end();
8697 // Representation of the flat content of a String.
8698 // A non-flat string doesn't have flat content.
8699 // A flat string has content that's encoded as a sequence of either
8700 // one-byte chars or two-byte UC16.
8701 // Returned by String::GetFlatContent().
8704 // Returns true if the string is flat and this structure contains content.
8705 bool IsFlat() { return state_ != NON_FLAT; }
8706 // Returns true if the structure contains one-byte content.
8707 bool IsOneByte() { return state_ == ONE_BYTE; }
8708 // Returns true if the structure contains two-byte content.
8709 bool IsTwoByte() { return state_ == TWO_BYTE; }
8711 // Return the one byte content of the string. Only use if IsOneByte()
8713 Vector<const uint8_t> ToOneByteVector() {
8714 DCHECK_EQ(ONE_BYTE, state_);
8715 return Vector<const uint8_t>(onebyte_start, length_);
8717 // Return the two-byte content of the string. Only use if IsTwoByte()
8719 Vector<const uc16> ToUC16Vector() {
8720 DCHECK_EQ(TWO_BYTE, state_);
8721 return Vector<const uc16>(twobyte_start, length_);
8725 DCHECK(i < length_);
8726 DCHECK(state_ != NON_FLAT);
8727 if (state_ == ONE_BYTE) return onebyte_start[i];
8728 return twobyte_start[i];
8731 bool UsesSameString(const FlatContent& other) const {
8732 return onebyte_start == other.onebyte_start;
8736 enum State { NON_FLAT, ONE_BYTE, TWO_BYTE };
8738 // Constructors only used by String::GetFlatContent().
8739 explicit FlatContent(const uint8_t* start, int length)
8740 : onebyte_start(start), length_(length), state_(ONE_BYTE) {}
8741 explicit FlatContent(const uc16* start, int length)
8742 : twobyte_start(start), length_(length), state_(TWO_BYTE) { }
8743 FlatContent() : onebyte_start(NULL), length_(0), state_(NON_FLAT) { }
8746 const uint8_t* onebyte_start;
8747 const uc16* twobyte_start;
8752 friend class String;
8753 friend class IterableSubString;
8756 template <typename Char>
8757 INLINE(Vector<const Char> GetCharVector());
8759 // Get and set the length of the string.
8760 inline int length() const;
8761 inline void set_length(int value);
8763 // Get and set the length of the string using acquire loads and release
8765 inline int synchronized_length() const;
8766 inline void synchronized_set_length(int value);
8768 // Returns whether this string has only one-byte chars, i.e. all of them can
8769 // be one-byte encoded. This might be the case even if the string is
8770 // two-byte. Such strings may appear when the embedder prefers
8771 // two-byte external representations even for one-byte data.
8772 inline bool IsOneByteRepresentation() const;
8773 inline bool IsTwoByteRepresentation() const;
8775 // Cons and slices have an encoding flag that may not represent the actual
8776 // encoding of the underlying string. This is taken into account here.
8777 // Requires: this->IsFlat()
8778 inline bool IsOneByteRepresentationUnderneath();
8779 inline bool IsTwoByteRepresentationUnderneath();
8781 // NOTE: this should be considered only a hint. False negatives are
8783 inline bool HasOnlyOneByteChars();
8785 // Get and set individual two byte chars in the string.
8786 inline void Set(int index, uint16_t value);
8787 // Get individual two byte char in the string. Repeated calls
8788 // to this method are not efficient unless the string is flat.
8789 INLINE(uint16_t Get(int index));
8791 // Flattens the string. Checks first inline to see if it is
8792 // necessary. Does nothing if the string is not a cons string.
8793 // Flattening allocates a sequential string with the same data as
8794 // the given string and mutates the cons string to a degenerate
8795 // form, where the first component is the new sequential string and
8796 // the second component is the empty string. If allocation fails,
8797 // this function returns a failure. If flattening succeeds, this
8798 // function returns the sequential string that is now the first
8799 // component of the cons string.
8801 // Degenerate cons strings are handled specially by the garbage
8802 // collector (see IsShortcutCandidate).
8804 static inline Handle<String> Flatten(Handle<String> string,
8805 PretenureFlag pretenure = NOT_TENURED);
8807 // Tries to return the content of a flat string as a structure holding either
8808 // a flat vector of char or of uc16.
8809 // If the string isn't flat, and therefore doesn't have flat content, the
8810 // returned structure will report so, and can't provide a vector of either
8812 FlatContent GetFlatContent();
8814 // Returns the parent of a sliced string or first part of a flat cons string.
8815 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
8816 inline String* GetUnderlying();
8818 // String equality operations.
8819 inline bool Equals(String* other);
8820 inline static bool Equals(Handle<String> one, Handle<String> two);
8821 bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
8822 bool IsOneByteEqualTo(Vector<const uint8_t> str);
8823 bool IsTwoByteEqualTo(Vector<const uc16> str);
8825 // Return a UTF8 representation of the string. The string is null
8826 // terminated but may optionally contain nulls. Length is returned
8827 // in length_output if length_output is not a null pointer The string
8828 // should be nearly flat, otherwise the performance of this method may
8829 // be very slow (quadratic in the length). Setting robustness_flag to
8830 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8831 // handles unexpected data without causing assert failures and it does not
8832 // do any heap allocations. This is useful when printing stack traces.
8833 base::SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
8834 RobustnessFlag robustness_flag,
8835 int offset, int length,
8836 int* length_output = 0);
8837 base::SmartArrayPointer<char> ToCString(
8838 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
8839 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
8840 int* length_output = 0);
8842 // Return a 16 bit Unicode representation of the string.
8843 // The string should be nearly flat, otherwise the performance of
8844 // of this method may be very bad. Setting robustness_flag to
8845 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8846 // handles unexpected data without causing assert failures and it does not
8847 // do any heap allocations. This is useful when printing stack traces.
8848 base::SmartArrayPointer<uc16> ToWideCString(
8849 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
8851 bool ComputeArrayIndex(uint32_t* index);
8854 bool MakeExternal(v8::String::ExternalStringResource* resource);
8855 bool MakeExternal(v8::String::ExternalOneByteStringResource* resource);
8858 inline bool AsArrayIndex(uint32_t* index);
8860 DECLARE_CAST(String)
8862 void PrintOn(FILE* out);
8864 // For use during stack traces. Performs rudimentary sanity check.
8867 // Dispatched behavior.
8868 void StringShortPrint(StringStream* accumulator);
8869 void PrintUC16(std::ostream& os, int start = 0, int end = -1); // NOLINT
8870 #if defined(DEBUG) || defined(OBJECT_PRINT)
8871 char* ToAsciiArray();
8873 DECLARE_PRINTER(String)
8874 DECLARE_VERIFIER(String)
8876 inline bool IsFlat();
8878 // Layout description.
8879 static const int kLengthOffset = Name::kSize;
8880 static const int kSize = kLengthOffset + kPointerSize;
8882 // Maximum number of characters to consider when trying to convert a string
8883 // value into an array index.
8884 static const int kMaxArrayIndexSize = 10;
8885 STATIC_ASSERT(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
8888 static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
8889 static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
8890 static const int kMaxUtf16CodeUnit = 0xffff;
8891 static const uint32_t kMaxUtf16CodeUnitU = kMaxUtf16CodeUnit;
8893 // Value of hash field containing computed hash equal to zero.
8894 static const int kEmptyStringHash = kIsNotArrayIndexMask;
8896 // Maximal string length.
8897 static const int kMaxLength = (1 << 28) - 16;
8899 // Max length for computing hash. For strings longer than this limit the
8900 // string length is used as the hash value.
8901 static const int kMaxHashCalcLength = 16383;
8903 // Limit for truncation in short printing.
8904 static const int kMaxShortPrintLength = 1024;
8906 // Support for regular expressions.
8907 const uc16* GetTwoByteData(unsigned start);
8909 // Helper function for flattening strings.
8910 template <typename sinkchar>
8911 static void WriteToFlat(String* source,
8916 // The return value may point to the first aligned word containing the first
8917 // non-one-byte character, rather than directly to the non-one-byte character.
8918 // If the return value is >= the passed length, the entire string was
8920 static inline int NonAsciiStart(const char* chars, int length) {
8921 const char* start = chars;
8922 const char* limit = chars + length;
8924 if (length >= kIntptrSize) {
8925 // Check unaligned bytes.
8926 while (!IsAligned(reinterpret_cast<intptr_t>(chars), sizeof(uintptr_t))) {
8927 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8928 return static_cast<int>(chars - start);
8932 // Check aligned words.
8933 DCHECK(unibrow::Utf8::kMaxOneByteChar == 0x7F);
8934 const uintptr_t non_one_byte_mask = kUintptrAllBitsSet / 0xFF * 0x80;
8935 while (chars + sizeof(uintptr_t) <= limit) {
8936 if (*reinterpret_cast<const uintptr_t*>(chars) & non_one_byte_mask) {
8937 return static_cast<int>(chars - start);
8939 chars += sizeof(uintptr_t);
8942 // Check remaining unaligned bytes.
8943 while (chars < limit) {
8944 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8945 return static_cast<int>(chars - start);
8950 return static_cast<int>(chars - start);
8953 static inline bool IsAscii(const char* chars, int length) {
8954 return NonAsciiStart(chars, length) >= length;
8957 static inline bool IsAscii(const uint8_t* chars, int length) {
8959 NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
8962 static inline int NonOneByteStart(const uc16* chars, int length) {
8963 const uc16* limit = chars + length;
8964 const uc16* start = chars;
8965 while (chars < limit) {
8966 if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
8969 return static_cast<int>(chars - start);
8972 static inline bool IsOneByte(const uc16* chars, int length) {
8973 return NonOneByteStart(chars, length) >= length;
8976 template<class Visitor>
8977 static inline ConsString* VisitFlat(Visitor* visitor,
8981 static Handle<FixedArray> CalculateLineEnds(Handle<String> string,
8982 bool include_ending_line);
8984 // Use the hash field to forward to the canonical internalized string
8985 // when deserializing an internalized string.
8986 inline void SetForwardedInternalizedString(String* string);
8987 inline String* GetForwardedInternalizedString();
8991 friend class StringTableInsertionKey;
8993 static Handle<String> SlowFlatten(Handle<ConsString> cons,
8994 PretenureFlag tenure);
8996 // Slow case of String::Equals. This implementation works on any strings
8997 // but it is most efficient on strings that are almost flat.
8998 bool SlowEquals(String* other);
9000 static bool SlowEquals(Handle<String> one, Handle<String> two);
9002 // Slow case of AsArrayIndex.
9003 bool SlowAsArrayIndex(uint32_t* index);
9005 // Compute and set the hash code.
9006 uint32_t ComputeAndSetHash();
9008 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
9012 // The SeqString abstract class captures sequential string values.
9013 class SeqString: public String {
9015 DECLARE_CAST(SeqString)
9017 // Layout description.
9018 static const int kHeaderSize = String::kSize;
9020 // Truncate the string in-place if possible and return the result.
9021 // In case of new_length == 0, the empty string is returned without
9022 // truncating the original string.
9023 MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
9026 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
9030 // The OneByteString class captures sequential one-byte string objects.
9031 // Each character in the OneByteString is an one-byte character.
9032 class SeqOneByteString: public SeqString {
9034 static const bool kHasOneByteEncoding = true;
9036 // Dispatched behavior.
9037 inline uint16_t SeqOneByteStringGet(int index);
9038 inline void SeqOneByteStringSet(int index, uint16_t value);
9040 // Get the address of the characters in this string.
9041 inline Address GetCharsAddress();
9043 inline uint8_t* GetChars();
9045 DECLARE_CAST(SeqOneByteString)
9047 // Garbage collection support. This method is called by the
9048 // garbage collector to compute the actual size of an OneByteString
9050 inline int SeqOneByteStringSize(InstanceType instance_type);
9052 // Computes the size for an OneByteString instance of a given length.
9053 static int SizeFor(int length) {
9054 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
9057 // Maximal memory usage for a single sequential one-byte string.
9058 static const int kMaxSize = 512 * MB - 1;
9059 STATIC_ASSERT((kMaxSize - kHeaderSize) >= String::kMaxLength);
9062 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
9066 // The TwoByteString class captures sequential unicode string objects.
9067 // Each character in the TwoByteString is a two-byte uint16_t.
9068 class SeqTwoByteString: public SeqString {
9070 static const bool kHasOneByteEncoding = false;
9072 // Dispatched behavior.
9073 inline uint16_t SeqTwoByteStringGet(int index);
9074 inline void SeqTwoByteStringSet(int index, uint16_t value);
9076 // Get the address of the characters in this string.
9077 inline Address GetCharsAddress();
9079 inline uc16* GetChars();
9082 const uint16_t* SeqTwoByteStringGetData(unsigned start);
9084 DECLARE_CAST(SeqTwoByteString)
9086 // Garbage collection support. This method is called by the
9087 // garbage collector to compute the actual size of a TwoByteString
9089 inline int SeqTwoByteStringSize(InstanceType instance_type);
9091 // Computes the size for a TwoByteString instance of a given length.
9092 static int SizeFor(int length) {
9093 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
9096 // Maximal memory usage for a single sequential two-byte string.
9097 static const int kMaxSize = 512 * MB - 1;
9098 STATIC_ASSERT(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
9099 String::kMaxLength);
9102 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
9106 // The ConsString class describes string values built by using the
9107 // addition operator on strings. A ConsString is a pair where the
9108 // first and second components are pointers to other string values.
9109 // One or both components of a ConsString can be pointers to other
9110 // ConsStrings, creating a binary tree of ConsStrings where the leaves
9111 // are non-ConsString string values. The string value represented by
9112 // a ConsString can be obtained by concatenating the leaf string
9113 // values in a left-to-right depth-first traversal of the tree.
9114 class ConsString: public String {
9116 // First string of the cons cell.
9117 inline String* first();
9118 // Doesn't check that the result is a string, even in debug mode. This is
9119 // useful during GC where the mark bits confuse the checks.
9120 inline Object* unchecked_first();
9121 inline void set_first(String* first,
9122 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9124 // Second string of the cons cell.
9125 inline String* second();
9126 // Doesn't check that the result is a string, even in debug mode. This is
9127 // useful during GC where the mark bits confuse the checks.
9128 inline Object* unchecked_second();
9129 inline void set_second(String* second,
9130 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9132 // Dispatched behavior.
9133 uint16_t ConsStringGet(int index);
9135 DECLARE_CAST(ConsString)
9137 // Layout description.
9138 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
9139 static const int kSecondOffset = kFirstOffset + kPointerSize;
9140 static const int kSize = kSecondOffset + kPointerSize;
9142 // Minimum length for a cons string.
9143 static const int kMinLength = 13;
9145 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
9148 DECLARE_VERIFIER(ConsString)
9151 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
9155 // The Sliced String class describes strings that are substrings of another
9156 // sequential string. The motivation is to save time and memory when creating
9157 // a substring. A Sliced String is described as a pointer to the parent,
9158 // the offset from the start of the parent string and the length. Using
9159 // a Sliced String therefore requires unpacking of the parent string and
9160 // adding the offset to the start address. A substring of a Sliced String
9161 // are not nested since the double indirection is simplified when creating
9162 // such a substring.
9163 // Currently missing features are:
9164 // - handling externalized parent strings
9165 // - external strings as parent
9166 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
9167 class SlicedString: public String {
9169 inline String* parent();
9170 inline void set_parent(String* parent,
9171 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9172 inline int offset() const;
9173 inline void set_offset(int offset);
9175 // Dispatched behavior.
9176 uint16_t SlicedStringGet(int index);
9178 DECLARE_CAST(SlicedString)
9180 // Layout description.
9181 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
9182 static const int kOffsetOffset = kParentOffset + kPointerSize;
9183 static const int kSize = kOffsetOffset + kPointerSize;
9185 // Minimum length for a sliced string.
9186 static const int kMinLength = 13;
9188 typedef FixedBodyDescriptor<kParentOffset,
9189 kOffsetOffset + kPointerSize, kSize>
9192 DECLARE_VERIFIER(SlicedString)
9195 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
9199 // The ExternalString class describes string values that are backed by
9200 // a string resource that lies outside the V8 heap. ExternalStrings
9201 // consist of the length field common to all strings, a pointer to the
9202 // external resource. It is important to ensure (externally) that the
9203 // resource is not deallocated while the ExternalString is live in the
9206 // The API expects that all ExternalStrings are created through the
9207 // API. Therefore, ExternalStrings should not be used internally.
9208 class ExternalString: public String {
9210 DECLARE_CAST(ExternalString)
9212 // Layout description.
9213 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
9214 static const int kShortSize = kResourceOffset + kPointerSize;
9215 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
9216 static const int kSize = kResourceDataOffset + kPointerSize;
9218 static const int kMaxShortLength =
9219 (kShortSize - SeqString::kHeaderSize) / kCharSize;
9221 // Return whether external string is short (data pointer is not cached).
9222 inline bool is_short();
9224 STATIC_ASSERT(kResourceOffset == Internals::kStringResourceOffset);
9227 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
9231 // The ExternalOneByteString class is an external string backed by an
9233 class ExternalOneByteString : public ExternalString {
9235 static const bool kHasOneByteEncoding = true;
9237 typedef v8::String::ExternalOneByteStringResource Resource;
9239 // The underlying resource.
9240 inline const Resource* resource();
9241 inline void set_resource(const Resource* buffer);
9243 // Update the pointer cache to the external character array.
9244 // The cached pointer is always valid, as the external character array does =
9245 // not move during lifetime. Deserialization is the only exception, after
9246 // which the pointer cache has to be refreshed.
9247 inline void update_data_cache();
9249 inline const uint8_t* GetChars();
9251 // Dispatched behavior.
9252 inline uint16_t ExternalOneByteStringGet(int index);
9254 DECLARE_CAST(ExternalOneByteString)
9256 // Garbage collection support.
9257 inline void ExternalOneByteStringIterateBody(ObjectVisitor* v);
9259 template <typename StaticVisitor>
9260 inline void ExternalOneByteStringIterateBody();
9263 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalOneByteString);
9267 // The ExternalTwoByteString class is an external string backed by a UTF-16
9269 class ExternalTwoByteString: public ExternalString {
9271 static const bool kHasOneByteEncoding = false;
9273 typedef v8::String::ExternalStringResource Resource;
9275 // The underlying string resource.
9276 inline const Resource* resource();
9277 inline void set_resource(const Resource* buffer);
9279 // Update the pointer cache to the external character array.
9280 // The cached pointer is always valid, as the external character array does =
9281 // not move during lifetime. Deserialization is the only exception, after
9282 // which the pointer cache has to be refreshed.
9283 inline void update_data_cache();
9285 inline const uint16_t* GetChars();
9287 // Dispatched behavior.
9288 inline uint16_t ExternalTwoByteStringGet(int index);
9291 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
9293 DECLARE_CAST(ExternalTwoByteString)
9295 // Garbage collection support.
9296 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
9298 template<typename StaticVisitor>
9299 inline void ExternalTwoByteStringIterateBody();
9302 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
9306 // Utility superclass for stack-allocated objects that must be updated
9307 // on gc. It provides two ways for the gc to update instances, either
9308 // iterating or updating after gc.
9309 class Relocatable BASE_EMBEDDED {
9311 explicit inline Relocatable(Isolate* isolate);
9312 inline virtual ~Relocatable();
9313 virtual void IterateInstance(ObjectVisitor* v) { }
9314 virtual void PostGarbageCollection() { }
9316 static void PostGarbageCollectionProcessing(Isolate* isolate);
9317 static int ArchiveSpacePerThread();
9318 static char* ArchiveState(Isolate* isolate, char* to);
9319 static char* RestoreState(Isolate* isolate, char* from);
9320 static void Iterate(Isolate* isolate, ObjectVisitor* v);
9321 static void Iterate(ObjectVisitor* v, Relocatable* top);
9322 static char* Iterate(ObjectVisitor* v, char* t);
9330 // A flat string reader provides random access to the contents of a
9331 // string independent of the character width of the string. The handle
9332 // must be valid as long as the reader is being used.
9333 class FlatStringReader : public Relocatable {
9335 FlatStringReader(Isolate* isolate, Handle<String> str);
9336 FlatStringReader(Isolate* isolate, Vector<const char> input);
9337 void PostGarbageCollection();
9338 inline uc32 Get(int index);
9339 template <typename Char>
9340 inline Char Get(int index);
9341 int length() { return length_; }
9350 // This maintains an off-stack representation of the stack frames required
9351 // to traverse a ConsString, allowing an entirely iterative and restartable
9352 // traversal of the entire string
9353 class ConsStringIterator {
9355 inline ConsStringIterator() {}
9356 inline explicit ConsStringIterator(ConsString* cons_string, int offset = 0) {
9357 Reset(cons_string, offset);
9359 inline void Reset(ConsString* cons_string, int offset = 0) {
9361 // Next will always return NULL.
9362 if (cons_string == NULL) return;
9363 Initialize(cons_string, offset);
9365 // Returns NULL when complete.
9366 inline String* Next(int* offset_out) {
9368 if (depth_ == 0) return NULL;
9369 return Continue(offset_out);
9373 static const int kStackSize = 32;
9374 // Use a mask instead of doing modulo operations for stack wrapping.
9375 static const int kDepthMask = kStackSize-1;
9376 STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
9377 static inline int OffsetForDepth(int depth);
9379 inline void PushLeft(ConsString* string);
9380 inline void PushRight(ConsString* string);
9381 inline void AdjustMaximumDepth();
9383 inline bool StackBlown() { return maximum_depth_ - depth_ == kStackSize; }
9384 void Initialize(ConsString* cons_string, int offset);
9385 String* Continue(int* offset_out);
9386 String* NextLeaf(bool* blew_stack);
9387 String* Search(int* offset_out);
9389 // Stack must always contain only frames for which right traversal
9390 // has not yet been performed.
9391 ConsString* frames_[kStackSize];
9396 DISALLOW_COPY_AND_ASSIGN(ConsStringIterator);
9400 class StringCharacterStream {
9402 inline StringCharacterStream(String* string,
9404 inline uint16_t GetNext();
9405 inline bool HasMore();
9406 inline void Reset(String* string, int offset = 0);
9407 inline void VisitOneByteString(const uint8_t* chars, int length);
9408 inline void VisitTwoByteString(const uint16_t* chars, int length);
9411 ConsStringIterator iter_;
9414 const uint8_t* buffer8_;
9415 const uint16_t* buffer16_;
9417 const uint8_t* end_;
9418 DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
9422 template <typename T>
9423 class VectorIterator {
9425 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
9426 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
9427 T GetNext() { return data_[index_++]; }
9428 bool has_more() { return index_ < data_.length(); }
9430 Vector<const T> data_;
9435 // The Oddball describes objects null, undefined, true, and false.
9436 class Oddball: public HeapObject {
9438 // [to_string]: Cached to_string computed at startup.
9439 DECL_ACCESSORS(to_string, String)
9441 // [to_number]: Cached to_number computed at startup.
9442 DECL_ACCESSORS(to_number, Object)
9444 inline byte kind() const;
9445 inline void set_kind(byte kind);
9447 DECLARE_CAST(Oddball)
9449 // Dispatched behavior.
9450 DECLARE_VERIFIER(Oddball)
9452 // Initialize the fields.
9453 static void Initialize(Isolate* isolate,
9454 Handle<Oddball> oddball,
9455 const char* to_string,
9456 Handle<Object> to_number,
9459 // Layout description.
9460 static const int kToStringOffset = HeapObject::kHeaderSize;
9461 static const int kToNumberOffset = kToStringOffset + kPointerSize;
9462 static const int kKindOffset = kToNumberOffset + kPointerSize;
9463 static const int kSize = kKindOffset + kPointerSize;
9465 static const byte kFalse = 0;
9466 static const byte kTrue = 1;
9467 static const byte kNotBooleanMask = ~1;
9468 static const byte kTheHole = 2;
9469 static const byte kNull = 3;
9470 static const byte kArgumentMarker = 4;
9471 static const byte kUndefined = 5;
9472 static const byte kUninitialized = 6;
9473 static const byte kOther = 7;
9474 static const byte kException = 8;
9476 typedef FixedBodyDescriptor<kToStringOffset,
9477 kToNumberOffset + kPointerSize,
9478 kSize> BodyDescriptor;
9480 STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset);
9481 STATIC_ASSERT(kNull == Internals::kNullOddballKind);
9482 STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind);
9485 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
9489 class Cell: public HeapObject {
9491 // [value]: value of the cell.
9492 DECL_ACCESSORS(value, Object)
9496 static inline Cell* FromValueAddress(Address value) {
9497 Object* result = FromAddress(value - kValueOffset);
9498 return static_cast<Cell*>(result);
9501 inline Address ValueAddress() {
9502 return address() + kValueOffset;
9505 // Dispatched behavior.
9506 DECLARE_PRINTER(Cell)
9507 DECLARE_VERIFIER(Cell)
9509 // Layout description.
9510 static const int kValueOffset = HeapObject::kHeaderSize;
9511 static const int kSize = kValueOffset + kPointerSize;
9513 typedef FixedBodyDescriptor<kValueOffset,
9514 kValueOffset + kPointerSize,
9515 kSize> BodyDescriptor;
9518 DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9522 class PropertyCell : public HeapObject {
9524 // [property_details]: details of the global property.
9525 DECL_ACCESSORS(property_details_raw, Object)
9526 // [value]: value of the global property.
9527 DECL_ACCESSORS(value, Object)
9528 // [dependent_code]: dependent code that depends on the type of the global
9530 DECL_ACCESSORS(dependent_code, DependentCode)
9532 PropertyDetails property_details() {
9533 return PropertyDetails(Smi::cast(property_details_raw()));
9536 void set_property_details(PropertyDetails details) {
9537 set_property_details_raw(details.AsSmi());
9540 PropertyCellConstantType GetConstantType();
9542 // Computes the new type of the cell's contents for the given value, but
9543 // without actually modifying the details.
9544 static PropertyCellType UpdatedType(Handle<PropertyCell> cell,
9545 Handle<Object> value,
9546 PropertyDetails details);
9547 static void UpdateCell(Handle<GlobalDictionary> dictionary, int entry,
9548 Handle<Object> value, PropertyDetails details);
9550 static Handle<PropertyCell> InvalidateEntry(
9551 Handle<GlobalDictionary> dictionary, int entry);
9553 static void SetValueWithInvalidation(Handle<PropertyCell> cell,
9554 Handle<Object> new_value);
9556 DECLARE_CAST(PropertyCell)
9558 // Dispatched behavior.
9559 DECLARE_PRINTER(PropertyCell)
9560 DECLARE_VERIFIER(PropertyCell)
9562 // Layout description.
9563 static const int kDetailsOffset = HeapObject::kHeaderSize;
9564 static const int kValueOffset = kDetailsOffset + kPointerSize;
9565 static const int kDependentCodeOffset = kValueOffset + kPointerSize;
9566 static const int kSize = kDependentCodeOffset + kPointerSize;
9568 static const int kPointerFieldsBeginOffset = kValueOffset;
9569 static const int kPointerFieldsEndOffset = kSize;
9571 typedef FixedBodyDescriptor<kValueOffset,
9573 kSize> BodyDescriptor;
9576 DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9580 class WeakCell : public HeapObject {
9582 inline Object* value() const;
9584 // This should not be called by anyone except GC.
9585 inline void clear();
9587 // This should not be called by anyone except allocator.
9588 inline void initialize(HeapObject* value);
9590 inline bool cleared() const;
9592 DECL_ACCESSORS(next, Object)
9594 inline void clear_next(Heap* heap);
9596 inline bool next_cleared();
9598 DECLARE_CAST(WeakCell)
9600 DECLARE_PRINTER(WeakCell)
9601 DECLARE_VERIFIER(WeakCell)
9603 // Layout description.
9604 static const int kValueOffset = HeapObject::kHeaderSize;
9605 static const int kNextOffset = kValueOffset + kPointerSize;
9606 static const int kSize = kNextOffset + kPointerSize;
9608 typedef FixedBodyDescriptor<kValueOffset, kSize, kSize> BodyDescriptor;
9611 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakCell);
9615 // The JSProxy describes EcmaScript Harmony proxies
9616 class JSProxy: public JSReceiver {
9618 // [handler]: The handler property.
9619 DECL_ACCESSORS(handler, Object)
9621 // [hash]: The hash code property (undefined if not initialized yet).
9622 DECL_ACCESSORS(hash, Object)
9624 DECLARE_CAST(JSProxy)
9626 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithHandler(
9627 Handle<JSProxy> proxy,
9628 Handle<Object> receiver,
9631 // If the handler defines an accessor property with a setter, invoke it.
9632 // If it defines an accessor property without a setter, or a data property
9633 // that is read-only, throw. In all these cases set '*done' to true,
9634 // otherwise set it to false.
9636 static MaybeHandle<Object> SetPropertyViaPrototypesWithHandler(
9637 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9638 Handle<Object> value, LanguageMode language_mode, bool* done);
9640 MUST_USE_RESULT static Maybe<PropertyAttributes>
9641 GetPropertyAttributesWithHandler(Handle<JSProxy> proxy,
9642 Handle<Object> receiver,
9644 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithHandler(
9645 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9646 Handle<Object> value, LanguageMode language_mode);
9648 // Turn the proxy into an (empty) JSObject.
9649 static void Fix(Handle<JSProxy> proxy);
9651 // Initializes the body after the handler slot.
9652 inline void InitializeBody(int object_size, Object* value);
9654 // Invoke a trap by name. If the trap does not exist on this's handler,
9655 // but derived_trap is non-NULL, invoke that instead. May cause GC.
9656 MUST_USE_RESULT static MaybeHandle<Object> CallTrap(
9657 Handle<JSProxy> proxy,
9659 Handle<Object> derived_trap,
9661 Handle<Object> args[]);
9663 // Dispatched behavior.
9664 DECLARE_PRINTER(JSProxy)
9665 DECLARE_VERIFIER(JSProxy)
9667 // Layout description. We add padding so that a proxy has the same
9668 // size as a virgin JSObject. This is essential for becoming a JSObject
9670 static const int kHandlerOffset = HeapObject::kHeaderSize;
9671 static const int kHashOffset = kHandlerOffset + kPointerSize;
9672 static const int kPaddingOffset = kHashOffset + kPointerSize;
9673 static const int kSize = JSObject::kHeaderSize;
9674 static const int kHeaderSize = kPaddingOffset;
9675 static const int kPaddingSize = kSize - kPaddingOffset;
9677 STATIC_ASSERT(kPaddingSize >= 0);
9679 typedef FixedBodyDescriptor<kHandlerOffset,
9681 kSize> BodyDescriptor;
9684 friend class JSReceiver;
9686 MUST_USE_RESULT static Maybe<bool> HasPropertyWithHandler(
9687 Handle<JSProxy> proxy, Handle<Name> name);
9689 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithHandler(
9690 Handle<JSProxy> proxy, Handle<Name> name, LanguageMode language_mode);
9692 MUST_USE_RESULT Object* GetIdentityHash();
9694 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
9696 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
9700 class JSFunctionProxy: public JSProxy {
9702 // [call_trap]: The call trap.
9703 DECL_ACCESSORS(call_trap, Object)
9705 // [construct_trap]: The construct trap.
9706 DECL_ACCESSORS(construct_trap, Object)
9708 DECLARE_CAST(JSFunctionProxy)
9710 // Dispatched behavior.
9711 DECLARE_PRINTER(JSFunctionProxy)
9712 DECLARE_VERIFIER(JSFunctionProxy)
9714 // Layout description.
9715 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
9716 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
9717 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
9718 static const int kSize = JSFunction::kSize;
9719 static const int kPaddingSize = kSize - kPaddingOffset;
9721 STATIC_ASSERT(kPaddingSize >= 0);
9723 typedef FixedBodyDescriptor<kHandlerOffset,
9724 kConstructTrapOffset + kPointerSize,
9725 kSize> BodyDescriptor;
9728 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
9732 class JSCollection : public JSObject {
9734 // [table]: the backing hash table
9735 DECL_ACCESSORS(table, Object)
9737 static const int kTableOffset = JSObject::kHeaderSize;
9738 static const int kSize = kTableOffset + kPointerSize;
9741 DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollection);
9745 // The JSSet describes EcmaScript Harmony sets
9746 class JSSet : public JSCollection {
9750 // Dispatched behavior.
9751 DECLARE_PRINTER(JSSet)
9752 DECLARE_VERIFIER(JSSet)
9755 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
9759 // The JSMap describes EcmaScript Harmony maps
9760 class JSMap : public JSCollection {
9764 // Dispatched behavior.
9765 DECLARE_PRINTER(JSMap)
9766 DECLARE_VERIFIER(JSMap)
9769 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
9773 // OrderedHashTableIterator is an iterator that iterates over the keys and
9774 // values of an OrderedHashTable.
9776 // The iterator has a reference to the underlying OrderedHashTable data,
9777 // [table], as well as the current [index] the iterator is at.
9779 // When the OrderedHashTable is rehashed it adds a reference from the old table
9780 // to the new table as well as storing enough data about the changes so that the
9781 // iterator [index] can be adjusted accordingly.
9783 // When the [Next] result from the iterator is requested, the iterator checks if
9784 // there is a newer table that it needs to transition to.
9785 template<class Derived, class TableType>
9786 class OrderedHashTableIterator: public JSObject {
9788 // [table]: the backing hash table mapping keys to values.
9789 DECL_ACCESSORS(table, Object)
9791 // [index]: The index into the data table.
9792 DECL_ACCESSORS(index, Object)
9794 // [kind]: The kind of iteration this is. One of the [Kind] enum values.
9795 DECL_ACCESSORS(kind, Object)
9798 void OrderedHashTableIteratorPrint(std::ostream& os); // NOLINT
9801 static const int kTableOffset = JSObject::kHeaderSize;
9802 static const int kIndexOffset = kTableOffset + kPointerSize;
9803 static const int kKindOffset = kIndexOffset + kPointerSize;
9804 static const int kSize = kKindOffset + kPointerSize;
9812 // Whether the iterator has more elements. This needs to be called before
9813 // calling |CurrentKey| and/or |CurrentValue|.
9816 // Move the index forward one.
9818 set_index(Smi::FromInt(Smi::cast(index())->value() + 1));
9821 // Populates the array with the next key and value and then moves the iterator
9823 // This returns the |kind| or 0 if the iterator is already at the end.
9824 Smi* Next(JSArray* value_array);
9826 // Returns the current key of the iterator. This should only be called when
9827 // |HasMore| returns true.
9828 inline Object* CurrentKey();
9831 // Transitions the iterator to the non obsolete backing store. This is a NOP
9832 // if the [table] is not obsolete.
9835 DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
9839 class JSSetIterator: public OrderedHashTableIterator<JSSetIterator,
9842 // Dispatched behavior.
9843 DECLARE_PRINTER(JSSetIterator)
9844 DECLARE_VERIFIER(JSSetIterator)
9846 DECLARE_CAST(JSSetIterator)
9848 // Called by |Next| to populate the array. This allows the subclasses to
9849 // populate the array differently.
9850 inline void PopulateValueArray(FixedArray* array);
9853 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSetIterator);
9857 class JSMapIterator: public OrderedHashTableIterator<JSMapIterator,
9860 // Dispatched behavior.
9861 DECLARE_PRINTER(JSMapIterator)
9862 DECLARE_VERIFIER(JSMapIterator)
9864 DECLARE_CAST(JSMapIterator)
9866 // Called by |Next| to populate the array. This allows the subclasses to
9867 // populate the array differently.
9868 inline void PopulateValueArray(FixedArray* array);
9871 // Returns the current value of the iterator. This should only be called when
9872 // |HasMore| returns true.
9873 inline Object* CurrentValue();
9875 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMapIterator);
9879 // Base class for both JSWeakMap and JSWeakSet
9880 class JSWeakCollection: public JSObject {
9882 // [table]: the backing hash table mapping keys to values.
9883 DECL_ACCESSORS(table, Object)
9885 // [next]: linked list of encountered weak maps during GC.
9886 DECL_ACCESSORS(next, Object)
9888 static const int kTableOffset = JSObject::kHeaderSize;
9889 static const int kNextOffset = kTableOffset + kPointerSize;
9890 static const int kSize = kNextOffset + kPointerSize;
9893 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
9897 // The JSWeakMap describes EcmaScript Harmony weak maps
9898 class JSWeakMap: public JSWeakCollection {
9900 DECLARE_CAST(JSWeakMap)
9902 // Dispatched behavior.
9903 DECLARE_PRINTER(JSWeakMap)
9904 DECLARE_VERIFIER(JSWeakMap)
9907 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
9911 // The JSWeakSet describes EcmaScript Harmony weak sets
9912 class JSWeakSet: public JSWeakCollection {
9914 DECLARE_CAST(JSWeakSet)
9916 // Dispatched behavior.
9917 DECLARE_PRINTER(JSWeakSet)
9918 DECLARE_VERIFIER(JSWeakSet)
9921 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
9925 // Whether a JSArrayBuffer is a SharedArrayBuffer or not.
9926 enum class SharedFlag { kNotShared, kShared };
9929 class JSArrayBuffer: public JSObject {
9931 // [backing_store]: backing memory for this array
9932 DECL_ACCESSORS(backing_store, void)
9934 // [byte_length]: length in bytes
9935 DECL_ACCESSORS(byte_length, Object)
9937 inline uint32_t bit_field() const;
9938 inline void set_bit_field(uint32_t bits);
9940 inline bool is_external();
9941 inline void set_is_external(bool value);
9943 inline bool is_neuterable();
9944 inline void set_is_neuterable(bool value);
9946 inline bool was_neutered();
9947 inline void set_was_neutered(bool value);
9949 inline bool is_shared();
9950 inline void set_is_shared(bool value);
9952 DECLARE_CAST(JSArrayBuffer)
9956 // Dispatched behavior.
9957 DECLARE_PRINTER(JSArrayBuffer)
9958 DECLARE_VERIFIER(JSArrayBuffer)
9960 static const int kBackingStoreOffset = JSObject::kHeaderSize;
9961 static const int kByteLengthOffset = kBackingStoreOffset + kPointerSize;
9962 static const int kBitFieldSlot = kByteLengthOffset + kPointerSize;
9963 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
9964 static const int kBitFieldOffset = kBitFieldSlot;
9966 static const int kBitFieldOffset = kBitFieldSlot + kIntSize;
9968 static const int kSize = kBitFieldSlot + kPointerSize;
9970 static const int kSizeWithInternalFields =
9971 kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
9973 class IsExternal : public BitField<bool, 1, 1> {};
9974 class IsNeuterable : public BitField<bool, 2, 1> {};
9975 class WasNeutered : public BitField<bool, 3, 1> {};
9976 class IsShared : public BitField<bool, 4, 1> {};
9979 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
9983 class JSArrayBufferView: public JSObject {
9985 // [buffer]: ArrayBuffer that this typed array views.
9986 DECL_ACCESSORS(buffer, Object)
9988 // [byte_offset]: offset of typed array in bytes.
9989 DECL_ACCESSORS(byte_offset, Object)
9991 // [byte_length]: length of typed array in bytes.
9992 DECL_ACCESSORS(byte_length, Object)
9994 DECLARE_CAST(JSArrayBufferView)
9996 DECLARE_VERIFIER(JSArrayBufferView)
9998 inline bool WasNeutered() const;
10000 static const int kBufferOffset = JSObject::kHeaderSize;
10001 static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
10002 static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
10003 static const int kViewSize = kByteLengthOffset + kPointerSize;
10007 DECL_ACCESSORS(raw_byte_offset, Object)
10008 DECL_ACCESSORS(raw_byte_length, Object)
10011 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
10015 class JSTypedArray: public JSArrayBufferView {
10017 // [length]: length of typed array in elements.
10018 DECL_ACCESSORS(length, Object)
10019 inline uint32_t length_value() const;
10021 DECLARE_CAST(JSTypedArray)
10023 ExternalArrayType type();
10024 size_t element_size();
10026 Handle<JSArrayBuffer> GetBuffer();
10028 // Dispatched behavior.
10029 DECLARE_PRINTER(JSTypedArray)
10030 DECLARE_VERIFIER(JSTypedArray)
10032 static const int kLengthOffset = kViewSize + kPointerSize;
10033 static const int kSize = kLengthOffset + kPointerSize;
10035 static const int kSizeWithInternalFields =
10036 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
10039 static Handle<JSArrayBuffer> MaterializeArrayBuffer(
10040 Handle<JSTypedArray> typed_array);
10042 DECL_ACCESSORS(raw_length, Object)
10045 DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
10049 class JSDataView: public JSArrayBufferView {
10051 DECLARE_CAST(JSDataView)
10053 // Dispatched behavior.
10054 DECLARE_PRINTER(JSDataView)
10055 DECLARE_VERIFIER(JSDataView)
10057 static const int kSize = kViewSize;
10059 static const int kSizeWithInternalFields =
10060 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
10063 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
10067 // Foreign describes objects pointing from JavaScript to C structures.
10068 class Foreign: public HeapObject {
10070 // [address]: field containing the address.
10071 inline Address foreign_address();
10072 inline void set_foreign_address(Address value);
10074 DECLARE_CAST(Foreign)
10076 // Dispatched behavior.
10077 inline void ForeignIterateBody(ObjectVisitor* v);
10079 template<typename StaticVisitor>
10080 inline void ForeignIterateBody();
10082 // Dispatched behavior.
10083 DECLARE_PRINTER(Foreign)
10084 DECLARE_VERIFIER(Foreign)
10086 // Layout description.
10088 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
10089 static const int kSize = kForeignAddressOffset + kPointerSize;
10091 STATIC_ASSERT(kForeignAddressOffset == Internals::kForeignAddressOffset);
10094 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
10098 // The JSArray describes JavaScript Arrays
10099 // Such an array can be in one of two modes:
10100 // - fast, backing storage is a FixedArray and length <= elements.length();
10101 // Please note: push and pop can be used to grow and shrink the array.
10102 // - slow, backing storage is a HashTable with numbers as keys.
10103 class JSArray: public JSObject {
10105 // [length]: The length property.
10106 DECL_ACCESSORS(length, Object)
10108 // Overload the length setter to skip write barrier when the length
10109 // is set to a smi. This matches the set function on FixedArray.
10110 inline void set_length(Smi* length);
10112 static bool HasReadOnlyLength(Handle<JSArray> array);
10113 static bool WouldChangeReadOnlyLength(Handle<JSArray> array, uint32_t index);
10114 static MaybeHandle<Object> ReadOnlyLengthError(Handle<JSArray> array);
10116 // Initialize the array with the given capacity. The function may
10117 // fail due to out-of-memory situations, but only if the requested
10118 // capacity is non-zero.
10119 static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
10121 // If the JSArray has fast elements, and new_length would result in
10122 // normalization, returns true.
10123 bool SetLengthWouldNormalize(uint32_t new_length);
10124 static inline bool SetLengthWouldNormalize(Heap* heap, uint32_t new_length);
10126 // Initializes the array to a certain length.
10127 inline bool AllowsSetLength();
10129 static void SetLength(Handle<JSArray> array, uint32_t length);
10130 // Same as above but will also queue splice records if |array| is observed.
10131 static MaybeHandle<Object> ObservableSetLength(Handle<JSArray> array,
10134 // Set the content of the array to the content of storage.
10135 static inline void SetContent(Handle<JSArray> array,
10136 Handle<FixedArrayBase> storage);
10138 DECLARE_CAST(JSArray)
10140 // Dispatched behavior.
10141 DECLARE_PRINTER(JSArray)
10142 DECLARE_VERIFIER(JSArray)
10144 // Number of element slots to pre-allocate for an empty array.
10145 static const int kPreallocatedArrayElements = 4;
10147 // Layout description.
10148 static const int kLengthOffset = JSObject::kHeaderSize;
10149 static const int kSize = kLengthOffset + kPointerSize;
10152 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
10156 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
10157 Handle<Map> initial_map);
10160 // JSRegExpResult is just a JSArray with a specific initial map.
10161 // This initial map adds in-object properties for "index" and "input"
10162 // properties, as assigned by RegExp.prototype.exec, which allows
10163 // faster creation of RegExp exec results.
10164 // This class just holds constants used when creating the result.
10165 // After creation the result must be treated as a JSArray in all regards.
10166 class JSRegExpResult: public JSArray {
10168 // Offsets of object fields.
10169 static const int kIndexOffset = JSArray::kSize;
10170 static const int kInputOffset = kIndexOffset + kPointerSize;
10171 static const int kSize = kInputOffset + kPointerSize;
10172 // Indices of in-object properties.
10173 static const int kIndexIndex = 0;
10174 static const int kInputIndex = 1;
10176 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
10180 class AccessorInfo: public Struct {
10182 DECL_ACCESSORS(name, Object)
10183 DECL_ACCESSORS(flag, Smi)
10184 DECL_ACCESSORS(expected_receiver_type, Object)
10186 inline bool all_can_read();
10187 inline void set_all_can_read(bool value);
10189 inline bool all_can_write();
10190 inline void set_all_can_write(bool value);
10192 inline bool is_special_data_property();
10193 inline void set_is_special_data_property(bool value);
10195 inline PropertyAttributes property_attributes();
10196 inline void set_property_attributes(PropertyAttributes attributes);
10198 // Checks whether the given receiver is compatible with this accessor.
10199 static bool IsCompatibleReceiverMap(Isolate* isolate,
10200 Handle<AccessorInfo> info,
10202 inline bool IsCompatibleReceiver(Object* receiver);
10204 DECLARE_CAST(AccessorInfo)
10206 // Dispatched behavior.
10207 DECLARE_VERIFIER(AccessorInfo)
10209 // Append all descriptors to the array that are not already there.
10210 // Return number added.
10211 static int AppendUnique(Handle<Object> descriptors,
10212 Handle<FixedArray> array,
10213 int valid_descriptors);
10215 static const int kNameOffset = HeapObject::kHeaderSize;
10216 static const int kFlagOffset = kNameOffset + kPointerSize;
10217 static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
10218 static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
10221 inline bool HasExpectedReceiverType() {
10222 return expected_receiver_type()->IsFunctionTemplateInfo();
10224 // Bit positions in flag.
10225 static const int kAllCanReadBit = 0;
10226 static const int kAllCanWriteBit = 1;
10227 static const int kSpecialDataProperty = 2;
10228 class AttributesField : public BitField<PropertyAttributes, 3, 3> {};
10230 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
10234 // An accessor must have a getter, but can have no setter.
10236 // When setting a property, V8 searches accessors in prototypes.
10237 // If an accessor was found and it does not have a setter,
10238 // the request is ignored.
10240 // If the accessor in the prototype has the READ_ONLY property attribute, then
10241 // a new value is added to the derived object when the property is set.
10242 // This shadows the accessor in the prototype.
10243 class ExecutableAccessorInfo: public AccessorInfo {
10245 DECL_ACCESSORS(getter, Object)
10246 DECL_ACCESSORS(setter, Object)
10247 DECL_ACCESSORS(data, Object)
10249 DECLARE_CAST(ExecutableAccessorInfo)
10251 // Dispatched behavior.
10252 DECLARE_PRINTER(ExecutableAccessorInfo)
10253 DECLARE_VERIFIER(ExecutableAccessorInfo)
10255 static const int kGetterOffset = AccessorInfo::kSize;
10256 static const int kSetterOffset = kGetterOffset + kPointerSize;
10257 static const int kDataOffset = kSetterOffset + kPointerSize;
10258 static const int kSize = kDataOffset + kPointerSize;
10260 static void ClearSetter(Handle<ExecutableAccessorInfo> info);
10263 DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
10267 // Support for JavaScript accessors: A pair of a getter and a setter. Each
10268 // accessor can either be
10269 // * a pointer to a JavaScript function or proxy: a real accessor
10270 // * undefined: considered an accessor by the spec, too, strangely enough
10271 // * the hole: an accessor which has not been set
10272 // * a pointer to a map: a transition used to ensure map sharing
10273 class AccessorPair: public Struct {
10275 DECL_ACCESSORS(getter, Object)
10276 DECL_ACCESSORS(setter, Object)
10278 DECLARE_CAST(AccessorPair)
10280 static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
10282 Object* get(AccessorComponent component) {
10283 return component == ACCESSOR_GETTER ? getter() : setter();
10286 void set(AccessorComponent component, Object* value) {
10287 if (component == ACCESSOR_GETTER) {
10294 // Note: Returns undefined instead in case of a hole.
10295 Object* GetComponent(AccessorComponent component);
10297 // Set both components, skipping arguments which are a JavaScript null.
10298 void SetComponents(Object* getter, Object* setter) {
10299 if (!getter->IsNull()) set_getter(getter);
10300 if (!setter->IsNull()) set_setter(setter);
10303 bool Equals(AccessorPair* pair) {
10304 return (this == pair) || pair->Equals(getter(), setter());
10307 bool Equals(Object* getter_value, Object* setter_value) {
10308 return (getter() == getter_value) && (setter() == setter_value);
10311 bool ContainsAccessor() {
10312 return IsJSAccessor(getter()) || IsJSAccessor(setter());
10315 // Dispatched behavior.
10316 DECLARE_PRINTER(AccessorPair)
10317 DECLARE_VERIFIER(AccessorPair)
10319 static const int kGetterOffset = HeapObject::kHeaderSize;
10320 static const int kSetterOffset = kGetterOffset + kPointerSize;
10321 static const int kSize = kSetterOffset + kPointerSize;
10324 // Strangely enough, in addition to functions and harmony proxies, the spec
10325 // requires us to consider undefined as a kind of accessor, too:
10327 // Object.defineProperty(obj, "foo", {get: undefined});
10328 // assertTrue("foo" in obj);
10329 bool IsJSAccessor(Object* obj) {
10330 return obj->IsSpecFunction() || obj->IsUndefined();
10333 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
10337 class AccessCheckInfo: public Struct {
10339 DECL_ACCESSORS(named_callback, Object)
10340 DECL_ACCESSORS(indexed_callback, Object)
10341 DECL_ACCESSORS(data, Object)
10343 DECLARE_CAST(AccessCheckInfo)
10345 // Dispatched behavior.
10346 DECLARE_PRINTER(AccessCheckInfo)
10347 DECLARE_VERIFIER(AccessCheckInfo)
10349 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
10350 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
10351 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
10352 static const int kSize = kDataOffset + kPointerSize;
10355 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
10359 class InterceptorInfo: public Struct {
10361 DECL_ACCESSORS(getter, Object)
10362 DECL_ACCESSORS(setter, Object)
10363 DECL_ACCESSORS(query, Object)
10364 DECL_ACCESSORS(deleter, Object)
10365 DECL_ACCESSORS(enumerator, Object)
10366 DECL_ACCESSORS(data, Object)
10367 DECL_BOOLEAN_ACCESSORS(can_intercept_symbols)
10368 DECL_BOOLEAN_ACCESSORS(all_can_read)
10369 DECL_BOOLEAN_ACCESSORS(non_masking)
10371 inline int flags() const;
10372 inline void set_flags(int flags);
10374 DECLARE_CAST(InterceptorInfo)
10376 // Dispatched behavior.
10377 DECLARE_PRINTER(InterceptorInfo)
10378 DECLARE_VERIFIER(InterceptorInfo)
10380 static const int kGetterOffset = HeapObject::kHeaderSize;
10381 static const int kSetterOffset = kGetterOffset + kPointerSize;
10382 static const int kQueryOffset = kSetterOffset + kPointerSize;
10383 static const int kDeleterOffset = kQueryOffset + kPointerSize;
10384 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
10385 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
10386 static const int kFlagsOffset = kDataOffset + kPointerSize;
10387 static const int kSize = kFlagsOffset + kPointerSize;
10389 static const int kCanInterceptSymbolsBit = 0;
10390 static const int kAllCanReadBit = 1;
10391 static const int kNonMasking = 2;
10394 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
10398 class CallHandlerInfo: public Struct {
10400 DECL_ACCESSORS(callback, Object)
10401 DECL_ACCESSORS(data, Object)
10403 DECLARE_CAST(CallHandlerInfo)
10405 // Dispatched behavior.
10406 DECLARE_PRINTER(CallHandlerInfo)
10407 DECLARE_VERIFIER(CallHandlerInfo)
10409 static const int kCallbackOffset = HeapObject::kHeaderSize;
10410 static const int kDataOffset = kCallbackOffset + kPointerSize;
10411 static const int kSize = kDataOffset + kPointerSize;
10414 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
10418 class TemplateInfo: public Struct {
10420 DECL_ACCESSORS(tag, Object)
10421 inline int number_of_properties() const;
10422 inline void set_number_of_properties(int value);
10423 DECL_ACCESSORS(property_list, Object)
10424 DECL_ACCESSORS(property_accessors, Object)
10426 DECLARE_VERIFIER(TemplateInfo)
10428 static const int kTagOffset = HeapObject::kHeaderSize;
10429 static const int kNumberOfProperties = kTagOffset + kPointerSize;
10430 static const int kPropertyListOffset = kNumberOfProperties + kPointerSize;
10431 static const int kPropertyAccessorsOffset =
10432 kPropertyListOffset + kPointerSize;
10433 static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
10436 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
10440 class FunctionTemplateInfo: public TemplateInfo {
10442 DECL_ACCESSORS(serial_number, Object)
10443 DECL_ACCESSORS(call_code, Object)
10444 DECL_ACCESSORS(prototype_template, Object)
10445 DECL_ACCESSORS(parent_template, Object)
10446 DECL_ACCESSORS(named_property_handler, Object)
10447 DECL_ACCESSORS(indexed_property_handler, Object)
10448 DECL_ACCESSORS(instance_template, Object)
10449 DECL_ACCESSORS(class_name, Object)
10450 DECL_ACCESSORS(signature, Object)
10451 DECL_ACCESSORS(instance_call_handler, Object)
10452 DECL_ACCESSORS(access_check_info, Object)
10453 DECL_ACCESSORS(flag, Smi)
10455 inline int length() const;
10456 inline void set_length(int value);
10458 // Following properties use flag bits.
10459 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
10460 DECL_BOOLEAN_ACCESSORS(undetectable)
10461 // If the bit is set, object instances created by this function
10462 // requires access check.
10463 DECL_BOOLEAN_ACCESSORS(needs_access_check)
10464 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
10465 DECL_BOOLEAN_ACCESSORS(remove_prototype)
10466 DECL_BOOLEAN_ACCESSORS(do_not_cache)
10467 DECL_BOOLEAN_ACCESSORS(instantiated)
10468 DECL_BOOLEAN_ACCESSORS(accept_any_receiver)
10470 DECLARE_CAST(FunctionTemplateInfo)
10472 // Dispatched behavior.
10473 DECLARE_PRINTER(FunctionTemplateInfo)
10474 DECLARE_VERIFIER(FunctionTemplateInfo)
10476 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
10477 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
10478 static const int kPrototypeTemplateOffset =
10479 kCallCodeOffset + kPointerSize;
10480 static const int kParentTemplateOffset =
10481 kPrototypeTemplateOffset + kPointerSize;
10482 static const int kNamedPropertyHandlerOffset =
10483 kParentTemplateOffset + kPointerSize;
10484 static const int kIndexedPropertyHandlerOffset =
10485 kNamedPropertyHandlerOffset + kPointerSize;
10486 static const int kInstanceTemplateOffset =
10487 kIndexedPropertyHandlerOffset + kPointerSize;
10488 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
10489 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
10490 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
10491 static const int kAccessCheckInfoOffset =
10492 kInstanceCallHandlerOffset + kPointerSize;
10493 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
10494 static const int kLengthOffset = kFlagOffset + kPointerSize;
10495 static const int kSize = kLengthOffset + kPointerSize;
10497 // Returns true if |object| is an instance of this function template.
10498 bool IsTemplateFor(Object* object);
10499 bool IsTemplateFor(Map* map);
10501 // Returns the holder JSObject if the function can legally be called with this
10502 // receiver. Returns Heap::null_value() if the call is illegal.
10503 Object* GetCompatibleReceiver(Isolate* isolate, Object* receiver);
10506 // Bit position in the flag, from least significant bit position.
10507 static const int kHiddenPrototypeBit = 0;
10508 static const int kUndetectableBit = 1;
10509 static const int kNeedsAccessCheckBit = 2;
10510 static const int kReadOnlyPrototypeBit = 3;
10511 static const int kRemovePrototypeBit = 4;
10512 static const int kDoNotCacheBit = 5;
10513 static const int kInstantiatedBit = 6;
10514 static const int kAcceptAnyReceiver = 7;
10516 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
10520 class ObjectTemplateInfo: public TemplateInfo {
10522 DECL_ACCESSORS(constructor, Object)
10523 DECL_ACCESSORS(internal_field_count, Object)
10525 DECLARE_CAST(ObjectTemplateInfo)
10527 // Dispatched behavior.
10528 DECLARE_PRINTER(ObjectTemplateInfo)
10529 DECLARE_VERIFIER(ObjectTemplateInfo)
10531 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10532 static const int kInternalFieldCountOffset =
10533 kConstructorOffset + kPointerSize;
10534 static const int kSize = kInternalFieldCountOffset + kPointerSize;
10538 class TypeSwitchInfo: public Struct {
10540 DECL_ACCESSORS(types, Object)
10542 DECLARE_CAST(TypeSwitchInfo)
10544 // Dispatched behavior.
10545 DECLARE_PRINTER(TypeSwitchInfo)
10546 DECLARE_VERIFIER(TypeSwitchInfo)
10548 static const int kTypesOffset = Struct::kHeaderSize;
10549 static const int kSize = kTypesOffset + kPointerSize;
10553 // The DebugInfo class holds additional information for a function being
10555 class DebugInfo: public Struct {
10557 // The shared function info for the source being debugged.
10558 DECL_ACCESSORS(shared, SharedFunctionInfo)
10559 // Code object for the patched code. This code object is the code object
10560 // currently active for the function.
10561 DECL_ACCESSORS(code, Code)
10562 // Fixed array holding status information for each active break point.
10563 DECL_ACCESSORS(break_points, FixedArray)
10565 // Check if there is a break point at a code position.
10566 bool HasBreakPoint(int code_position);
10567 // Get the break point info object for a code position.
10568 Object* GetBreakPointInfo(int code_position);
10569 // Clear a break point.
10570 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
10572 Handle<Object> break_point_object);
10573 // Set a break point.
10574 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
10575 int source_position, int statement_position,
10576 Handle<Object> break_point_object);
10577 // Get the break point objects for a code position.
10578 Handle<Object> GetBreakPointObjects(int code_position);
10579 // Find the break point info holding this break point object.
10580 static Handle<Object> FindBreakPointInfo(Handle<DebugInfo> debug_info,
10581 Handle<Object> break_point_object);
10582 // Get the number of break points for this function.
10583 int GetBreakPointCount();
10585 DECLARE_CAST(DebugInfo)
10587 // Dispatched behavior.
10588 DECLARE_PRINTER(DebugInfo)
10589 DECLARE_VERIFIER(DebugInfo)
10591 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
10592 static const int kCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
10593 static const int kBreakPointsStateIndex = kCodeIndex + kPointerSize;
10594 static const int kSize = kBreakPointsStateIndex + kPointerSize;
10596 static const int kEstimatedNofBreakPointsInFunction = 16;
10599 static const int kNoBreakPointInfo = -1;
10601 // Lookup the index in the break_points array for a code position.
10602 int GetBreakPointInfoIndex(int code_position);
10604 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
10608 // The BreakPointInfo class holds information for break points set in a
10609 // function. The DebugInfo object holds a BreakPointInfo object for each code
10610 // position with one or more break points.
10611 class BreakPointInfo: public Struct {
10613 // The position in the code for the break point.
10614 DECL_ACCESSORS(code_position, Smi)
10615 // The position in the source for the break position.
10616 DECL_ACCESSORS(source_position, Smi)
10617 // The position in the source for the last statement before this break
10619 DECL_ACCESSORS(statement_position, Smi)
10620 // List of related JavaScript break points.
10621 DECL_ACCESSORS(break_point_objects, Object)
10623 // Removes a break point.
10624 static void ClearBreakPoint(Handle<BreakPointInfo> info,
10625 Handle<Object> break_point_object);
10626 // Set a break point.
10627 static void SetBreakPoint(Handle<BreakPointInfo> info,
10628 Handle<Object> break_point_object);
10629 // Check if break point info has this break point object.
10630 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
10631 Handle<Object> break_point_object);
10632 // Get the number of break points for this code position.
10633 int GetBreakPointCount();
10635 DECLARE_CAST(BreakPointInfo)
10637 // Dispatched behavior.
10638 DECLARE_PRINTER(BreakPointInfo)
10639 DECLARE_VERIFIER(BreakPointInfo)
10641 static const int kCodePositionIndex = Struct::kHeaderSize;
10642 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
10643 static const int kStatementPositionIndex =
10644 kSourcePositionIndex + kPointerSize;
10645 static const int kBreakPointObjectsIndex =
10646 kStatementPositionIndex + kPointerSize;
10647 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
10650 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
10654 #undef DECL_BOOLEAN_ACCESSORS
10655 #undef DECL_ACCESSORS
10656 #undef DECLARE_CAST
10657 #undef DECLARE_VERIFIER
10659 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
10660 V(kStringTable, "string_table", "(Internalized strings)") \
10661 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
10662 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
10663 V(kSmiRootList, "smi_root_list", "(Smi roots)") \
10664 V(kInternalizedString, "internalized_string", "(Internal string)") \
10665 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
10666 V(kTop, "top", "(Isolate)") \
10667 V(kRelocatable, "relocatable", "(Relocatable)") \
10668 V(kDebug, "debug", "(Debugger)") \
10669 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
10670 V(kHandleScope, "handlescope", "(Handle scope)") \
10671 V(kBuiltins, "builtins", "(Builtins)") \
10672 V(kGlobalHandles, "globalhandles", "(Global handles)") \
10673 V(kEternalHandles, "eternalhandles", "(Eternal handles)") \
10674 V(kThreadManager, "threadmanager", "(Thread manager)") \
10675 V(kStrongRoots, "strong roots", "(Strong roots)") \
10676 V(kExtensions, "Extensions", "(Extensions)")
10678 class VisitorSynchronization : public AllStatic {
10680 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
10682 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
10685 #undef DECLARE_ENUM
10687 static const char* const kTags[kNumberOfSyncTags];
10688 static const char* const kTagNames[kNumberOfSyncTags];
10691 // Abstract base class for visiting, and optionally modifying, the
10692 // pointers contained in Objects. Used in GC and serialization/deserialization.
10693 class ObjectVisitor BASE_EMBEDDED {
10695 virtual ~ObjectVisitor() {}
10697 // Visits a contiguous arrays of pointers in the half-open range
10698 // [start, end). Any or all of the values may be modified on return.
10699 virtual void VisitPointers(Object** start, Object** end) = 0;
10701 // Handy shorthand for visiting a single pointer.
10702 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
10704 // Visit weak next_code_link in Code object.
10705 virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
10707 // To allow lazy clearing of inline caches the visitor has
10708 // a rich interface for iterating over Code objects..
10710 // Visits a code target in the instruction stream.
10711 virtual void VisitCodeTarget(RelocInfo* rinfo);
10713 // Visits a code entry in a JS function.
10714 virtual void VisitCodeEntry(Address entry_address);
10716 // Visits a global property cell reference in the instruction stream.
10717 virtual void VisitCell(RelocInfo* rinfo);
10719 // Visits a runtime entry in the instruction stream.
10720 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
10722 // Visits the resource of an one-byte or two-byte string.
10723 virtual void VisitExternalOneByteString(
10724 v8::String::ExternalOneByteStringResource** resource) {}
10725 virtual void VisitExternalTwoByteString(
10726 v8::String::ExternalStringResource** resource) {}
10728 // Visits a debug call target in the instruction stream.
10729 virtual void VisitDebugTarget(RelocInfo* rinfo);
10731 // Visits the byte sequence in a function's prologue that contains information
10732 // about the code's age.
10733 virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
10735 // Visit pointer embedded into a code object.
10736 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
10738 // Visits an external reference embedded into a code object.
10739 virtual void VisitExternalReference(RelocInfo* rinfo);
10741 // Visits an external reference.
10742 virtual void VisitExternalReference(Address* p) {}
10744 // Visits an (encoded) internal reference.
10745 virtual void VisitInternalReference(RelocInfo* rinfo) {}
10747 // Visits a handle that has an embedder-assigned class ID.
10748 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
10750 // Intended for serialization/deserialization checking: insert, or
10751 // check for the presence of, a tag at this position in the stream.
10752 // Also used for marking up GC roots in heap snapshots.
10753 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
10757 class StructBodyDescriptor : public
10758 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
10760 static inline int SizeOf(Map* map, HeapObject* object) {
10761 return map->instance_size();
10766 // BooleanBit is a helper class for setting and getting a bit in an
10768 class BooleanBit : public AllStatic {
10770 static inline bool get(Smi* smi, int bit_position) {
10771 return get(smi->value(), bit_position);
10774 static inline bool get(int value, int bit_position) {
10775 return (value & (1 << bit_position)) != 0;
10778 static inline Smi* set(Smi* smi, int bit_position, bool v) {
10779 return Smi::FromInt(set(smi->value(), bit_position, v));
10782 static inline int set(int value, int bit_position, bool v) {
10784 value |= (1 << bit_position);
10786 value &= ~(1 << bit_position);
10792 } } // namespace v8::internal
10794 #endif // V8_OBJECTS_H_