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) \
386 V(PROPERTY_CELL_TYPE) \
388 V(HEAP_NUMBER_TYPE) \
389 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) \
926 V(ExternalTwoByteString) \
927 V(ExternalOneByteString) \
928 V(SeqTwoByteString) \
929 V(SeqOneByteString) \
930 V(InternalizedString) \
934 V(ExternalInt8Array) \
935 V(ExternalUint8Array) \
936 V(ExternalInt16Array) \
937 V(ExternalUint16Array) \
938 V(ExternalInt32Array) \
939 V(ExternalUint32Array) \
940 V(ExternalFloat32Array) \
941 V(ExternalFloat64Array) \
942 V(ExternalUint8ClampedArray) \
943 V(FixedTypedArrayBase) \
946 V(FixedUint16Array) \
948 V(FixedUint32Array) \
950 V(FixedFloat32Array) \
951 V(FixedFloat64Array) \
952 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
2056 // index. Returns the number of properties added.
2057 int GetOwnPropertyNames(FixedArray* storage, int index,
2058 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);
2286 static bool AllCanRead(LookupIterator* it);
2287 static bool AllCanWrite(LookupIterator* it);
2290 friend class JSReceiver;
2291 friend class Object;
2293 static void MigrateFastToFast(Handle<JSObject> object, Handle<Map> new_map);
2294 static void MigrateFastToSlow(Handle<JSObject> object,
2295 Handle<Map> new_map,
2296 int expected_additional_properties);
2298 // Used from Object::GetProperty().
2299 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithFailedAccessCheck(
2300 LookupIterator* it);
2302 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithFailedAccessCheck(
2303 LookupIterator* it, Handle<Object> value);
2305 // Add a property to a slow-case object.
2306 static void AddSlowProperty(Handle<JSObject> object,
2308 Handle<Object> value,
2309 PropertyAttributes attributes);
2311 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithInterceptor(
2312 LookupIterator* it);
2314 bool ReferencesObjectFromElements(FixedArray* elements,
2318 // Return the hash table backing store or the inline stored identity hash,
2319 // whatever is found.
2320 MUST_USE_RESULT Object* GetHiddenPropertiesHashTable();
2322 // Return the hash table backing store for hidden properties. If there is no
2323 // backing store, allocate one.
2324 static Handle<ObjectHashTable> GetOrCreateHiddenPropertiesHashtable(
2325 Handle<JSObject> object);
2327 // Set the hidden property backing store to either a hash table or
2328 // the inline-stored identity hash.
2329 static Handle<Object> SetHiddenPropertiesHashTable(
2330 Handle<JSObject> object,
2331 Handle<Object> value);
2333 MUST_USE_RESULT Object* GetIdentityHash();
2335 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSObject> object);
2337 static Handle<SeededNumberDictionary> GetNormalizedElementDictionary(
2338 Handle<JSObject> object, Handle<FixedArrayBase> elements);
2340 // Helper for fast versions of preventExtensions, seal, and freeze.
2341 // attrs is one of NONE, SEALED, or FROZEN (depending on the operation).
2342 template <PropertyAttributes attrs>
2343 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensionsWithTransition(
2344 Handle<JSObject> object);
2346 DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
2350 // Common superclass for FixedArrays that allow implementations to share
2351 // common accessors and some code paths.
2352 class FixedArrayBase: public HeapObject {
2354 // [length]: length of the array.
2355 inline int length() const;
2356 inline void set_length(int value);
2358 // Get and set the length using acquire loads and release stores.
2359 inline int synchronized_length() const;
2360 inline void synchronized_set_length(int value);
2362 DECLARE_CAST(FixedArrayBase)
2364 // Layout description.
2365 // Length is smi tagged when it is stored.
2366 static const int kLengthOffset = HeapObject::kHeaderSize;
2367 static const int kHeaderSize = kLengthOffset + kPointerSize;
2371 class FixedDoubleArray;
2372 class IncrementalMarking;
2375 // FixedArray describes fixed-sized arrays with element type Object*.
2376 class FixedArray: public FixedArrayBase {
2378 // Setter and getter for elements.
2379 inline Object* get(int index) const;
2380 void SetValue(uint32_t index, Object* value);
2381 static inline Handle<Object> get(Handle<FixedArray> array, int index);
2382 // Setter that uses write barrier.
2383 inline void set(int index, Object* value);
2384 inline bool is_the_hole(int index);
2386 // Setter that doesn't need write barrier.
2387 inline void set(int index, Smi* value);
2388 // Setter with explicit barrier mode.
2389 inline void set(int index, Object* value, WriteBarrierMode mode);
2391 // Setters for frequently used oddballs located in old space.
2392 inline void set_undefined(int index);
2393 inline void set_null(int index);
2394 inline void set_the_hole(int index);
2396 inline Object** GetFirstElementAddress();
2397 inline bool ContainsOnlySmisOrHoles();
2399 // Gives access to raw memory which stores the array's data.
2400 inline Object** data_start();
2402 inline void FillWithHoles(int from, int to);
2404 // Shrink length and insert filler objects.
2405 void Shrink(int length);
2408 static Handle<FixedArray> CopySize(Handle<FixedArray> array,
2410 PretenureFlag pretenure = NOT_TENURED);
2412 enum KeyFilter { ALL_KEYS, NON_SYMBOL_KEYS };
2414 // Add the elements of a JSArray to this FixedArray.
2415 MUST_USE_RESULT static MaybeHandle<FixedArray> AddKeysFromArrayLike(
2416 Handle<FixedArray> content, Handle<JSObject> array,
2417 KeyFilter filter = ALL_KEYS);
2419 // Computes the union of keys and return the result.
2420 // Used for implementing "for (n in object) { }"
2421 MUST_USE_RESULT static MaybeHandle<FixedArray> UnionOfKeys(
2422 Handle<FixedArray> first,
2423 Handle<FixedArray> second);
2425 // Copy a sub array from the receiver to dest.
2426 void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
2428 // Garbage collection support.
2429 static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
2431 // Code Generation support.
2432 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2434 // Garbage collection support.
2435 Object** RawFieldOfElementAt(int index) {
2436 return HeapObject::RawField(this, OffsetOfElementAt(index));
2439 DECLARE_CAST(FixedArray)
2441 // Maximal allowed size, in bytes, of a single FixedArray.
2442 // Prevents overflowing size computations, as well as extreme memory
2444 static const int kMaxSize = 128 * MB * kPointerSize;
2445 // Maximally allowed length of a FixedArray.
2446 static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
2448 // Dispatched behavior.
2449 DECLARE_PRINTER(FixedArray)
2450 DECLARE_VERIFIER(FixedArray)
2452 // Checks if two FixedArrays have identical contents.
2453 bool IsEqualTo(FixedArray* other);
2456 // Swap two elements in a pair of arrays. If this array and the
2457 // numbers array are the same object, the elements are only swapped
2459 void SwapPairs(FixedArray* numbers, int i, int j);
2461 // Sort prefix of this array and the numbers array as pairs wrt. the
2462 // numbers. If the numbers array and the this array are the same
2463 // object, the prefix of this array is sorted.
2464 void SortPairs(FixedArray* numbers, uint32_t len);
2466 class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
2468 static inline int SizeOf(Map* map, HeapObject* object) {
2470 reinterpret_cast<FixedArray*>(object)->synchronized_length());
2475 // Set operation on FixedArray without using write barriers. Can
2476 // only be used for storing old space objects or smis.
2477 static inline void NoWriteBarrierSet(FixedArray* array,
2481 // Set operation on FixedArray without incremental write barrier. Can
2482 // only be used if the object is guaranteed to be white (whiteness witness
2484 static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
2489 STATIC_ASSERT(kHeaderSize == Internals::kFixedArrayHeaderSize);
2491 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
2495 // FixedDoubleArray describes fixed-sized arrays with element type double.
2496 class FixedDoubleArray: public FixedArrayBase {
2498 // Setter and getter for elements.
2499 inline double get_scalar(int index);
2500 inline uint64_t get_representation(int index);
2501 static inline Handle<Object> get(Handle<FixedDoubleArray> array, int index);
2502 // This accessor has to get a Number as |value|.
2503 void SetValue(uint32_t index, Object* value);
2504 inline void set(int index, double value);
2505 inline void set_the_hole(int index);
2507 // Checking for the hole.
2508 inline bool is_the_hole(int index);
2510 // Garbage collection support.
2511 inline static int SizeFor(int length) {
2512 return kHeaderSize + length * kDoubleSize;
2515 // Gives access to raw memory which stores the array's data.
2516 inline double* data_start();
2518 inline void FillWithHoles(int from, int to);
2520 // Code Generation support.
2521 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2523 DECLARE_CAST(FixedDoubleArray)
2525 // Maximal allowed size, in bytes, of a single FixedDoubleArray.
2526 // Prevents overflowing size computations, as well as extreme memory
2528 static const int kMaxSize = 512 * MB;
2529 // Maximally allowed length of a FixedArray.
2530 static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
2532 // Dispatched behavior.
2533 DECLARE_PRINTER(FixedDoubleArray)
2534 DECLARE_VERIFIER(FixedDoubleArray)
2537 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
2541 class WeakFixedArray : public FixedArray {
2543 enum SearchForDuplicates { kAlwaysAdd, kAddIfNotFound };
2545 // If |maybe_array| is not a WeakFixedArray, a fresh one will be allocated.
2546 static Handle<WeakFixedArray> Add(
2547 Handle<Object> maybe_array, Handle<HeapObject> value,
2548 SearchForDuplicates search_for_duplicates = kAlwaysAdd,
2549 bool* was_present = NULL);
2551 // Returns true if an entry was found and removed.
2552 bool Remove(Handle<HeapObject> value);
2556 inline Object* Get(int index) const;
2557 inline void Clear(int index);
2558 inline int Length() const;
2560 inline bool IsEmptySlot(int index) const;
2561 static Object* Empty() { return Smi::FromInt(0); }
2563 DECLARE_CAST(WeakFixedArray)
2566 static const int kLastUsedIndexIndex = 0;
2567 static const int kFirstIndex = 1;
2569 static Handle<WeakFixedArray> Allocate(
2570 Isolate* isolate, int size, Handle<WeakFixedArray> initialize_from);
2572 static void Set(Handle<WeakFixedArray> array, int index,
2573 Handle<HeapObject> value);
2574 inline void clear(int index);
2576 inline int last_used_index() const;
2577 inline void set_last_used_index(int index);
2579 // Disallow inherited setters.
2580 void set(int index, Smi* value);
2581 void set(int index, Object* value);
2582 void set(int index, Object* value, WriteBarrierMode mode);
2583 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakFixedArray);
2587 // Generic array grows dynamically with O(1) amortized insertion.
2588 class ArrayList : public FixedArray {
2592 // Use this if GC can delete elements from the array.
2593 kReloadLengthAfterAllocation,
2595 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj,
2596 AddMode mode = kNone);
2597 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj1,
2598 Handle<Object> obj2, AddMode = kNone);
2599 inline int Length();
2600 inline void SetLength(int length);
2601 inline Object* Get(int index);
2602 inline Object** Slot(int index);
2603 inline void Set(int index, Object* obj);
2604 inline void Clear(int index, Object* undefined);
2605 DECLARE_CAST(ArrayList)
2608 static Handle<ArrayList> EnsureSpace(Handle<ArrayList> array, int length);
2609 static const int kLengthIndex = 0;
2610 static const int kFirstIndex = 1;
2611 DISALLOW_IMPLICIT_CONSTRUCTORS(ArrayList);
2615 // DescriptorArrays are fixed arrays used to hold instance descriptors.
2616 // The format of the these objects is:
2617 // [0]: Number of descriptors
2618 // [1]: Either Smi(0) if uninitialized, or a pointer to small fixed array:
2619 // [0]: pointer to fixed array with enum cache
2620 // [1]: either Smi(0) or pointer to fixed array with indices
2622 // [2 + number of descriptors * kDescriptorSize]: start of slack
2623 class DescriptorArray: public FixedArray {
2625 // Returns true for both shared empty_descriptor_array and for smis, which the
2626 // map uses to encode additional bit fields when the descriptor array is not
2628 inline bool IsEmpty();
2630 // Returns the number of descriptors in the array.
2631 int number_of_descriptors() {
2632 DCHECK(length() >= kFirstIndex || IsEmpty());
2634 return len == 0 ? 0 : Smi::cast(get(kDescriptorLengthIndex))->value();
2637 int number_of_descriptors_storage() {
2639 return len == 0 ? 0 : (len - kFirstIndex) / kDescriptorSize;
2642 int NumberOfSlackDescriptors() {
2643 return number_of_descriptors_storage() - number_of_descriptors();
2646 inline void SetNumberOfDescriptors(int number_of_descriptors);
2647 inline int number_of_entries() { return number_of_descriptors(); }
2649 bool HasEnumCache() {
2650 return !IsEmpty() && !get(kEnumCacheIndex)->IsSmi();
2653 void CopyEnumCacheFrom(DescriptorArray* array) {
2654 set(kEnumCacheIndex, array->get(kEnumCacheIndex));
2657 FixedArray* GetEnumCache() {
2658 DCHECK(HasEnumCache());
2659 FixedArray* bridge = FixedArray::cast(get(kEnumCacheIndex));
2660 return FixedArray::cast(bridge->get(kEnumCacheBridgeCacheIndex));
2663 bool HasEnumIndicesCache() {
2664 if (IsEmpty()) return false;
2665 Object* object = get(kEnumCacheIndex);
2666 if (object->IsSmi()) return false;
2667 FixedArray* bridge = FixedArray::cast(object);
2668 return !bridge->get(kEnumCacheBridgeIndicesCacheIndex)->IsSmi();
2671 FixedArray* GetEnumIndicesCache() {
2672 DCHECK(HasEnumIndicesCache());
2673 FixedArray* bridge = FixedArray::cast(get(kEnumCacheIndex));
2674 return FixedArray::cast(bridge->get(kEnumCacheBridgeIndicesCacheIndex));
2677 Object** GetEnumCacheSlot() {
2678 DCHECK(HasEnumCache());
2679 return HeapObject::RawField(reinterpret_cast<HeapObject*>(this),
2683 void ClearEnumCache();
2685 // Initialize or change the enum cache,
2686 // using the supplied storage for the small "bridge".
2687 void SetEnumCache(FixedArray* bridge_storage,
2688 FixedArray* new_cache,
2689 Object* new_index_cache);
2691 bool CanHoldValue(int descriptor, Object* value);
2693 // Accessors for fetching instance descriptor at descriptor number.
2694 inline Name* GetKey(int descriptor_number);
2695 inline Object** GetKeySlot(int descriptor_number);
2696 inline Object* GetValue(int descriptor_number);
2697 inline void SetValue(int descriptor_number, Object* value);
2698 inline Object** GetValueSlot(int descriptor_number);
2699 static inline int GetValueOffset(int descriptor_number);
2700 inline Object** GetDescriptorStartSlot(int descriptor_number);
2701 inline Object** GetDescriptorEndSlot(int descriptor_number);
2702 inline PropertyDetails GetDetails(int descriptor_number);
2703 inline PropertyType GetType(int descriptor_number);
2704 inline int GetFieldIndex(int descriptor_number);
2705 inline HeapType* GetFieldType(int descriptor_number);
2706 inline Object* GetConstant(int descriptor_number);
2707 inline Object* GetCallbacksObject(int descriptor_number);
2708 inline AccessorDescriptor* GetCallbacks(int descriptor_number);
2710 inline Name* GetSortedKey(int descriptor_number);
2711 inline int GetSortedKeyIndex(int descriptor_number);
2712 inline void SetSortedKey(int pointer, int descriptor_number);
2713 inline void SetRepresentation(int descriptor_number,
2714 Representation representation);
2716 // Accessor for complete descriptor.
2717 inline void Get(int descriptor_number, Descriptor* desc);
2718 inline void Set(int descriptor_number, Descriptor* desc);
2719 void Replace(int descriptor_number, Descriptor* descriptor);
2721 // Append automatically sets the enumeration index. This should only be used
2722 // to add descriptors in bulk at the end, followed by sorting the descriptor
2724 inline void Append(Descriptor* desc);
2726 static Handle<DescriptorArray> CopyUpTo(Handle<DescriptorArray> desc,
2727 int enumeration_index,
2730 static Handle<DescriptorArray> CopyUpToAddAttributes(
2731 Handle<DescriptorArray> desc,
2732 int enumeration_index,
2733 PropertyAttributes attributes,
2736 // Sort the instance descriptors by the hash codes of their keys.
2739 // Search the instance descriptors for given name.
2740 INLINE(int Search(Name* name, int number_of_own_descriptors));
2742 // As the above, but uses DescriptorLookupCache and updates it when
2744 INLINE(int SearchWithCache(Name* name, Map* map));
2746 // Allocates a DescriptorArray, but returns the singleton
2747 // empty descriptor array object if number_of_descriptors is 0.
2748 static Handle<DescriptorArray> Allocate(Isolate* isolate,
2749 int number_of_descriptors,
2752 DECLARE_CAST(DescriptorArray)
2754 // Constant for denoting key was not found.
2755 static const int kNotFound = -1;
2757 static const int kDescriptorLengthIndex = 0;
2758 static const int kEnumCacheIndex = 1;
2759 static const int kFirstIndex = 2;
2761 // The length of the "bridge" to the enum cache.
2762 static const int kEnumCacheBridgeLength = 2;
2763 static const int kEnumCacheBridgeCacheIndex = 0;
2764 static const int kEnumCacheBridgeIndicesCacheIndex = 1;
2766 // Layout description.
2767 static const int kDescriptorLengthOffset = FixedArray::kHeaderSize;
2768 static const int kEnumCacheOffset = kDescriptorLengthOffset + kPointerSize;
2769 static const int kFirstOffset = kEnumCacheOffset + kPointerSize;
2771 // Layout description for the bridge array.
2772 static const int kEnumCacheBridgeCacheOffset = FixedArray::kHeaderSize;
2774 // Layout of descriptor.
2775 static const int kDescriptorKey = 0;
2776 static const int kDescriptorDetails = 1;
2777 static const int kDescriptorValue = 2;
2778 static const int kDescriptorSize = 3;
2780 #if defined(DEBUG) || defined(OBJECT_PRINT)
2781 // For our gdb macros, we should perhaps change these in the future.
2784 // Print all the descriptors.
2785 void PrintDescriptors(std::ostream& os); // NOLINT
2789 // Is the descriptor array sorted and without duplicates?
2790 bool IsSortedNoDuplicates(int valid_descriptors = -1);
2792 // Is the descriptor array consistent with the back pointers in targets?
2793 bool IsConsistentWithBackPointers(Map* current_map);
2795 // Are two DescriptorArrays equal?
2796 bool IsEqualTo(DescriptorArray* other);
2799 // Returns the fixed array length required to hold number_of_descriptors
2801 static int LengthFor(int number_of_descriptors) {
2802 return ToKeyIndex(number_of_descriptors);
2806 // WhitenessWitness is used to prove that a descriptor array is white
2807 // (unmarked), so incremental write barriers can be skipped because the
2808 // marking invariant cannot be broken and slots pointing into evacuation
2809 // candidates will be discovered when the object is scanned. A witness is
2810 // always stack-allocated right after creating an array. By allocating a
2811 // witness, incremental marking is globally disabled. The witness is then
2812 // passed along wherever needed to statically prove that the array is known to
2814 class WhitenessWitness {
2816 inline explicit WhitenessWitness(DescriptorArray* array);
2817 inline ~WhitenessWitness();
2820 IncrementalMarking* marking_;
2823 // An entry in a DescriptorArray, represented as an (array, index) pair.
2826 inline explicit Entry(DescriptorArray* descs, int index) :
2827 descs_(descs), index_(index) { }
2829 inline PropertyType type() { return descs_->GetType(index_); }
2830 inline Object* GetCallbackObject() { return descs_->GetValue(index_); }
2833 DescriptorArray* descs_;
2837 // Conversion from descriptor number to array indices.
2838 static int ToKeyIndex(int descriptor_number) {
2839 return kFirstIndex +
2840 (descriptor_number * kDescriptorSize) +
2844 static int ToDetailsIndex(int descriptor_number) {
2845 return kFirstIndex +
2846 (descriptor_number * kDescriptorSize) +
2850 static int ToValueIndex(int descriptor_number) {
2851 return kFirstIndex +
2852 (descriptor_number * kDescriptorSize) +
2856 // Transfer a complete descriptor from the src descriptor array to this
2857 // descriptor array.
2858 void CopyFrom(int index, DescriptorArray* src, const WhitenessWitness&);
2860 inline void Set(int descriptor_number,
2862 const WhitenessWitness&);
2864 // Swap first and second descriptor.
2865 inline void SwapSortedKeys(int first, int second);
2867 DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
2871 enum SearchMode { ALL_ENTRIES, VALID_ENTRIES };
2873 template <SearchMode search_mode, typename T>
2874 inline int Search(T* array, Name* name, int valid_entries = 0,
2875 int* out_insertion_index = NULL);
2878 // HashTable is a subclass of FixedArray that implements a hash table
2879 // that uses open addressing and quadratic probing.
2881 // In order for the quadratic probing to work, elements that have not
2882 // yet been used and elements that have been deleted are
2883 // distinguished. Probing continues when deleted elements are
2884 // encountered and stops when unused elements are encountered.
2886 // - Elements with key == undefined have not been used yet.
2887 // - Elements with key == the_hole have been deleted.
2889 // The hash table class is parameterized with a Shape and a Key.
2890 // Shape must be a class with the following interface:
2891 // class ExampleShape {
2893 // // Tells whether key matches other.
2894 // static bool IsMatch(Key key, Object* other);
2895 // // Returns the hash value for key.
2896 // static uint32_t Hash(Key key);
2897 // // Returns the hash value for object.
2898 // static uint32_t HashForObject(Key key, Object* object);
2899 // // Convert key to an object.
2900 // static inline Handle<Object> AsHandle(Isolate* isolate, Key key);
2901 // // The prefix size indicates number of elements in the beginning
2902 // // of the backing storage.
2903 // static const int kPrefixSize = ..;
2904 // // The Element size indicates number of elements per entry.
2905 // static const int kEntrySize = ..;
2907 // The prefix size indicates an amount of memory in the
2908 // beginning of the backing storage that can be used for non-element
2909 // information by subclasses.
2911 template<typename Key>
2914 static const bool UsesSeed = false;
2915 static uint32_t Hash(Key key) { return 0; }
2916 static uint32_t SeededHash(Key key, uint32_t seed) {
2920 static uint32_t HashForObject(Key key, Object* object) { return 0; }
2921 static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
2923 return HashForObject(key, object);
2928 class HashTableBase : public FixedArray {
2930 // Returns the number of elements in the hash table.
2931 int NumberOfElements() {
2932 return Smi::cast(get(kNumberOfElementsIndex))->value();
2935 // Returns the number of deleted elements in the hash table.
2936 int NumberOfDeletedElements() {
2937 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
2940 // Returns the capacity of the hash table.
2942 return Smi::cast(get(kCapacityIndex))->value();
2945 // ElementAdded should be called whenever an element is added to a
2947 void ElementAdded() { SetNumberOfElements(NumberOfElements() + 1); }
2949 // ElementRemoved should be called whenever an element is removed from
2951 void ElementRemoved() {
2952 SetNumberOfElements(NumberOfElements() - 1);
2953 SetNumberOfDeletedElements(NumberOfDeletedElements() + 1);
2955 void ElementsRemoved(int n) {
2956 SetNumberOfElements(NumberOfElements() - n);
2957 SetNumberOfDeletedElements(NumberOfDeletedElements() + n);
2960 // Computes the required capacity for a table holding the given
2961 // number of elements. May be more than HashTable::kMaxCapacity.
2962 static inline int ComputeCapacity(int at_least_space_for);
2964 // Use a different heuristic to compute capacity when serializing.
2965 static inline int ComputeCapacityForSerialization(int at_least_space_for);
2967 // Tells whether k is a real key. The hole and undefined are not allowed
2968 // as keys and can be used to indicate missing or deleted elements.
2969 bool IsKey(Object* k) {
2970 return !k->IsTheHole() && !k->IsUndefined();
2973 // Compute the probe offset (quadratic probing).
2974 INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
2975 return (n + n * n) >> 1;
2978 static const int kNumberOfElementsIndex = 0;
2979 static const int kNumberOfDeletedElementsIndex = 1;
2980 static const int kCapacityIndex = 2;
2981 static const int kPrefixStartIndex = 3;
2983 // Constant used for denoting a absent entry.
2984 static const int kNotFound = -1;
2987 // Update the number of elements in the hash table.
2988 void SetNumberOfElements(int nof) {
2989 set(kNumberOfElementsIndex, Smi::FromInt(nof));
2992 // Update the number of deleted elements in the hash table.
2993 void SetNumberOfDeletedElements(int nod) {
2994 set(kNumberOfDeletedElementsIndex, Smi::FromInt(nod));
2997 // Returns probe entry.
2998 static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
2999 DCHECK(base::bits::IsPowerOfTwo32(size));
3000 return (hash + GetProbeOffset(number)) & (size - 1);
3003 inline static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
3004 return hash & (size - 1);
3007 inline static uint32_t NextProbe(
3008 uint32_t last, uint32_t number, uint32_t size) {
3009 return (last + number) & (size - 1);
3014 template <typename Derived, typename Shape, typename Key>
3015 class HashTable : public HashTableBase {
3018 inline uint32_t Hash(Key key) {
3019 if (Shape::UsesSeed) {
3020 return Shape::SeededHash(key, GetHeap()->HashSeed());
3022 return Shape::Hash(key);
3026 inline uint32_t HashForObject(Key key, Object* object) {
3027 if (Shape::UsesSeed) {
3028 return Shape::SeededHashForObject(key, GetHeap()->HashSeed(), object);
3030 return Shape::HashForObject(key, object);
3034 // Returns a new HashTable object.
3035 MUST_USE_RESULT static Handle<Derived> New(
3036 Isolate* isolate, int at_least_space_for,
3037 MinimumCapacity capacity_option = USE_DEFAULT_MINIMUM_CAPACITY,
3038 PretenureFlag pretenure = NOT_TENURED);
3040 DECLARE_CAST(HashTable)
3042 // Garbage collection support.
3043 void IteratePrefix(ObjectVisitor* visitor);
3044 void IterateElements(ObjectVisitor* visitor);
3046 // Find entry for key otherwise return kNotFound.
3047 inline int FindEntry(Key key);
3048 inline int FindEntry(Isolate* isolate, Key key, int32_t hash);
3049 int FindEntry(Isolate* isolate, Key key);
3051 // Rehashes the table in-place.
3052 void Rehash(Key key);
3054 // Returns the key at entry.
3055 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3057 static const int kElementsStartIndex = kPrefixStartIndex + Shape::kPrefixSize;
3058 static const int kEntrySize = Shape::kEntrySize;
3059 static const int kElementsStartOffset =
3060 kHeaderSize + kElementsStartIndex * kPointerSize;
3061 static const int kCapacityOffset =
3062 kHeaderSize + kCapacityIndex * kPointerSize;
3064 // Returns the index for an entry (of the key)
3065 static inline int EntryToIndex(int entry) {
3066 return (entry * kEntrySize) + kElementsStartIndex;
3070 friend class ObjectHashTable;
3072 // Find the entry at which to insert element with the given key that
3073 // has the given hash value.
3074 uint32_t FindInsertionEntry(uint32_t hash);
3076 // Attempt to shrink hash table after removal of key.
3077 MUST_USE_RESULT static Handle<Derived> Shrink(Handle<Derived> table, Key key);
3079 // Ensure enough space for n additional elements.
3080 MUST_USE_RESULT static Handle<Derived> EnsureCapacity(
3081 Handle<Derived> table,
3084 PretenureFlag pretenure = NOT_TENURED);
3086 // Sets the capacity of the hash table.
3087 void SetCapacity(int capacity) {
3088 // To scale a computed hash code to fit within the hash table, we
3089 // use bit-wise AND with a mask, so the capacity must be positive
3091 DCHECK(capacity > 0);
3092 DCHECK(capacity <= kMaxCapacity);
3093 set(kCapacityIndex, Smi::FromInt(capacity));
3096 // Maximal capacity of HashTable. Based on maximal length of underlying
3097 // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
3099 static const int kMaxCapacity =
3100 (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
3103 // Returns _expected_ if one of entries given by the first _probe_ probes is
3104 // equal to _expected_. Otherwise, returns the entry given by the probe
3106 uint32_t EntryForProbe(Key key, Object* k, int probe, uint32_t expected);
3108 void Swap(uint32_t entry1, uint32_t entry2, WriteBarrierMode mode);
3110 // Rehashes this hash-table into the new table.
3111 void Rehash(Handle<Derived> new_table, Key key);
3115 // HashTableKey is an abstract superclass for virtual key behavior.
3116 class HashTableKey {
3118 // Returns whether the other object matches this key.
3119 virtual bool IsMatch(Object* other) = 0;
3120 // Returns the hash value for this key.
3121 virtual uint32_t Hash() = 0;
3122 // Returns the hash value for object.
3123 virtual uint32_t HashForObject(Object* key) = 0;
3124 // Returns the key object for storing into the hash table.
3125 MUST_USE_RESULT virtual Handle<Object> AsHandle(Isolate* isolate) = 0;
3127 virtual ~HashTableKey() {}
3131 class StringTableShape : public BaseShape<HashTableKey*> {
3133 static inline bool IsMatch(HashTableKey* key, Object* value) {
3134 return key->IsMatch(value);
3137 static inline uint32_t Hash(HashTableKey* key) {
3141 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3142 return key->HashForObject(object);
3145 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3147 static const int kPrefixSize = 0;
3148 static const int kEntrySize = 1;
3151 class SeqOneByteString;
3155 // No special elements in the prefix and the element size is 1
3156 // because only the string itself (the key) needs to be stored.
3157 class StringTable: public HashTable<StringTable,
3161 // Find string in the string table. If it is not there yet, it is
3162 // added. The return value is the string found.
3163 static Handle<String> LookupString(Isolate* isolate, Handle<String> key);
3164 static Handle<String> LookupKey(Isolate* isolate, HashTableKey* key);
3165 static String* LookupKeyIfExists(Isolate* isolate, HashTableKey* key);
3167 // Tries to internalize given string and returns string handle on success
3168 // or an empty handle otherwise.
3169 MUST_USE_RESULT static MaybeHandle<String> InternalizeStringIfExists(
3171 Handle<String> string);
3173 // Looks up a string that is equal to the given string and returns
3174 // string handle if it is found, or an empty handle otherwise.
3175 MUST_USE_RESULT static MaybeHandle<String> LookupStringIfExists(
3177 Handle<String> str);
3178 MUST_USE_RESULT static MaybeHandle<String> LookupTwoCharsStringIfExists(
3183 static void EnsureCapacityForDeserialization(Isolate* isolate, int expected);
3185 DECLARE_CAST(StringTable)
3188 template <bool seq_one_byte>
3189 friend class JsonParser;
3191 DISALLOW_IMPLICIT_CONSTRUCTORS(StringTable);
3195 template <typename Derived, typename Shape, typename Key>
3196 class Dictionary: public HashTable<Derived, Shape, Key> {
3197 typedef HashTable<Derived, Shape, Key> DerivedHashTable;
3200 // Returns the value at entry.
3201 Object* ValueAt(int entry) {
3202 return this->get(Derived::EntryToIndex(entry) + 1);
3205 // Set the value for entry.
3206 void ValueAtPut(int entry, Object* value) {
3207 this->set(Derived::EntryToIndex(entry) + 1, value);
3210 // Returns the property details for the property at entry.
3211 PropertyDetails DetailsAt(int entry) {
3212 return Shape::DetailsAt(static_cast<Derived*>(this), entry);
3215 // Set the details for entry.
3216 void DetailsAtPut(int entry, PropertyDetails value) {
3217 Shape::DetailsAtPut(static_cast<Derived*>(this), entry, value);
3220 // Returns true if property at given entry is deleted.
3221 bool IsDeleted(int entry) {
3222 return Shape::IsDeleted(static_cast<Derived*>(this), entry);
3225 // Delete a property from the dictionary.
3226 static Handle<Object> DeleteProperty(Handle<Derived> dictionary, int entry);
3228 // Attempt to shrink the dictionary after deletion of key.
3229 MUST_USE_RESULT static inline Handle<Derived> Shrink(
3230 Handle<Derived> dictionary,
3232 return DerivedHashTable::Shrink(dictionary, key);
3236 // TODO(dcarney): templatize or move to SeededNumberDictionary
3237 void CopyValuesTo(FixedArray* elements);
3239 // Returns the number of elements in the dictionary filtering out properties
3240 // with the specified attributes.
3241 int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3243 // Returns the number of enumerable elements in the dictionary.
3244 int NumberOfEnumElements() {
3245 return NumberOfElementsFilterAttributes(
3246 static_cast<PropertyAttributes>(DONT_ENUM | SYMBOLIC));
3249 // Returns true if the dictionary contains any elements that are non-writable,
3250 // non-configurable, non-enumerable, or have getters/setters.
3251 bool HasComplexElements();
3253 enum SortMode { UNSORTED, SORTED };
3255 // Fill in details for properties into storage.
3256 // Returns the number of properties added.
3257 int 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 // [external_pointer]: For now, contains the offset between base_pointer and
4540 // the start of the data.
4541 DECL_ACCESSORS(external_pointer, void)
4543 // Dispatched behavior.
4544 inline void FixedTypedArrayBaseIterateBody(ObjectVisitor* v);
4546 template <typename StaticVisitor>
4547 inline void FixedTypedArrayBaseIterateBody();
4549 DECLARE_CAST(FixedTypedArrayBase)
4551 static const int kBasePointerOffset = FixedArrayBase::kHeaderSize;
4552 static const int kExternalPointerOffset = kBasePointerOffset + kPointerSize;
4553 static const int kHeaderSize =
4554 DOUBLE_POINTER_ALIGN(kExternalPointerOffset + kPointerSize);
4556 static const int kDataOffset = kHeaderSize;
4560 static inline int TypedArraySize(InstanceType type, int length);
4561 inline int TypedArraySize(InstanceType type);
4563 // Use with care: returns raw pointer into heap.
4564 inline void* DataPtr();
4566 inline int DataSize();
4569 static inline int ElementSize(InstanceType type);
4571 inline int DataSize(InstanceType type);
4573 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
4577 template <class Traits>
4578 class FixedTypedArray: public FixedTypedArrayBase {
4580 typedef typename Traits::ElementType ElementType;
4581 static const InstanceType kInstanceType = Traits::kInstanceType;
4583 DECLARE_CAST(FixedTypedArray<Traits>)
4585 inline ElementType get_scalar(int index);
4586 static inline Handle<Object> get(Handle<FixedTypedArray> array, int index);
4587 inline void set(int index, ElementType value);
4589 static inline ElementType from_int(int value);
4590 static inline ElementType from_double(double value);
4592 // This accessor applies the correct conversion from Smi, HeapNumber
4594 void SetValue(uint32_t index, Object* value);
4596 DECLARE_PRINTER(FixedTypedArray)
4597 DECLARE_VERIFIER(FixedTypedArray)
4600 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
4603 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size) \
4604 class Type##ArrayTraits { \
4605 public: /* NOLINT */ \
4606 typedef elementType ElementType; \
4607 static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE; \
4608 static const char* Designator() { return #type " array"; } \
4609 static inline Handle<Object> ToHandle(Isolate* isolate, \
4610 elementType scalar); \
4611 static inline elementType defaultValue(); \
4614 typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
4616 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
4618 #undef FIXED_TYPED_ARRAY_TRAITS
4621 // DeoptimizationInputData is a fixed array used to hold the deoptimization
4622 // data for code generated by the Hydrogen/Lithium compiler. It also
4623 // contains information about functions that were inlined. If N different
4624 // functions were inlined then first N elements of the literal array will
4625 // contain these functions.
4628 class DeoptimizationInputData: public FixedArray {
4630 // Layout description. Indices in the array.
4631 static const int kTranslationByteArrayIndex = 0;
4632 static const int kInlinedFunctionCountIndex = 1;
4633 static const int kLiteralArrayIndex = 2;
4634 static const int kOsrAstIdIndex = 3;
4635 static const int kOsrPcOffsetIndex = 4;
4636 static const int kOptimizationIdIndex = 5;
4637 static const int kSharedFunctionInfoIndex = 6;
4638 static const int kWeakCellCacheIndex = 7;
4639 static const int kFirstDeoptEntryIndex = 8;
4641 // Offsets of deopt entry elements relative to the start of the entry.
4642 static const int kAstIdRawOffset = 0;
4643 static const int kTranslationIndexOffset = 1;
4644 static const int kArgumentsStackHeightOffset = 2;
4645 static const int kPcOffset = 3;
4646 static const int kDeoptEntrySize = 4;
4648 // Simple element accessors.
4649 #define DEFINE_ELEMENT_ACCESSORS(name, type) \
4651 return type::cast(get(k##name##Index)); \
4653 void Set##name(type* value) { \
4654 set(k##name##Index, value); \
4657 DEFINE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
4658 DEFINE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
4659 DEFINE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
4660 DEFINE_ELEMENT_ACCESSORS(OsrAstId, Smi)
4661 DEFINE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
4662 DEFINE_ELEMENT_ACCESSORS(OptimizationId, Smi)
4663 DEFINE_ELEMENT_ACCESSORS(SharedFunctionInfo, Object)
4664 DEFINE_ELEMENT_ACCESSORS(WeakCellCache, Object)
4666 #undef DEFINE_ELEMENT_ACCESSORS
4668 // Accessors for elements of the ith deoptimization entry.
4669 #define DEFINE_ENTRY_ACCESSORS(name, type) \
4670 type* name(int i) { \
4671 return type::cast(get(IndexForEntry(i) + k##name##Offset)); \
4673 void Set##name(int i, type* value) { \
4674 set(IndexForEntry(i) + k##name##Offset, value); \
4677 DEFINE_ENTRY_ACCESSORS(AstIdRaw, Smi)
4678 DEFINE_ENTRY_ACCESSORS(TranslationIndex, Smi)
4679 DEFINE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
4680 DEFINE_ENTRY_ACCESSORS(Pc, Smi)
4682 #undef DEFINE_DEOPT_ENTRY_ACCESSORS
4684 BailoutId AstId(int i) {
4685 return BailoutId(AstIdRaw(i)->value());
4688 void SetAstId(int i, BailoutId value) {
4689 SetAstIdRaw(i, Smi::FromInt(value.ToInt()));
4693 return (length() - kFirstDeoptEntryIndex) / kDeoptEntrySize;
4696 // Allocates a DeoptimizationInputData.
4697 static Handle<DeoptimizationInputData> New(Isolate* isolate,
4698 int deopt_entry_count,
4699 PretenureFlag pretenure);
4701 DECLARE_CAST(DeoptimizationInputData)
4703 #ifdef ENABLE_DISASSEMBLER
4704 void DeoptimizationInputDataPrint(std::ostream& os); // NOLINT
4708 static int IndexForEntry(int i) {
4709 return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
4713 static int LengthFor(int entry_count) { return IndexForEntry(entry_count); }
4717 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
4718 // data for code generated by the full compiler.
4719 // The format of the these objects is
4720 // [i * 2]: Ast ID for ith deoptimization.
4721 // [i * 2 + 1]: PC and state of ith deoptimization
4722 class DeoptimizationOutputData: public FixedArray {
4724 int DeoptPoints() { return length() / 2; }
4726 BailoutId AstId(int index) {
4727 return BailoutId(Smi::cast(get(index * 2))->value());
4730 void SetAstId(int index, BailoutId id) {
4731 set(index * 2, Smi::FromInt(id.ToInt()));
4734 Smi* PcAndState(int index) { return Smi::cast(get(1 + index * 2)); }
4735 void SetPcAndState(int index, Smi* offset) { set(1 + index * 2, offset); }
4737 static int LengthOfFixedArray(int deopt_points) {
4738 return deopt_points * 2;
4741 // Allocates a DeoptimizationOutputData.
4742 static Handle<DeoptimizationOutputData> New(Isolate* isolate,
4743 int number_of_deopt_points,
4744 PretenureFlag pretenure);
4746 DECLARE_CAST(DeoptimizationOutputData)
4748 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4749 void DeoptimizationOutputDataPrint(std::ostream& os); // NOLINT
4754 // HandlerTable is a fixed array containing entries for exception handlers in
4755 // the code object it is associated with. The tables comes in two flavors:
4756 // 1) Based on ranges: Used for unoptimized code. Contains one entry per
4757 // exception handler and a range representing the try-block covered by that
4758 // handler. Layout looks as follows:
4759 // [ range-start , range-end , handler-offset , stack-depth ]
4760 // 2) Based on return addresses: Used for turbofanned code. Contains one entry
4761 // per call-site that could throw an exception. Layout looks as follows:
4762 // [ return-address-offset , handler-offset ]
4763 class HandlerTable : public FixedArray {
4765 // Conservative prediction whether a given handler will locally catch an
4766 // exception or cause a re-throw to outside the code boundary. Since this is
4767 // undecidable it is merely an approximation (e.g. useful for debugger).
4768 enum CatchPrediction { UNCAUGHT, CAUGHT };
4770 // Accessors for handler table based on ranges.
4771 void SetRangeStart(int index, int value) {
4772 set(index * kRangeEntrySize + kRangeStartIndex, Smi::FromInt(value));
4774 void SetRangeEnd(int index, int value) {
4775 set(index * kRangeEntrySize + kRangeEndIndex, Smi::FromInt(value));
4777 void SetRangeHandler(int index, int offset, CatchPrediction prediction) {
4778 int value = HandlerOffsetField::encode(offset) |
4779 HandlerPredictionField::encode(prediction);
4780 set(index * kRangeEntrySize + kRangeHandlerIndex, Smi::FromInt(value));
4782 void SetRangeDepth(int index, int value) {
4783 set(index * kRangeEntrySize + kRangeDepthIndex, Smi::FromInt(value));
4786 // Accessors for handler table based on return addresses.
4787 void SetReturnOffset(int index, int value) {
4788 set(index * kReturnEntrySize + kReturnOffsetIndex, Smi::FromInt(value));
4790 void SetReturnHandler(int index, int offset, CatchPrediction prediction) {
4791 int value = HandlerOffsetField::encode(offset) |
4792 HandlerPredictionField::encode(prediction);
4793 set(index * kReturnEntrySize + kReturnHandlerIndex, Smi::FromInt(value));
4796 // Lookup handler in a table based on ranges.
4797 int LookupRange(int pc_offset, int* stack_depth, CatchPrediction* prediction);
4799 // Lookup handler in a table based on return addresses.
4800 int LookupReturn(int pc_offset, CatchPrediction* prediction);
4802 // Returns the required length of the underlying fixed array.
4803 static int LengthForRange(int entries) { return entries * kRangeEntrySize; }
4804 static int LengthForReturn(int entries) { return entries * kReturnEntrySize; }
4806 DECLARE_CAST(HandlerTable)
4808 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4809 void HandlerTableRangePrint(std::ostream& os); // NOLINT
4810 void HandlerTableReturnPrint(std::ostream& os); // NOLINT
4814 // Layout description for handler table based on ranges.
4815 static const int kRangeStartIndex = 0;
4816 static const int kRangeEndIndex = 1;
4817 static const int kRangeHandlerIndex = 2;
4818 static const int kRangeDepthIndex = 3;
4819 static const int kRangeEntrySize = 4;
4821 // Layout description for handler table based on return addresses.
4822 static const int kReturnOffsetIndex = 0;
4823 static const int kReturnHandlerIndex = 1;
4824 static const int kReturnEntrySize = 2;
4826 // Encoding of the {handler} field.
4827 class HandlerPredictionField : public BitField<CatchPrediction, 0, 1> {};
4828 class HandlerOffsetField : public BitField<int, 1, 30> {};
4832 // Code describes objects with on-the-fly generated machine code.
4833 class Code: public HeapObject {
4835 // Opaque data type for encapsulating code flags like kind, inline
4836 // cache state, and arguments count.
4837 typedef uint32_t Flags;
4839 #define NON_IC_KIND_LIST(V) \
4841 V(OPTIMIZED_FUNCTION) \
4847 #define IC_KIND_LIST(V) \
4858 #define CODE_KIND_LIST(V) \
4859 NON_IC_KIND_LIST(V) \
4863 #define DEFINE_CODE_KIND_ENUM(name) name,
4864 CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
4865 #undef DEFINE_CODE_KIND_ENUM
4869 // No more than 16 kinds. The value is currently encoded in four bits in
4871 STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
4873 static const char* Kind2String(Kind kind);
4881 static const int kPrologueOffsetNotSet = -1;
4883 #ifdef ENABLE_DISASSEMBLER
4885 static const char* ICState2String(InlineCacheState state);
4886 static const char* StubType2String(StubType type);
4887 static void PrintExtraICState(std::ostream& os, // NOLINT
4888 Kind kind, ExtraICState extra);
4889 void Disassemble(const char* name, std::ostream& os); // NOLINT
4890 #endif // ENABLE_DISASSEMBLER
4892 // [instruction_size]: Size of the native instructions
4893 inline int instruction_size() const;
4894 inline void set_instruction_size(int value);
4896 // [relocation_info]: Code relocation information
4897 DECL_ACCESSORS(relocation_info, ByteArray)
4898 void InvalidateRelocation();
4899 void InvalidateEmbeddedObjects();
4901 // [handler_table]: Fixed array containing offsets of exception handlers.
4902 DECL_ACCESSORS(handler_table, FixedArray)
4904 // [deoptimization_data]: Array containing data for deopt.
4905 DECL_ACCESSORS(deoptimization_data, FixedArray)
4907 // [raw_type_feedback_info]: This field stores various things, depending on
4908 // the kind of the code object.
4909 // FUNCTION => type feedback information.
4910 // STUB and ICs => major/minor key as Smi.
4911 DECL_ACCESSORS(raw_type_feedback_info, Object)
4912 inline Object* type_feedback_info();
4913 inline void set_type_feedback_info(
4914 Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
4915 inline uint32_t stub_key();
4916 inline void set_stub_key(uint32_t key);
4918 // [next_code_link]: Link for lists of optimized or deoptimized code.
4919 // Note that storage for this field is overlapped with typefeedback_info.
4920 DECL_ACCESSORS(next_code_link, Object)
4922 // [gc_metadata]: Field used to hold GC related metadata. The contents of this
4923 // field does not have to be traced during garbage collection since
4924 // it is only used by the garbage collector itself.
4925 DECL_ACCESSORS(gc_metadata, Object)
4927 // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
4928 // at the moment when this object was created.
4929 inline void set_ic_age(int count);
4930 inline int ic_age() const;
4932 // [prologue_offset]: Offset of the function prologue, used for aging
4933 // FUNCTIONs and OPTIMIZED_FUNCTIONs.
4934 inline int prologue_offset() const;
4935 inline void set_prologue_offset(int offset);
4937 // [constant_pool offset]: Offset of the constant pool.
4938 // Valid for FLAG_enable_embedded_constant_pool only
4939 inline int constant_pool_offset() const;
4940 inline void set_constant_pool_offset(int offset);
4942 // Unchecked accessors to be used during GC.
4943 inline ByteArray* unchecked_relocation_info();
4945 inline int relocation_size();
4947 // [flags]: Various code flags.
4948 inline Flags flags();
4949 inline void set_flags(Flags flags);
4951 // [flags]: Access to specific code flags.
4953 inline InlineCacheState ic_state(); // Only valid for IC stubs.
4954 inline ExtraICState extra_ic_state(); // Only valid for IC stubs.
4956 inline StubType type(); // Only valid for monomorphic IC stubs.
4958 // Testers for IC stub kinds.
4959 inline bool is_inline_cache_stub();
4960 inline bool is_debug_stub();
4961 inline bool is_handler() { return kind() == HANDLER; }
4962 inline bool is_load_stub() { return kind() == LOAD_IC; }
4963 inline bool is_keyed_load_stub() { return kind() == KEYED_LOAD_IC; }
4964 inline bool is_store_stub() { return kind() == STORE_IC; }
4965 inline bool is_keyed_store_stub() { return kind() == KEYED_STORE_IC; }
4966 inline bool is_call_stub() { return kind() == CALL_IC; }
4967 inline bool is_binary_op_stub() { return kind() == BINARY_OP_IC; }
4968 inline bool is_compare_ic_stub() { return kind() == COMPARE_IC; }
4969 inline bool is_compare_nil_ic_stub() { return kind() == COMPARE_NIL_IC; }
4970 inline bool is_to_boolean_ic_stub() { return kind() == TO_BOOLEAN_IC; }
4971 inline bool is_keyed_stub();
4972 inline bool is_optimized_code() { return kind() == OPTIMIZED_FUNCTION; }
4973 inline bool embeds_maps_weakly() {
4975 return (k == LOAD_IC || k == STORE_IC || k == KEYED_LOAD_IC ||
4976 k == KEYED_STORE_IC || k == COMPARE_NIL_IC) &&
4977 ic_state() == MONOMORPHIC;
4980 inline bool IsCodeStubOrIC();
4982 inline void set_raw_kind_specific_flags1(int value);
4983 inline void set_raw_kind_specific_flags2(int value);
4985 // [is_crankshafted]: For kind STUB or ICs, tells whether or not a code
4986 // object was generated by either the hydrogen or the TurboFan optimizing
4987 // compiler (but it may not be an optimized function).
4988 inline bool is_crankshafted();
4989 inline bool is_hydrogen_stub(); // Crankshafted, but not a function.
4990 inline void set_is_crankshafted(bool value);
4992 // [is_turbofanned]: For kind STUB or OPTIMIZED_FUNCTION, tells whether the
4993 // code object was generated by the TurboFan optimizing compiler.
4994 inline bool is_turbofanned();
4995 inline void set_is_turbofanned(bool value);
4997 // [can_have_weak_objects]: For kind OPTIMIZED_FUNCTION, tells whether the
4998 // embedded objects in code should be treated weakly.
4999 inline bool can_have_weak_objects();
5000 inline void set_can_have_weak_objects(bool value);
5002 // [has_deoptimization_support]: For FUNCTION kind, tells if it has
5003 // deoptimization support.
5004 inline bool has_deoptimization_support();
5005 inline void set_has_deoptimization_support(bool value);
5007 // [has_debug_break_slots]: For FUNCTION kind, tells if it has
5008 // been compiled with debug break slots.
5009 inline bool has_debug_break_slots();
5010 inline void set_has_debug_break_slots(bool value);
5012 // [compiled_with_optimizing]: For FUNCTION kind, tells if it has
5013 // been compiled with IsOptimizing set to true.
5014 inline bool is_compiled_optimizable();
5015 inline void set_compiled_optimizable(bool value);
5017 // [has_reloc_info_for_serialization]: For FUNCTION kind, tells if its
5018 // reloc info includes runtime and external references to support
5019 // serialization/deserialization.
5020 inline bool has_reloc_info_for_serialization();
5021 inline void set_has_reloc_info_for_serialization(bool value);
5023 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
5024 // how long the function has been marked for OSR and therefore which
5025 // level of loop nesting we are willing to do on-stack replacement
5027 inline void set_allow_osr_at_loop_nesting_level(int level);
5028 inline int allow_osr_at_loop_nesting_level();
5030 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
5031 // the code object was seen on the stack with no IC patching going on.
5032 inline int profiler_ticks();
5033 inline void set_profiler_ticks(int ticks);
5035 // [builtin_index]: For BUILTIN kind, tells which builtin index it has.
5036 // For builtins, tells which builtin index it has.
5037 // Note that builtins can have a code kind other than BUILTIN, which means
5038 // that for arbitrary code objects, this index value may be random garbage.
5039 // To verify in that case, compare the code object to the indexed builtin.
5040 inline int builtin_index();
5041 inline void set_builtin_index(int id);
5043 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
5044 // reserved in the code prologue.
5045 inline unsigned stack_slots();
5046 inline void set_stack_slots(unsigned slots);
5048 // [safepoint_table_start]: For kind OPTIMIZED_FUNCTION, the offset in
5049 // the instruction stream where the safepoint table starts.
5050 inline unsigned safepoint_table_offset();
5051 inline void set_safepoint_table_offset(unsigned offset);
5053 // [back_edge_table_start]: For kind FUNCTION, the offset in the
5054 // instruction stream where the back edge table starts.
5055 inline unsigned back_edge_table_offset();
5056 inline void set_back_edge_table_offset(unsigned offset);
5058 inline bool back_edges_patched_for_osr();
5060 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
5061 inline uint16_t to_boolean_state();
5063 // [has_function_cache]: For kind STUB tells whether there is a function
5064 // cache is passed to the stub.
5065 inline bool has_function_cache();
5066 inline void set_has_function_cache(bool flag);
5069 // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
5070 // the code is going to be deoptimized because of dead embedded maps.
5071 inline bool marked_for_deoptimization();
5072 inline void set_marked_for_deoptimization(bool flag);
5074 // [constant_pool]: The constant pool for this function.
5075 inline Address constant_pool();
5077 // Get the safepoint entry for the given pc.
5078 SafepointEntry GetSafepointEntry(Address pc);
5080 // Find an object in a stub with a specified map
5081 Object* FindNthObject(int n, Map* match_map);
5083 // Find the first allocation site in an IC stub.
5084 AllocationSite* FindFirstAllocationSite();
5086 // Find the first map in an IC stub.
5087 Map* FindFirstMap();
5088 void FindAllMaps(MapHandleList* maps);
5090 // Find the first handler in an IC stub.
5091 Code* FindFirstHandler();
5093 // Find |length| handlers and put them into |code_list|. Returns false if not
5094 // enough handlers can be found.
5095 bool FindHandlers(CodeHandleList* code_list, int length = -1);
5097 // Find the handler for |map|.
5098 MaybeHandle<Code> FindHandlerForMap(Map* map);
5100 // Find the first name in an IC stub.
5101 Name* FindFirstName();
5103 class FindAndReplacePattern;
5104 // For each (map-to-find, object-to-replace) pair in the pattern, this
5105 // function replaces the corresponding placeholder in the code with the
5106 // object-to-replace. The function assumes that pairs in the pattern come in
5107 // the same order as the placeholders in the code.
5108 // If the placeholder is a weak cell, then the value of weak cell is matched
5109 // against the map-to-find.
5110 void FindAndReplace(const FindAndReplacePattern& pattern);
5112 // The entire code object including its header is copied verbatim to the
5113 // snapshot so that it can be written in one, fast, memcpy during
5114 // deserialization. The deserializer will overwrite some pointers, rather
5115 // like a runtime linker, but the random allocation addresses used in the
5116 // mksnapshot process would still be present in the unlinked snapshot data,
5117 // which would make snapshot production non-reproducible. This method wipes
5118 // out the to-be-overwritten header data for reproducible snapshots.
5119 inline void WipeOutHeader();
5121 // Flags operations.
5122 static inline Flags ComputeFlags(
5123 Kind kind, InlineCacheState ic_state = UNINITIALIZED,
5124 ExtraICState extra_ic_state = kNoExtraICState, StubType type = NORMAL,
5125 CacheHolderFlag holder = kCacheOnReceiver);
5127 static inline Flags ComputeMonomorphicFlags(
5128 Kind kind, ExtraICState extra_ic_state = kNoExtraICState,
5129 CacheHolderFlag holder = kCacheOnReceiver, StubType type = NORMAL);
5131 static inline Flags ComputeHandlerFlags(
5132 Kind handler_kind, StubType type = NORMAL,
5133 CacheHolderFlag holder = kCacheOnReceiver);
5135 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
5136 static inline StubType ExtractTypeFromFlags(Flags flags);
5137 static inline CacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
5138 static inline Kind ExtractKindFromFlags(Flags flags);
5139 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
5141 static inline Flags RemoveTypeFromFlags(Flags flags);
5142 static inline Flags RemoveTypeAndHolderFromFlags(Flags flags);
5144 // Convert a target address into a code object.
5145 static inline Code* GetCodeFromTargetAddress(Address address);
5147 // Convert an entry address into an object.
5148 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
5150 // Returns the address of the first instruction.
5151 inline byte* instruction_start();
5153 // Returns the address right after the last instruction.
5154 inline byte* instruction_end();
5156 // Returns the size of the instructions, padding, and relocation information.
5157 inline int body_size();
5159 // Returns the address of the first relocation info (read backwards!).
5160 inline byte* relocation_start();
5162 // Code entry point.
5163 inline byte* entry();
5165 // Returns true if pc is inside this object's instructions.
5166 inline bool contains(byte* pc);
5168 // Relocate the code by delta bytes. Called to signal that this code
5169 // object has been moved by delta bytes.
5170 void Relocate(intptr_t delta);
5172 // Migrate code described by desc.
5173 void CopyFrom(const CodeDesc& desc);
5175 // Returns the object size for a given body (used for allocation).
5176 static int SizeFor(int body_size) {
5177 DCHECK_SIZE_TAG_ALIGNED(body_size);
5178 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
5181 // Calculate the size of the code object to report for log events. This takes
5182 // the layout of the code object into account.
5183 int ExecutableSize() {
5184 // Check that the assumptions about the layout of the code object holds.
5185 DCHECK_EQ(static_cast<int>(instruction_start() - address()),
5187 return instruction_size() + Code::kHeaderSize;
5190 // Locating source position.
5191 int SourcePosition(Address pc);
5192 int SourceStatementPosition(Address pc);
5196 // Dispatched behavior.
5197 int CodeSize() { return SizeFor(body_size()); }
5198 inline void CodeIterateBody(ObjectVisitor* v);
5200 template<typename StaticVisitor>
5201 inline void CodeIterateBody(Heap* heap);
5203 DECLARE_PRINTER(Code)
5204 DECLARE_VERIFIER(Code)
5206 void ClearInlineCaches();
5207 void ClearInlineCaches(Kind kind);
5209 BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
5210 uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
5212 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
5214 kToBeExecutedOnceCodeAge = -3,
5215 kNotExecutedCodeAge = -2,
5216 kExecutedOnceCodeAge = -1,
5218 CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
5220 kFirstCodeAge = kToBeExecutedOnceCodeAge,
5221 kLastCodeAge = kAfterLastCodeAge - 1,
5222 kCodeAgeCount = kAfterLastCodeAge - kFirstCodeAge - 1,
5223 kIsOldCodeAge = kSexagenarianCodeAge,
5224 kPreAgedCodeAge = kIsOldCodeAge - 1
5226 #undef DECLARE_CODE_AGE_ENUM
5228 // Code aging. Indicates how many full GCs this code has survived without
5229 // being entered through the prologue. Used to determine when it is
5230 // relatively safe to flush this code object and replace it with the lazy
5231 // compilation stub.
5232 static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
5233 static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
5234 void MakeYoung(Isolate* isolate);
5235 void MarkToBeExecutedOnce(Isolate* isolate);
5236 void MakeOlder(MarkingParity);
5237 static bool IsYoungSequence(Isolate* isolate, byte* sequence);
5240 static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
5241 return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
5244 void PrintDeoptLocation(FILE* out, Address pc);
5245 bool CanDeoptAt(Address pc);
5248 void VerifyEmbeddedObjectsDependency();
5252 enum VerifyMode { kNoContextSpecificPointers, kNoContextRetainingPointers };
5253 void VerifyEmbeddedObjects(VerifyMode mode = kNoContextRetainingPointers);
5256 inline bool CanContainWeakObjects() {
5257 // is_turbofanned() implies !can_have_weak_objects().
5258 DCHECK(!is_optimized_code() || !is_turbofanned() ||
5259 !can_have_weak_objects());
5260 return is_optimized_code() && can_have_weak_objects();
5263 inline bool IsWeakObject(Object* object) {
5264 return (CanContainWeakObjects() && IsWeakObjectInOptimizedCode(object));
5267 static inline bool IsWeakObjectInOptimizedCode(Object* object);
5269 static Handle<WeakCell> WeakCellFor(Handle<Code> code);
5270 WeakCell* CachedWeakCell();
5272 // Max loop nesting marker used to postpose OSR. We don't take loop
5273 // nesting that is deeper than 5 levels into account.
5274 static const int kMaxLoopNestingMarker = 6;
5276 static const int kConstantPoolSize =
5277 FLAG_enable_embedded_constant_pool ? kIntSize : 0;
5279 // Layout description.
5280 static const int kRelocationInfoOffset = HeapObject::kHeaderSize;
5281 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
5282 static const int kDeoptimizationDataOffset =
5283 kHandlerTableOffset + kPointerSize;
5284 // For FUNCTION kind, we store the type feedback info here.
5285 static const int kTypeFeedbackInfoOffset =
5286 kDeoptimizationDataOffset + kPointerSize;
5287 static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
5288 static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
5289 static const int kInstructionSizeOffset = kGCMetadataOffset + kPointerSize;
5290 static const int kICAgeOffset = kInstructionSizeOffset + kIntSize;
5291 static const int kFlagsOffset = kICAgeOffset + kIntSize;
5292 static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
5293 static const int kKindSpecificFlags2Offset =
5294 kKindSpecificFlags1Offset + kIntSize;
5295 // Note: We might be able to squeeze this into the flags above.
5296 static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
5297 static const int kConstantPoolOffset = kPrologueOffset + kIntSize;
5298 static const int kHeaderPaddingStart =
5299 kConstantPoolOffset + kConstantPoolSize;
5301 // Add padding to align the instruction start following right after
5302 // the Code object header.
5303 static const int kHeaderSize =
5304 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
5306 // Byte offsets within kKindSpecificFlags1Offset.
5307 static const int kFullCodeFlags = kKindSpecificFlags1Offset;
5308 class FullCodeFlagsHasDeoptimizationSupportField:
5309 public BitField<bool, 0, 1> {}; // NOLINT
5310 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
5311 class FullCodeFlagsIsCompiledOptimizable: public BitField<bool, 2, 1> {};
5312 class FullCodeFlagsHasRelocInfoForSerialization
5313 : public BitField<bool, 3, 1> {};
5314 class ProfilerTicksField : public BitField<int, 4, 28> {};
5316 // Flags layout. BitField<type, shift, size>.
5317 class ICStateField : public BitField<InlineCacheState, 0, 4> {};
5318 class TypeField : public BitField<StubType, 4, 1> {};
5319 class CacheHolderField : public BitField<CacheHolderFlag, 5, 2> {};
5320 class KindField : public BitField<Kind, 7, 4> {};
5321 class ExtraICStateField: public BitField<ExtraICState, 11,
5322 PlatformSmiTagging::kSmiValueSize - 11 + 1> {}; // NOLINT
5324 // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
5325 static const int kStackSlotsFirstBit = 0;
5326 static const int kStackSlotsBitCount = 24;
5327 static const int kHasFunctionCacheBit =
5328 kStackSlotsFirstBit + kStackSlotsBitCount;
5329 static const int kMarkedForDeoptimizationBit = kHasFunctionCacheBit + 1;
5330 static const int kIsTurbofannedBit = kMarkedForDeoptimizationBit + 1;
5331 static const int kCanHaveWeakObjects = kIsTurbofannedBit + 1;
5333 STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
5334 STATIC_ASSERT(kCanHaveWeakObjects + 1 <= 32);
5336 class StackSlotsField: public BitField<int,
5337 kStackSlotsFirstBit, kStackSlotsBitCount> {}; // NOLINT
5338 class HasFunctionCacheField : public BitField<bool, kHasFunctionCacheBit, 1> {
5340 class MarkedForDeoptimizationField
5341 : public BitField<bool, kMarkedForDeoptimizationBit, 1> {}; // NOLINT
5342 class IsTurbofannedField : public BitField<bool, kIsTurbofannedBit, 1> {
5344 class CanHaveWeakObjectsField
5345 : public BitField<bool, kCanHaveWeakObjects, 1> {}; // NOLINT
5347 // KindSpecificFlags2 layout (ALL)
5348 static const int kIsCrankshaftedBit = 0;
5349 class IsCrankshaftedField: public BitField<bool,
5350 kIsCrankshaftedBit, 1> {}; // NOLINT
5352 // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
5353 static const int kSafepointTableOffsetFirstBit = kIsCrankshaftedBit + 1;
5354 static const int kSafepointTableOffsetBitCount = 24;
5356 STATIC_ASSERT(kSafepointTableOffsetFirstBit +
5357 kSafepointTableOffsetBitCount <= 32);
5358 STATIC_ASSERT(1 + kSafepointTableOffsetBitCount <= 32);
5360 class SafepointTableOffsetField: public BitField<int,
5361 kSafepointTableOffsetFirstBit,
5362 kSafepointTableOffsetBitCount> {}; // NOLINT
5364 // KindSpecificFlags2 layout (FUNCTION)
5365 class BackEdgeTableOffsetField: public BitField<int,
5366 kIsCrankshaftedBit + 1, 27> {}; // NOLINT
5367 class AllowOSRAtLoopNestingLevelField: public BitField<int,
5368 kIsCrankshaftedBit + 1 + 27, 4> {}; // NOLINT
5369 STATIC_ASSERT(AllowOSRAtLoopNestingLevelField::kMax >= kMaxLoopNestingMarker);
5371 static const int kArgumentsBits = 16;
5372 static const int kMaxArguments = (1 << kArgumentsBits) - 1;
5374 // This constant should be encodable in an ARM instruction.
5375 static const int kFlagsNotUsedInLookup =
5376 TypeField::kMask | CacheHolderField::kMask;
5379 friend class RelocIterator;
5380 friend class Deoptimizer; // For FindCodeAgeSequence.
5382 void ClearInlineCaches(Kind* kind);
5385 byte* FindCodeAgeSequence();
5386 static void GetCodeAgeAndParity(Code* code, Age* age,
5387 MarkingParity* parity);
5388 static void GetCodeAgeAndParity(Isolate* isolate, byte* sequence, Age* age,
5389 MarkingParity* parity);
5390 static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
5392 // Code aging -- platform-specific
5393 static void PatchPlatformCodeAge(Isolate* isolate,
5394 byte* sequence, Age age,
5395 MarkingParity parity);
5397 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5401 // This class describes the layout of dependent codes array of a map. The
5402 // array is partitioned into several groups of dependent codes. Each group
5403 // contains codes with the same dependency on the map. The array has the
5404 // following layout for n dependency groups:
5406 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5407 // | C1 | C2 | ... | Cn | group 1 | group 2 | ... | group n | undefined |
5408 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5410 // The first n elements are Smis, each of them specifies the number of codes
5411 // in the corresponding group. The subsequent elements contain grouped code
5412 // objects in weak cells. The suffix of the array can be filled with the
5413 // undefined value if the number of codes is less than the length of the
5414 // array. The order of the code objects within a group is not preserved.
5416 // All code indexes used in the class are counted starting from the first
5417 // code object of the first group. In other words, code index 0 corresponds
5418 // to array index n = kCodesStartIndex.
5420 class DependentCode: public FixedArray {
5422 enum DependencyGroup {
5423 // Group of code that weakly embed this map and depend on being
5424 // deoptimized when the map is garbage collected.
5426 // Group of code that embed a transition to this map, and depend on being
5427 // deoptimized when the transition is replaced by a new version.
5429 // Group of code that omit run-time prototype checks for prototypes
5430 // described by this map. The group is deoptimized whenever an object
5431 // described by this map changes shape (and transitions to a new map),
5432 // possibly invalidating the assumptions embedded in the code.
5433 kPrototypeCheckGroup,
5434 // Group of code that depends on global property values in property cells
5435 // not being changed.
5436 kPropertyCellChangedGroup,
5437 // Group of code that omit run-time type checks for the field(s) introduced
5440 // Group of code that omit run-time type checks for initial maps of
5442 kInitialMapChangedGroup,
5443 // Group of code that depends on tenuring information in AllocationSites
5444 // not being changed.
5445 kAllocationSiteTenuringChangedGroup,
5446 // Group of code that depends on element transition information in
5447 // AllocationSites not being changed.
5448 kAllocationSiteTransitionChangedGroup
5451 static const int kGroupCount = kAllocationSiteTransitionChangedGroup + 1;
5453 // Array for holding the index of the first code object of each group.
5454 // The last element stores the total number of code objects.
5455 class GroupStartIndexes {
5457 explicit GroupStartIndexes(DependentCode* entries);
5458 void Recompute(DependentCode* entries);
5459 int at(int i) { return start_indexes_[i]; }
5460 int number_of_entries() { return start_indexes_[kGroupCount]; }
5462 int start_indexes_[kGroupCount + 1];
5465 bool Contains(DependencyGroup group, WeakCell* code_cell);
5467 static Handle<DependentCode> InsertCompilationDependencies(
5468 Handle<DependentCode> entries, DependencyGroup group,
5469 Handle<Foreign> info);
5471 static Handle<DependentCode> InsertWeakCode(Handle<DependentCode> entries,
5472 DependencyGroup group,
5473 Handle<WeakCell> code_cell);
5475 void UpdateToFinishedCode(DependencyGroup group, Foreign* info,
5476 WeakCell* code_cell);
5478 void RemoveCompilationDependencies(DependentCode::DependencyGroup group,
5481 void DeoptimizeDependentCodeGroup(Isolate* isolate,
5482 DependentCode::DependencyGroup group);
5484 bool MarkCodeForDeoptimization(Isolate* isolate,
5485 DependentCode::DependencyGroup group);
5487 // The following low-level accessors should only be used by this class
5488 // and the mark compact collector.
5489 inline int number_of_entries(DependencyGroup group);
5490 inline void set_number_of_entries(DependencyGroup group, int value);
5491 inline Object* object_at(int i);
5492 inline void set_object_at(int i, Object* object);
5493 inline void clear_at(int i);
5494 inline void copy(int from, int to);
5495 DECLARE_CAST(DependentCode)
5497 static const char* DependencyGroupName(DependencyGroup group);
5498 static void SetMarkedForDeoptimization(Code* code, DependencyGroup group);
5501 static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5502 DependencyGroup group,
5503 Handle<Object> object);
5504 static Handle<DependentCode> EnsureSpace(Handle<DependentCode> entries);
5505 // Make a room at the end of the given group by moving out the first
5506 // code objects of the subsequent groups.
5507 inline void ExtendGroup(DependencyGroup group);
5508 // Compact by removing cleared weak cells and return true if there was
5509 // any cleared weak cell.
5511 static int Grow(int number_of_entries) {
5512 if (number_of_entries < 5) return number_of_entries + 1;
5513 return number_of_entries * 5 / 4;
5515 static const int kCodesStartIndex = kGroupCount;
5519 class PrototypeInfo;
5522 // All heap objects have a Map that describes their structure.
5523 // A Map contains information about:
5524 // - Size information about the object
5525 // - How to iterate over an object (for garbage collection)
5526 class Map: public HeapObject {
5529 // Size in bytes or kVariableSizeSentinel if instances do not have
5531 inline int instance_size();
5532 inline void set_instance_size(int value);
5534 // Only to clear an unused byte, remove once byte is used.
5535 inline void clear_unused();
5537 // Count of properties allocated in the object.
5538 inline int inobject_properties();
5539 inline void set_inobject_properties(int value);
5542 inline InstanceType instance_type();
5543 inline void set_instance_type(InstanceType value);
5545 // Tells how many unused property fields are available in the
5546 // instance (only used for JSObject in fast mode).
5547 inline int unused_property_fields();
5548 inline void set_unused_property_fields(int value);
5551 inline byte bit_field() const;
5552 inline void set_bit_field(byte value);
5555 inline byte bit_field2() const;
5556 inline void set_bit_field2(byte value);
5559 inline uint32_t bit_field3() const;
5560 inline void set_bit_field3(uint32_t bits);
5562 class EnumLengthBits: public BitField<int,
5563 0, kDescriptorIndexBitCount> {}; // NOLINT
5564 class NumberOfOwnDescriptorsBits: public BitField<int,
5565 kDescriptorIndexBitCount, kDescriptorIndexBitCount> {}; // NOLINT
5566 STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
5567 class DictionaryMap : public BitField<bool, 20, 1> {};
5568 class OwnsDescriptors : public BitField<bool, 21, 1> {};
5569 class HasInstanceCallHandler : public BitField<bool, 22, 1> {};
5570 class Deprecated : public BitField<bool, 23, 1> {};
5571 class IsUnstable : public BitField<bool, 24, 1> {};
5572 class IsMigrationTarget : public BitField<bool, 25, 1> {};
5573 class IsStrong : public BitField<bool, 26, 1> {};
5576 // Keep this bit field at the very end for better code in
5577 // Builtins::kJSConstructStubGeneric stub.
5578 // This counter is used for in-object slack tracking and for map aging.
5579 // The in-object slack tracking is considered enabled when the counter is
5580 // in the range [kSlackTrackingCounterStart, kSlackTrackingCounterEnd].
5581 class Counter : public BitField<int, 28, 4> {};
5582 static const int kSlackTrackingCounterStart = 14;
5583 static const int kSlackTrackingCounterEnd = 8;
5584 static const int kRetainingCounterStart = kSlackTrackingCounterEnd - 1;
5585 static const int kRetainingCounterEnd = 0;
5587 // Tells whether the object in the prototype property will be used
5588 // for instances created from this function. If the prototype
5589 // property is set to a value that is not a JSObject, the prototype
5590 // property will not be used to create instances of the function.
5591 // See ECMA-262, 13.2.2.
5592 inline void set_non_instance_prototype(bool value);
5593 inline bool has_non_instance_prototype();
5595 // Tells whether function has special prototype property. If not, prototype
5596 // property will not be created when accessed (will return undefined),
5597 // and construction from this function will not be allowed.
5598 inline void set_function_with_prototype(bool value);
5599 inline bool function_with_prototype();
5601 // Tells whether the instance with this map should be ignored by the
5602 // Object.getPrototypeOf() function and the __proto__ accessor.
5603 inline void set_is_hidden_prototype() {
5604 set_bit_field(bit_field() | (1 << kIsHiddenPrototype));
5607 inline bool is_hidden_prototype() {
5608 return ((1 << kIsHiddenPrototype) & bit_field()) != 0;
5611 // Records and queries whether the instance has a named interceptor.
5612 inline void set_has_named_interceptor() {
5613 set_bit_field(bit_field() | (1 << kHasNamedInterceptor));
5616 inline bool has_named_interceptor() {
5617 return ((1 << kHasNamedInterceptor) & bit_field()) != 0;
5620 // Records and queries whether the instance has an indexed interceptor.
5621 inline void set_has_indexed_interceptor() {
5622 set_bit_field(bit_field() | (1 << kHasIndexedInterceptor));
5625 inline bool has_indexed_interceptor() {
5626 return ((1 << kHasIndexedInterceptor) & bit_field()) != 0;
5629 // Tells whether the instance is undetectable.
5630 // An undetectable object is a special class of JSObject: 'typeof' operator
5631 // returns undefined, ToBoolean returns false. Otherwise it behaves like
5632 // a normal JS object. It is useful for implementing undetectable
5633 // document.all in Firefox & Safari.
5634 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
5635 inline void set_is_undetectable() {
5636 set_bit_field(bit_field() | (1 << kIsUndetectable));
5639 inline bool is_undetectable() {
5640 return ((1 << kIsUndetectable) & bit_field()) != 0;
5643 // Tells whether the instance has a call-as-function handler.
5644 inline void set_is_observed() {
5645 set_bit_field(bit_field() | (1 << kIsObserved));
5648 inline bool is_observed() {
5649 return ((1 << kIsObserved) & bit_field()) != 0;
5652 inline void set_is_strong();
5653 inline bool is_strong();
5654 inline void set_is_extensible(bool value);
5655 inline bool is_extensible();
5656 inline void set_is_prototype_map(bool value);
5657 inline bool is_prototype_map() const;
5659 inline void set_elements_kind(ElementsKind elements_kind) {
5660 DCHECK(static_cast<int>(elements_kind) < kElementsKindCount);
5661 DCHECK(kElementsKindCount <= (1 << Map::ElementsKindBits::kSize));
5662 set_bit_field2(Map::ElementsKindBits::update(bit_field2(), elements_kind));
5663 DCHECK(this->elements_kind() == elements_kind);
5666 inline ElementsKind elements_kind() {
5667 return Map::ElementsKindBits::decode(bit_field2());
5670 // Tells whether the instance has fast elements that are only Smis.
5671 inline bool has_fast_smi_elements() {
5672 return IsFastSmiElementsKind(elements_kind());
5675 // Tells whether the instance has fast elements.
5676 inline bool has_fast_object_elements() {
5677 return IsFastObjectElementsKind(elements_kind());
5680 inline bool has_fast_smi_or_object_elements() {
5681 return IsFastSmiOrObjectElementsKind(elements_kind());
5684 inline bool has_fast_double_elements() {
5685 return IsFastDoubleElementsKind(elements_kind());
5688 inline bool has_fast_elements() {
5689 return IsFastElementsKind(elements_kind());
5692 inline bool has_sloppy_arguments_elements() {
5693 return IsSloppyArgumentsElements(elements_kind());
5696 inline bool has_external_array_elements() {
5697 return IsExternalArrayElementsKind(elements_kind());
5700 inline bool has_fixed_typed_array_elements() {
5701 return IsFixedTypedArrayElementsKind(elements_kind());
5704 inline bool has_dictionary_elements() {
5705 return IsDictionaryElementsKind(elements_kind());
5708 static bool IsValidElementsTransition(ElementsKind from_kind,
5709 ElementsKind to_kind);
5711 // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
5712 // map with DICTIONARY_ELEMENTS was found in the prototype chain.
5713 bool DictionaryElementsInPrototypeChainOnly();
5715 inline Map* ElementsTransitionMap();
5717 inline FixedArrayBase* GetInitialElements();
5719 // [raw_transitions]: Provides access to the transitions storage field.
5720 // Don't call set_raw_transitions() directly to overwrite transitions, use
5721 // the TransitionArray::ReplaceTransitions() wrapper instead!
5722 DECL_ACCESSORS(raw_transitions, Object)
5723 // [prototype_info]: Per-prototype metadata. Aliased with transitions
5724 // (which prototype maps don't have).
5725 DECL_ACCESSORS(prototype_info, Object)
5726 // PrototypeInfo is created lazily using this helper (which installs it on
5727 // the given prototype's map).
5728 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5729 Handle<JSObject> prototype, Isolate* isolate);
5731 // [prototype chain validity cell]: Associated with a prototype object,
5732 // stored in that object's map's PrototypeInfo, indicates that prototype
5733 // chains through this object are currently valid. The cell will be
5734 // invalidated and replaced when the prototype chain changes.
5735 static Handle<Cell> GetOrCreatePrototypeChainValidityCell(Handle<Map> map,
5737 static const int kPrototypeChainValid = 0;
5738 static const int kPrototypeChainInvalid = 1;
5741 Map* FindFieldOwner(int descriptor);
5743 inline int GetInObjectPropertyOffset(int index);
5745 int NumberOfFields();
5747 // TODO(ishell): candidate with JSObject::MigrateToMap().
5748 bool InstancesNeedRewriting(Map* target, int target_number_of_fields,
5749 int target_inobject, int target_unused,
5750 int* old_number_of_fields);
5751 // TODO(ishell): moveit!
5752 static Handle<Map> GeneralizeAllFieldRepresentations(Handle<Map> map);
5753 MUST_USE_RESULT static Handle<HeapType> GeneralizeFieldType(
5754 Handle<HeapType> type1,
5755 Handle<HeapType> type2,
5757 static void GeneralizeFieldType(Handle<Map> map, int modify_index,
5758 Representation new_representation,
5759 Handle<HeapType> new_field_type);
5760 static Handle<Map> ReconfigureProperty(Handle<Map> map, int modify_index,
5761 PropertyKind new_kind,
5762 PropertyAttributes new_attributes,
5763 Representation new_representation,
5764 Handle<HeapType> new_field_type,
5765 StoreMode store_mode);
5766 static Handle<Map> CopyGeneralizeAllRepresentations(
5767 Handle<Map> map, int modify_index, StoreMode store_mode,
5768 PropertyKind kind, PropertyAttributes attributes, const char* reason);
5770 static Handle<Map> PrepareForDataProperty(Handle<Map> old_map,
5771 int descriptor_number,
5772 Handle<Object> value);
5774 static Handle<Map> Normalize(Handle<Map> map, PropertyNormalizationMode mode,
5775 const char* reason);
5777 // Returns the constructor name (the name (possibly, inferred name) of the
5778 // function that was used to instantiate the object).
5779 String* constructor_name();
5781 // Tells whether the map is used for JSObjects in dictionary mode (ie
5782 // normalized objects, ie objects for which HasFastProperties returns false).
5783 // A map can never be used for both dictionary mode and fast mode JSObjects.
5784 // False by default and for HeapObjects that are not JSObjects.
5785 inline void set_dictionary_map(bool value);
5786 inline bool is_dictionary_map();
5788 // Tells whether the instance needs security checks when accessing its
5790 inline void set_is_access_check_needed(bool access_check_needed);
5791 inline bool is_access_check_needed();
5793 // Returns true if map has a non-empty stub code cache.
5794 inline bool has_code_cache();
5796 // [prototype]: implicit prototype object.
5797 DECL_ACCESSORS(prototype, Object)
5798 // TODO(jkummerow): make set_prototype private.
5799 static void SetPrototype(
5800 Handle<Map> map, Handle<Object> prototype,
5801 PrototypeOptimizationMode proto_mode = FAST_PROTOTYPE);
5803 // [constructor]: points back to the function responsible for this map.
5804 // The field overlaps with the back pointer. All maps in a transition tree
5805 // have the same constructor, so maps with back pointers can walk the
5806 // back pointer chain until they find the map holding their constructor.
5807 DECL_ACCESSORS(constructor_or_backpointer, Object)
5808 inline Object* GetConstructor() const;
5809 inline void SetConstructor(Object* constructor,
5810 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5811 // [back pointer]: points back to the parent map from which a transition
5812 // leads to this map. The field overlaps with the constructor (see above).
5813 inline Object* GetBackPointer();
5814 inline void SetBackPointer(Object* value,
5815 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5817 // [instance descriptors]: describes the object.
5818 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
5820 // [layout descriptor]: describes the object layout.
5821 DECL_ACCESSORS(layout_descriptor, LayoutDescriptor)
5822 // |layout descriptor| accessor which can be used from GC.
5823 inline LayoutDescriptor* layout_descriptor_gc_safe();
5824 inline bool HasFastPointerLayout() const;
5826 // |layout descriptor| accessor that is safe to call even when
5827 // FLAG_unbox_double_fields is disabled (in this case Map does not contain
5828 // |layout_descriptor| field at all).
5829 inline LayoutDescriptor* GetLayoutDescriptor();
5831 inline void UpdateDescriptors(DescriptorArray* descriptors,
5832 LayoutDescriptor* layout_descriptor);
5833 inline void InitializeDescriptors(DescriptorArray* descriptors,
5834 LayoutDescriptor* layout_descriptor);
5836 // [stub cache]: contains stubs compiled for this map.
5837 DECL_ACCESSORS(code_cache, Object)
5839 // [dependent code]: list of optimized codes that weakly embed this map.
5840 DECL_ACCESSORS(dependent_code, DependentCode)
5842 // [weak cell cache]: cache that stores a weak cell pointing to this map.
5843 DECL_ACCESSORS(weak_cell_cache, Object)
5845 inline PropertyDetails GetLastDescriptorDetails();
5848 int number_of_own_descriptors = NumberOfOwnDescriptors();
5849 DCHECK(number_of_own_descriptors > 0);
5850 return number_of_own_descriptors - 1;
5853 int NumberOfOwnDescriptors() {
5854 return NumberOfOwnDescriptorsBits::decode(bit_field3());
5857 void SetNumberOfOwnDescriptors(int number) {
5858 DCHECK(number <= instance_descriptors()->number_of_descriptors());
5859 set_bit_field3(NumberOfOwnDescriptorsBits::update(bit_field3(), number));
5862 inline Cell* RetrieveDescriptorsPointer();
5865 return EnumLengthBits::decode(bit_field3());
5868 void SetEnumLength(int length) {
5869 if (length != kInvalidEnumCacheSentinel) {
5870 DCHECK(length >= 0);
5871 DCHECK(length == 0 || instance_descriptors()->HasEnumCache());
5872 DCHECK(length <= NumberOfOwnDescriptors());
5874 set_bit_field3(EnumLengthBits::update(bit_field3(), length));
5877 inline bool owns_descriptors();
5878 inline void set_owns_descriptors(bool owns_descriptors);
5879 inline bool has_instance_call_handler();
5880 inline void set_has_instance_call_handler();
5881 inline void mark_unstable();
5882 inline bool is_stable();
5883 inline void set_migration_target(bool value);
5884 inline bool is_migration_target();
5885 inline void set_counter(int value);
5886 inline int counter();
5887 inline void deprecate();
5888 inline bool is_deprecated();
5889 inline bool CanBeDeprecated();
5890 // Returns a non-deprecated version of the input. If the input was not
5891 // deprecated, it is directly returned. Otherwise, the non-deprecated version
5892 // is found by re-transitioning from the root of the transition tree using the
5893 // descriptor array of the map. Returns MaybeHandle<Map>() if no updated map
5895 static MaybeHandle<Map> TryUpdate(Handle<Map> map) WARN_UNUSED_RESULT;
5897 // Returns a non-deprecated version of the input. This method may deprecate
5898 // existing maps along the way if encodings conflict. Not for use while
5899 // gathering type feedback. Use TryUpdate in those cases instead.
5900 static Handle<Map> Update(Handle<Map> map);
5902 static Handle<Map> CopyDropDescriptors(Handle<Map> map);
5903 static Handle<Map> CopyInsertDescriptor(Handle<Map> map,
5904 Descriptor* descriptor,
5905 TransitionFlag flag);
5907 MUST_USE_RESULT static MaybeHandle<Map> CopyWithField(
5910 Handle<HeapType> type,
5911 PropertyAttributes attributes,
5912 Representation representation,
5913 TransitionFlag flag);
5915 MUST_USE_RESULT static MaybeHandle<Map> CopyWithConstant(
5918 Handle<Object> constant,
5919 PropertyAttributes attributes,
5920 TransitionFlag flag);
5922 // Returns a new map with all transitions dropped from the given map and
5923 // the ElementsKind set.
5924 static Handle<Map> TransitionElementsTo(Handle<Map> map,
5925 ElementsKind to_kind);
5927 static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
5929 static Handle<Map> CopyAsElementsKind(Handle<Map> map,
5931 TransitionFlag flag);
5933 static Handle<Map> CopyForObserved(Handle<Map> map);
5935 static Handle<Map> CopyForPreventExtensions(Handle<Map> map,
5936 PropertyAttributes attrs_to_add,
5937 Handle<Symbol> transition_marker,
5938 const char* reason);
5940 static Handle<Map> FixProxy(Handle<Map> map, InstanceType type, int size);
5943 // Maximal number of fast properties. Used to restrict the number of map
5944 // transitions to avoid an explosion in the number of maps for objects used as
5946 inline bool TooManyFastProperties(StoreFromKeyed store_mode);
5947 static Handle<Map> TransitionToDataProperty(Handle<Map> map,
5949 Handle<Object> value,
5950 PropertyAttributes attributes,
5951 StoreFromKeyed store_mode);
5952 static Handle<Map> TransitionToAccessorProperty(
5953 Handle<Map> map, Handle<Name> name, AccessorComponent component,
5954 Handle<Object> accessor, PropertyAttributes attributes);
5955 static Handle<Map> ReconfigureExistingProperty(Handle<Map> map,
5958 PropertyAttributes attributes);
5960 inline void AppendDescriptor(Descriptor* desc);
5962 // Returns a copy of the map, prepared for inserting into the transition
5963 // tree (if the |map| owns descriptors then the new one will share
5964 // descriptors with |map|).
5965 static Handle<Map> CopyForTransition(Handle<Map> map, const char* reason);
5967 // Returns a copy of the map, with all transitions dropped from the
5968 // instance descriptors.
5969 static Handle<Map> Copy(Handle<Map> map, const char* reason);
5970 static Handle<Map> Create(Isolate* isolate, int inobject_properties);
5972 // Returns the next free property index (only valid for FAST MODE).
5973 int NextFreePropertyIndex();
5975 // Returns the number of properties described in instance_descriptors
5976 // filtering out properties with the specified attributes.
5977 int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
5978 PropertyAttributes filter = NONE);
5982 // Code cache operations.
5984 // Clears the code cache.
5985 inline void ClearCodeCache(Heap* heap);
5987 // Update code cache.
5988 static void UpdateCodeCache(Handle<Map> map,
5992 // Extend the descriptor array of the map with the list of descriptors.
5993 // In case of duplicates, the latest descriptor is used.
5994 static void AppendCallbackDescriptors(Handle<Map> map,
5995 Handle<Object> descriptors);
5997 static inline int SlackForArraySize(int old_size, int size_limit);
5999 static void EnsureDescriptorSlack(Handle<Map> map, int slack);
6001 // Returns the found code or undefined if absent.
6002 Object* FindInCodeCache(Name* name, Code::Flags flags);
6004 // Returns the non-negative index of the code object if it is in the
6005 // cache and -1 otherwise.
6006 int IndexInCodeCache(Object* name, Code* code);
6008 // Removes a code object from the code cache at the given index.
6009 void RemoveFromCodeCache(Name* name, Code* code, int index);
6011 // Computes a hash value for this map, to be used in HashTables and such.
6014 // Returns the map that this map transitions to if its elements_kind
6015 // is changed to |elements_kind|, or NULL if no such map is cached yet.
6016 // |safe_to_add_transitions| is set to false if adding transitions is not
6018 Map* LookupElementsTransitionMap(ElementsKind elements_kind);
6020 // Returns the transitioned map for this map with the most generic
6021 // elements_kind that's found in |candidates|, or null handle if no match is
6023 static Handle<Map> FindTransitionedMap(Handle<Map> map,
6024 MapHandleList* candidates);
6026 bool CanTransition() {
6027 // Only JSObject and subtypes have map transitions and back pointers.
6028 STATIC_ASSERT(LAST_TYPE == LAST_JS_OBJECT_TYPE);
6029 return instance_type() >= FIRST_JS_OBJECT_TYPE;
6032 bool IsJSObjectMap() {
6033 return instance_type() >= FIRST_JS_OBJECT_TYPE;
6035 bool IsJSArrayMap() { return instance_type() == JS_ARRAY_TYPE; }
6036 bool IsStringMap() { return instance_type() < FIRST_NONSTRING_TYPE; }
6037 bool IsJSProxyMap() {
6038 InstanceType type = instance_type();
6039 return FIRST_JS_PROXY_TYPE <= type && type <= LAST_JS_PROXY_TYPE;
6041 bool IsJSGlobalProxyMap() {
6042 return instance_type() == JS_GLOBAL_PROXY_TYPE;
6044 bool IsJSGlobalObjectMap() {
6045 return instance_type() == JS_GLOBAL_OBJECT_TYPE;
6047 bool IsGlobalObjectMap() {
6048 const InstanceType type = instance_type();
6049 return type == JS_GLOBAL_OBJECT_TYPE || type == JS_BUILTINS_OBJECT_TYPE;
6052 inline bool CanOmitMapChecks();
6054 static void AddDependentCode(Handle<Map> map,
6055 DependentCode::DependencyGroup group,
6058 bool IsMapInArrayPrototypeChain();
6060 static Handle<WeakCell> WeakCellForMap(Handle<Map> map);
6062 // Dispatched behavior.
6063 DECLARE_PRINTER(Map)
6064 DECLARE_VERIFIER(Map)
6067 void DictionaryMapVerify();
6068 void VerifyOmittedMapChecks();
6071 inline int visitor_id();
6072 inline void set_visitor_id(int visitor_id);
6074 static Handle<Map> TransitionToPrototype(Handle<Map> map,
6075 Handle<Object> prototype,
6076 PrototypeOptimizationMode mode);
6078 static const int kMaxPreAllocatedPropertyFields = 255;
6080 // Layout description.
6081 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
6082 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
6083 static const int kBitField3Offset = kInstanceAttributesOffset + kIntSize;
6084 static const int kPrototypeOffset = kBitField3Offset + kPointerSize;
6085 static const int kConstructorOrBackPointerOffset =
6086 kPrototypeOffset + kPointerSize;
6087 // When there is only one transition, it is stored directly in this field;
6088 // otherwise a transition array is used.
6089 // For prototype maps, this slot is used to store this map's PrototypeInfo
6091 static const int kTransitionsOrPrototypeInfoOffset =
6092 kConstructorOrBackPointerOffset + kPointerSize;
6093 static const int kDescriptorsOffset =
6094 kTransitionsOrPrototypeInfoOffset + kPointerSize;
6095 #if V8_DOUBLE_FIELDS_UNBOXING
6096 static const int kLayoutDecriptorOffset = kDescriptorsOffset + kPointerSize;
6097 static const int kCodeCacheOffset = kLayoutDecriptorOffset + kPointerSize;
6099 static const int kLayoutDecriptorOffset = 1; // Must not be ever accessed.
6100 static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
6102 static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
6103 static const int kWeakCellCacheOffset = kDependentCodeOffset + kPointerSize;
6104 static const int kSize = kWeakCellCacheOffset + kPointerSize;
6106 // Layout of pointer fields. Heap iteration code relies on them
6107 // being continuously allocated.
6108 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
6109 static const int kPointerFieldsEndOffset = kSize;
6111 // Byte offsets within kInstanceSizesOffset.
6112 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
6113 static const int kInObjectPropertiesByte = 1;
6114 static const int kInObjectPropertiesOffset =
6115 kInstanceSizesOffset + kInObjectPropertiesByte;
6116 // Note there is one byte available for use here.
6117 static const int kUnusedByte = 2;
6118 static const int kUnusedOffset = kInstanceSizesOffset + kUnusedByte;
6119 static const int kVisitorIdByte = 3;
6120 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
6122 // Byte offsets within kInstanceAttributesOffset attributes.
6123 #if V8_TARGET_LITTLE_ENDIAN
6124 // Order instance type and bit field together such that they can be loaded
6125 // together as a 16-bit word with instance type in the lower 8 bits regardless
6126 // of endianess. Also provide endian-independent offset to that 16-bit word.
6127 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
6128 static const int kBitFieldOffset = kInstanceAttributesOffset + 1;
6130 static const int kBitFieldOffset = kInstanceAttributesOffset + 0;
6131 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 1;
6133 static const int kInstanceTypeAndBitFieldOffset =
6134 kInstanceAttributesOffset + 0;
6135 static const int kBitField2Offset = kInstanceAttributesOffset + 2;
6136 static const int kUnusedPropertyFieldsByte = 3;
6137 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 3;
6139 STATIC_ASSERT(kInstanceTypeAndBitFieldOffset ==
6140 Internals::kMapInstanceTypeAndBitFieldOffset);
6142 // Bit positions for bit field.
6143 static const int kHasNonInstancePrototype = 0;
6144 static const int kIsHiddenPrototype = 1;
6145 static const int kHasNamedInterceptor = 2;
6146 static const int kHasIndexedInterceptor = 3;
6147 static const int kIsUndetectable = 4;
6148 static const int kIsObserved = 5;
6149 static const int kIsAccessCheckNeeded = 6;
6150 class FunctionWithPrototype: public BitField<bool, 7, 1> {};
6152 // Bit positions for bit field 2
6153 static const int kIsExtensible = 0;
6154 static const int kStringWrapperSafeForDefaultValueOf = 1;
6155 class IsPrototypeMapBits : public BitField<bool, 2, 1> {};
6156 class ElementsKindBits: public BitField<ElementsKind, 3, 5> {};
6158 // Derived values from bit field 2
6159 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
6160 (FAST_ELEMENTS + 1) << Map::ElementsKindBits::kShift) - 1;
6161 static const int8_t kMaximumBitField2FastSmiElementValue =
6162 static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
6163 Map::ElementsKindBits::kShift) - 1;
6164 static const int8_t kMaximumBitField2FastHoleyElementValue =
6165 static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
6166 Map::ElementsKindBits::kShift) - 1;
6167 static const int8_t kMaximumBitField2FastHoleySmiElementValue =
6168 static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
6169 Map::ElementsKindBits::kShift) - 1;
6171 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
6172 kPointerFieldsEndOffset,
6173 kSize> BodyDescriptor;
6175 // Compares this map to another to see if they describe equivalent objects.
6176 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
6177 // it had exactly zero inobject properties.
6178 // The "shared" flags of both this map and |other| are ignored.
6179 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
6181 // Returns true if given field is unboxed double.
6182 inline bool IsUnboxedDoubleField(FieldIndex index);
6185 static void TraceTransition(const char* what, Map* from, Map* to, Name* name);
6186 static void TraceAllTransitions(Map* map);
6189 static inline Handle<Map> CopyInstallDescriptorsForTesting(
6190 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
6191 Handle<LayoutDescriptor> layout_descriptor);
6194 static void ConnectTransition(Handle<Map> parent, Handle<Map> child,
6195 Handle<Name> name, SimpleTransitionFlag flag);
6197 bool EquivalentToForTransition(Map* other);
6198 static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
6199 static Handle<Map> ShareDescriptor(Handle<Map> map,
6200 Handle<DescriptorArray> descriptors,
6201 Descriptor* descriptor);
6202 static Handle<Map> CopyInstallDescriptors(
6203 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
6204 Handle<LayoutDescriptor> layout_descriptor);
6205 static Handle<Map> CopyAddDescriptor(Handle<Map> map,
6206 Descriptor* descriptor,
6207 TransitionFlag flag);
6208 static Handle<Map> CopyReplaceDescriptors(
6209 Handle<Map> map, Handle<DescriptorArray> descriptors,
6210 Handle<LayoutDescriptor> layout_descriptor, TransitionFlag flag,
6211 MaybeHandle<Name> maybe_name, const char* reason,
6212 SimpleTransitionFlag simple_flag);
6214 static Handle<Map> CopyReplaceDescriptor(Handle<Map> map,
6215 Handle<DescriptorArray> descriptors,
6216 Descriptor* descriptor,
6218 TransitionFlag flag);
6219 static MUST_USE_RESULT MaybeHandle<Map> TryReconfigureExistingProperty(
6220 Handle<Map> map, int descriptor, PropertyKind kind,
6221 PropertyAttributes attributes, const char** reason);
6223 static Handle<Map> CopyNormalized(Handle<Map> map,
6224 PropertyNormalizationMode mode);
6226 // Fires when the layout of an object with a leaf map changes.
6227 // This includes adding transitions to the leaf map or changing
6228 // the descriptor array.
6229 inline void NotifyLeafMapLayoutChange();
6231 void DeprecateTransitionTree();
6232 bool DeprecateTarget(PropertyKind kind, Name* key,
6233 PropertyAttributes attributes,
6234 DescriptorArray* new_descriptors,
6235 LayoutDescriptor* new_layout_descriptor);
6237 Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
6239 // Update field type of the given descriptor to new representation and new
6240 // type. The type must be prepared for storing in descriptor array:
6241 // it must be either a simple type or a map wrapped in a weak cell.
6242 void UpdateFieldType(int descriptor_number, Handle<Name> name,
6243 Representation new_representation,
6244 Handle<Object> new_wrapped_type);
6246 void PrintReconfiguration(FILE* file, int modify_index, PropertyKind kind,
6247 PropertyAttributes attributes);
6248 void PrintGeneralization(FILE* file,
6253 bool constant_to_field,
6254 Representation old_representation,
6255 Representation new_representation,
6256 HeapType* old_field_type,
6257 HeapType* new_field_type);
6259 static const int kFastPropertiesSoftLimit = 12;
6260 static const int kMaxFastProperties = 128;
6262 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
6266 // An abstract superclass, a marker class really, for simple structure classes.
6267 // It doesn't carry much functionality but allows struct classes to be
6268 // identified in the type system.
6269 class Struct: public HeapObject {
6271 inline void InitializeBody(int object_size);
6272 DECLARE_CAST(Struct)
6276 // A simple one-element struct, useful where smis need to be boxed.
6277 class Box : public Struct {
6279 // [value]: the boxed contents.
6280 DECL_ACCESSORS(value, Object)
6284 // Dispatched behavior.
6285 DECLARE_PRINTER(Box)
6286 DECLARE_VERIFIER(Box)
6288 static const int kValueOffset = HeapObject::kHeaderSize;
6289 static const int kSize = kValueOffset + kPointerSize;
6292 DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
6296 // Container for metadata stored on each prototype map.
6297 class PrototypeInfo : public Struct {
6299 // [prototype_users]: WeakFixedArray containing maps using this prototype,
6300 // or Smi(0) if uninitialized.
6301 DECL_ACCESSORS(prototype_users, Object)
6302 // [validity_cell]: Cell containing the validity bit for prototype chains
6303 // going through this object, or Smi(0) if uninitialized.
6304 DECL_ACCESSORS(validity_cell, Object)
6305 // [constructor_name]: User-friendly name of the original constructor.
6306 DECL_ACCESSORS(constructor_name, Object)
6308 DECLARE_CAST(PrototypeInfo)
6310 // Dispatched behavior.
6311 DECLARE_PRINTER(PrototypeInfo)
6312 DECLARE_VERIFIER(PrototypeInfo)
6314 static const int kPrototypeUsersOffset = HeapObject::kHeaderSize;
6315 static const int kValidityCellOffset = kPrototypeUsersOffset + kPointerSize;
6316 static const int kConstructorNameOffset = kValidityCellOffset + kPointerSize;
6317 static const int kSize = kConstructorNameOffset + kPointerSize;
6320 DISALLOW_IMPLICIT_CONSTRUCTORS(PrototypeInfo);
6324 // Script describes a script which has been added to the VM.
6325 class Script: public Struct {
6334 // Script compilation types.
6335 enum CompilationType {
6336 COMPILATION_TYPE_HOST = 0,
6337 COMPILATION_TYPE_EVAL = 1
6340 // Script compilation state.
6341 enum CompilationState {
6342 COMPILATION_STATE_INITIAL = 0,
6343 COMPILATION_STATE_COMPILED = 1
6346 // [source]: the script source.
6347 DECL_ACCESSORS(source, Object)
6349 // [name]: the script name.
6350 DECL_ACCESSORS(name, Object)
6352 // [id]: the script id.
6353 DECL_ACCESSORS(id, Smi)
6355 // [line_offset]: script line offset in resource from where it was extracted.
6356 DECL_ACCESSORS(line_offset, Smi)
6358 // [column_offset]: script column offset in resource from where it was
6360 DECL_ACCESSORS(column_offset, Smi)
6362 // [context_data]: context data for the context this script was compiled in.
6363 DECL_ACCESSORS(context_data, Object)
6365 // [wrapper]: the wrapper cache. This is either undefined or a WeakCell.
6366 DECL_ACCESSORS(wrapper, HeapObject)
6368 // [type]: the script type.
6369 DECL_ACCESSORS(type, Smi)
6371 // [line_ends]: FixedArray of line ends positions.
6372 DECL_ACCESSORS(line_ends, Object)
6374 // [eval_from_shared]: for eval scripts the shared funcion info for the
6375 // function from which eval was called.
6376 DECL_ACCESSORS(eval_from_shared, Object)
6378 // [eval_from_instructions_offset]: the instruction offset in the code for the
6379 // function from which eval was called where eval was called.
6380 DECL_ACCESSORS(eval_from_instructions_offset, Smi)
6382 // [shared_function_infos]: weak fixed array containing all shared
6383 // function infos created from this script.
6384 DECL_ACCESSORS(shared_function_infos, Object)
6386 // [flags]: Holds an exciting bitfield.
6387 DECL_ACCESSORS(flags, Smi)
6389 // [source_url]: sourceURL from magic comment
6390 DECL_ACCESSORS(source_url, Object)
6392 // [source_url]: sourceMappingURL magic comment
6393 DECL_ACCESSORS(source_mapping_url, Object)
6395 // [compilation_type]: how the the script was compiled. Encoded in the
6397 inline CompilationType compilation_type();
6398 inline void set_compilation_type(CompilationType type);
6400 // [compilation_state]: determines whether the script has already been
6401 // compiled. Encoded in the 'flags' field.
6402 inline CompilationState compilation_state();
6403 inline void set_compilation_state(CompilationState state);
6405 // [origin_options]: optional attributes set by the embedder via ScriptOrigin,
6406 // and used by the embedder to make decisions about the script. V8 just passes
6407 // this through. Encoded in the 'flags' field.
6408 inline v8::ScriptOriginOptions origin_options();
6409 inline void set_origin_options(ScriptOriginOptions origin_options);
6411 DECLARE_CAST(Script)
6413 // If script source is an external string, check that the underlying
6414 // resource is accessible. Otherwise, always return true.
6415 inline bool HasValidSource();
6417 // Convert code position into column number.
6418 static int GetColumnNumber(Handle<Script> script, int code_pos);
6420 // Convert code position into (zero-based) line number.
6421 // The non-handlified version does not allocate, but may be much slower.
6422 static int GetLineNumber(Handle<Script> script, int code_pos);
6423 int GetLineNumber(int code_pos);
6425 static Handle<Object> GetNameOrSourceURL(Handle<Script> script);
6427 // Init line_ends array with code positions of line ends inside script source.
6428 static void InitLineEnds(Handle<Script> script);
6430 // Get the JS object wrapping the given script; create it if none exists.
6431 static Handle<JSObject> GetWrapper(Handle<Script> script);
6433 // Look through the list of existing shared function infos to find one
6434 // that matches the function literal. Return empty handle if not found.
6435 MaybeHandle<SharedFunctionInfo> FindSharedFunctionInfo(FunctionLiteral* fun);
6437 // Dispatched behavior.
6438 DECLARE_PRINTER(Script)
6439 DECLARE_VERIFIER(Script)
6441 static const int kSourceOffset = HeapObject::kHeaderSize;
6442 static const int kNameOffset = kSourceOffset + kPointerSize;
6443 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
6444 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
6445 static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
6446 static const int kWrapperOffset = kContextOffset + kPointerSize;
6447 static const int kTypeOffset = kWrapperOffset + kPointerSize;
6448 static const int kLineEndsOffset = kTypeOffset + kPointerSize;
6449 static const int kIdOffset = kLineEndsOffset + kPointerSize;
6450 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
6451 static const int kEvalFrominstructionsOffsetOffset =
6452 kEvalFromSharedOffset + kPointerSize;
6453 static const int kSharedFunctionInfosOffset =
6454 kEvalFrominstructionsOffsetOffset + kPointerSize;
6455 static const int kFlagsOffset = kSharedFunctionInfosOffset + kPointerSize;
6456 static const int kSourceUrlOffset = kFlagsOffset + kPointerSize;
6457 static const int kSourceMappingUrlOffset = kSourceUrlOffset + kPointerSize;
6458 static const int kSize = kSourceMappingUrlOffset + kPointerSize;
6461 int GetLineNumberWithArray(int code_pos);
6463 // Bit positions in the flags field.
6464 static const int kCompilationTypeBit = 0;
6465 static const int kCompilationStateBit = 1;
6466 static const int kOriginOptionsShift = 2;
6467 static const int kOriginOptionsSize = 3;
6468 static const int kOriginOptionsMask = ((1 << kOriginOptionsSize) - 1)
6469 << kOriginOptionsShift;
6471 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6475 // List of builtin functions we want to identify to improve code
6478 // Each entry has a name of a global object property holding an object
6479 // optionally followed by ".prototype", a name of a builtin function
6480 // on the object (the one the id is set for), and a label.
6482 // Installation of ids for the selected builtin functions is handled
6483 // by the bootstrapper.
6484 #define FUNCTIONS_WITH_ID_LIST(V) \
6485 V(Array.prototype, indexOf, ArrayIndexOf) \
6486 V(Array.prototype, lastIndexOf, ArrayLastIndexOf) \
6487 V(Array.prototype, push, ArrayPush) \
6488 V(Array.prototype, pop, ArrayPop) \
6489 V(Array.prototype, shift, ArrayShift) \
6490 V(Function.prototype, apply, FunctionApply) \
6491 V(Function.prototype, call, FunctionCall) \
6492 V(String.prototype, charCodeAt, StringCharCodeAt) \
6493 V(String.prototype, charAt, StringCharAt) \
6494 V(String, fromCharCode, StringFromCharCode) \
6495 V(Math, random, MathRandom) \
6496 V(Math, floor, MathFloor) \
6497 V(Math, round, MathRound) \
6498 V(Math, ceil, MathCeil) \
6499 V(Math, abs, MathAbs) \
6500 V(Math, log, MathLog) \
6501 V(Math, exp, MathExp) \
6502 V(Math, sqrt, MathSqrt) \
6503 V(Math, pow, MathPow) \
6504 V(Math, max, MathMax) \
6505 V(Math, min, MathMin) \
6506 V(Math, cos, MathCos) \
6507 V(Math, sin, MathSin) \
6508 V(Math, tan, MathTan) \
6509 V(Math, acos, MathAcos) \
6510 V(Math, asin, MathAsin) \
6511 V(Math, atan, MathAtan) \
6512 V(Math, atan2, MathAtan2) \
6513 V(Math, imul, MathImul) \
6514 V(Math, clz32, MathClz32) \
6515 V(Math, fround, MathFround)
6517 #define ATOMIC_FUNCTIONS_WITH_ID_LIST(V) \
6518 V(Atomics, load, AtomicsLoad) \
6519 V(Atomics, store, AtomicsStore)
6521 enum BuiltinFunctionId {
6523 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
6525 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6526 ATOMIC_FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6527 #undef DECLARE_FUNCTION_ID
6528 // Fake id for a special case of Math.pow. Note, it continues the
6529 // list of math functions.
6534 // Result of searching in an optimized code map of a SharedFunctionInfo. Note
6535 // that both {code} and {literals} can be NULL to pass search result status.
6536 struct CodeAndLiterals {
6537 Code* code; // Cached optimized code.
6538 FixedArray* literals; // Cached literals array.
6542 // SharedFunctionInfo describes the JSFunction information that can be
6543 // shared by multiple instances of the function.
6544 class SharedFunctionInfo: public HeapObject {
6546 // [name]: Function name.
6547 DECL_ACCESSORS(name, Object)
6549 // [code]: Function code.
6550 DECL_ACCESSORS(code, Code)
6551 inline void ReplaceCode(Code* code);
6553 // [optimized_code_map]: Map from native context to optimized code
6554 // and a shared literals array or Smi(0) if none.
6555 DECL_ACCESSORS(optimized_code_map, Object)
6557 // Returns entry from optimized code map for specified context and OSR entry.
6558 // Note that {code == nullptr} indicates no matching entry has been found,
6559 // whereas {literals == nullptr} indicates the code is context-independent.
6560 CodeAndLiterals SearchOptimizedCodeMap(Context* native_context,
6561 BailoutId osr_ast_id);
6563 // Clear optimized code map.
6564 void ClearOptimizedCodeMap();
6566 // Removed a specific optimized code object from the optimized code map.
6567 void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
6569 // Trims the optimized code map after entries have been removed.
6570 void TrimOptimizedCodeMap(int shrink_by);
6572 // Add a new entry to the optimized code map for context-independent code.
6573 static void AddSharedCodeToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6576 // Add a new entry to the optimized code map for context-dependent code.
6577 static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6578 Handle<Context> native_context,
6580 Handle<FixedArray> literals,
6581 BailoutId osr_ast_id);
6583 // Set up the link between shared function info and the script. The shared
6584 // function info is added to the list on the script.
6585 static void SetScript(Handle<SharedFunctionInfo> shared,
6586 Handle<Object> script_object);
6588 // Layout description of the optimized code map.
6589 static const int kNextMapIndex = 0;
6590 static const int kSharedCodeIndex = 1;
6591 static const int kEntriesStart = 2;
6592 static const int kContextOffset = 0;
6593 static const int kCachedCodeOffset = 1;
6594 static const int kLiteralsOffset = 2;
6595 static const int kOsrAstIdOffset = 3;
6596 static const int kEntryLength = 4;
6597 static const int kInitialLength = kEntriesStart + kEntryLength;
6599 // [scope_info]: Scope info.
6600 DECL_ACCESSORS(scope_info, ScopeInfo)
6602 // [construct stub]: Code stub for constructing instances of this function.
6603 DECL_ACCESSORS(construct_stub, Code)
6605 // Returns if this function has been compiled to native code yet.
6606 inline bool is_compiled();
6608 // [length]: The function length - usually the number of declared parameters.
6609 // Use up to 2^30 parameters.
6610 inline int length() const;
6611 inline void set_length(int value);
6613 // [internal formal parameter count]: The declared number of parameters.
6614 // For subclass constructors, also includes new.target.
6615 // The size of function's frame is internal_formal_parameter_count + 1.
6616 inline int internal_formal_parameter_count() const;
6617 inline void set_internal_formal_parameter_count(int value);
6619 // Set the formal parameter count so the function code will be
6620 // called without using argument adaptor frames.
6621 inline void DontAdaptArguments();
6623 // [expected_nof_properties]: Expected number of properties for the function.
6624 inline int expected_nof_properties() const;
6625 inline void set_expected_nof_properties(int value);
6627 // [feedback_vector] - accumulates ast node feedback from full-codegen and
6628 // (increasingly) from crankshafted code where sufficient feedback isn't
6630 DECL_ACCESSORS(feedback_vector, TypeFeedbackVector)
6632 // Unconditionally clear the type feedback vector (including vector ICs).
6633 void ClearTypeFeedbackInfo();
6635 // Clear the type feedback vector with a more subtle policy at GC time.
6636 void ClearTypeFeedbackInfoAtGCTime();
6639 // [unique_id] - For --trace-maps purposes, an identifier that's persistent
6640 // even if the GC moves this SharedFunctionInfo.
6641 inline int unique_id() const;
6642 inline void set_unique_id(int value);
6645 // [instance class name]: class name for instances.
6646 DECL_ACCESSORS(instance_class_name, Object)
6648 // [function data]: This field holds some additional data for function.
6649 // Currently it either has FunctionTemplateInfo to make benefit the API
6650 // or Smi identifying a builtin function.
6651 // In the long run we don't want all functions to have this field but
6652 // we can fix that when we have a better model for storing hidden data
6654 DECL_ACCESSORS(function_data, Object)
6656 inline bool IsApiFunction();
6657 inline FunctionTemplateInfo* get_api_func_data();
6658 inline bool HasBuiltinFunctionId();
6659 inline BuiltinFunctionId builtin_function_id();
6661 // [script info]: Script from which the function originates.
6662 DECL_ACCESSORS(script, Object)
6664 // [num_literals]: Number of literals used by this function.
6665 inline int num_literals() const;
6666 inline void set_num_literals(int value);
6668 // [start_position_and_type]: Field used to store both the source code
6669 // position, whether or not the function is a function expression,
6670 // and whether or not the function is a toplevel function. The two
6671 // least significants bit indicates whether the function is an
6672 // expression and the rest contains the source code position.
6673 inline int start_position_and_type() const;
6674 inline void set_start_position_and_type(int value);
6676 // The function is subject to debugging if a debug info is attached.
6677 inline bool HasDebugInfo();
6678 inline DebugInfo* GetDebugInfo();
6680 // A function has debug code if the compiled code has debug break slots.
6681 inline bool HasDebugCode();
6683 // [debug info]: Debug information.
6684 DECL_ACCESSORS(debug_info, Object)
6686 // [inferred name]: Name inferred from variable or property
6687 // assignment of this function. Used to facilitate debugging and
6688 // profiling of JavaScript code written in OO style, where almost
6689 // all functions are anonymous but are assigned to object
6691 DECL_ACCESSORS(inferred_name, String)
6693 // The function's name if it is non-empty, otherwise the inferred name.
6694 String* DebugName();
6696 // Position of the 'function' token in the script source.
6697 inline int function_token_position() const;
6698 inline void set_function_token_position(int function_token_position);
6700 // Position of this function in the script source.
6701 inline int start_position() const;
6702 inline void set_start_position(int start_position);
6704 // End position of this function in the script source.
6705 inline int end_position() const;
6706 inline void set_end_position(int end_position);
6708 // Is this function a function expression in the source code.
6709 DECL_BOOLEAN_ACCESSORS(is_expression)
6711 // Is this function a top-level function (scripts, evals).
6712 DECL_BOOLEAN_ACCESSORS(is_toplevel)
6714 // Bit field containing various information collected by the compiler to
6715 // drive optimization.
6716 inline int compiler_hints() const;
6717 inline void set_compiler_hints(int value);
6719 inline int ast_node_count() const;
6720 inline void set_ast_node_count(int count);
6722 inline int profiler_ticks() const;
6723 inline void set_profiler_ticks(int ticks);
6725 // Inline cache age is used to infer whether the function survived a context
6726 // disposal or not. In the former case we reset the opt_count.
6727 inline int ic_age();
6728 inline void set_ic_age(int age);
6730 // Indicates if this function can be lazy compiled.
6731 // This is used to determine if we can safely flush code from a function
6732 // when doing GC if we expect that the function will no longer be used.
6733 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
6735 // Indicates if this function can be lazy compiled without a context.
6736 // This is used to determine if we can force compilation without reaching
6737 // the function through program execution but through other means (e.g. heap
6738 // iteration by the debugger).
6739 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
6741 // Indicates whether optimizations have been disabled for this
6742 // shared function info. If a function is repeatedly optimized or if
6743 // we cannot optimize the function we disable optimization to avoid
6744 // spending time attempting to optimize it again.
6745 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
6747 // Indicates the language mode.
6748 inline LanguageMode language_mode();
6749 inline void set_language_mode(LanguageMode language_mode);
6751 // False if the function definitely does not allocate an arguments object.
6752 DECL_BOOLEAN_ACCESSORS(uses_arguments)
6754 // Indicates that this function uses a super property (or an eval that may
6755 // use a super property).
6756 // This is needed to set up the [[HomeObject]] on the function instance.
6757 DECL_BOOLEAN_ACCESSORS(needs_home_object)
6759 // True if the function has any duplicated parameter names.
6760 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
6762 // Indicates whether the function is a native function.
6763 // These needs special treatment in .call and .apply since
6764 // null passed as the receiver should not be translated to the
6766 DECL_BOOLEAN_ACCESSORS(native)
6768 // Indicate that this function should always be inlined in optimized code.
6769 DECL_BOOLEAN_ACCESSORS(force_inline)
6771 // Indicates that the function was created by the Function function.
6772 // Though it's anonymous, toString should treat it as if it had the name
6773 // "anonymous". We don't set the name itself so that the system does not
6774 // see a binding for it.
6775 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
6777 // Indicates whether the function is a bound function created using
6778 // the bind function.
6779 DECL_BOOLEAN_ACCESSORS(bound)
6781 // Indicates that the function is anonymous (the name field can be set
6782 // through the API, which does not change this flag).
6783 DECL_BOOLEAN_ACCESSORS(is_anonymous)
6785 // Is this a function or top-level/eval code.
6786 DECL_BOOLEAN_ACCESSORS(is_function)
6788 // Indicates that code for this function cannot be compiled with Crankshaft.
6789 DECL_BOOLEAN_ACCESSORS(dont_crankshaft)
6791 // Indicates that code for this function cannot be flushed.
6792 DECL_BOOLEAN_ACCESSORS(dont_flush)
6794 // Indicates that this function is a generator.
6795 DECL_BOOLEAN_ACCESSORS(is_generator)
6797 // Indicates that this function is an arrow function.
6798 DECL_BOOLEAN_ACCESSORS(is_arrow)
6800 // Indicates that this function is a concise method.
6801 DECL_BOOLEAN_ACCESSORS(is_concise_method)
6803 // Indicates that this function is an accessor (getter or setter).
6804 DECL_BOOLEAN_ACCESSORS(is_accessor_function)
6806 // Indicates that this function is a default constructor.
6807 DECL_BOOLEAN_ACCESSORS(is_default_constructor)
6809 // Indicates that this function is an asm function.
6810 DECL_BOOLEAN_ACCESSORS(asm_function)
6812 // Indicates that the the shared function info is deserialized from cache.
6813 DECL_BOOLEAN_ACCESSORS(deserialized)
6815 // Indicates that the the shared function info has never been compiled before.
6816 DECL_BOOLEAN_ACCESSORS(never_compiled)
6818 inline FunctionKind kind();
6819 inline void set_kind(FunctionKind kind);
6821 // Indicates whether or not the code in the shared function support
6823 inline bool has_deoptimization_support();
6825 // Enable deoptimization support through recompiled code.
6826 void EnableDeoptimizationSupport(Code* recompiled);
6828 // Disable (further) attempted optimization of all functions sharing this
6829 // shared function info.
6830 void DisableOptimization(BailoutReason reason);
6832 inline BailoutReason disable_optimization_reason();
6834 // Lookup the bailout ID and DCHECK that it exists in the non-optimized
6835 // code, returns whether it asserted (i.e., always true if assertions are
6837 bool VerifyBailoutId(BailoutId id);
6839 // [source code]: Source code for the function.
6840 bool HasSourceCode() const;
6841 Handle<Object> GetSourceCode();
6843 // Number of times the function was optimized.
6844 inline int opt_count();
6845 inline void set_opt_count(int opt_count);
6847 // Number of times the function was deoptimized.
6848 inline void set_deopt_count(int value);
6849 inline int deopt_count();
6850 inline void increment_deopt_count();
6852 // Number of time we tried to re-enable optimization after it
6853 // was disabled due to high number of deoptimizations.
6854 inline void set_opt_reenable_tries(int value);
6855 inline int opt_reenable_tries();
6857 inline void TryReenableOptimization();
6859 // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
6860 inline void set_counters(int value);
6861 inline int counters() const;
6863 // Stores opt_count and bailout_reason as bit-fields.
6864 inline void set_opt_count_and_bailout_reason(int value);
6865 inline int opt_count_and_bailout_reason() const;
6867 void set_disable_optimization_reason(BailoutReason reason) {
6868 set_opt_count_and_bailout_reason(
6869 DisabledOptimizationReasonBits::update(opt_count_and_bailout_reason(),
6873 // Tells whether this function should be subject to debugging.
6874 inline bool IsSubjectToDebugging();
6876 // Check whether or not this function is inlineable.
6877 bool IsInlineable();
6879 // Source size of this function.
6882 // Calculate the instance size.
6883 int CalculateInstanceSize();
6885 // Calculate the number of in-object properties.
6886 int CalculateInObjectProperties();
6888 inline bool is_simple_parameter_list();
6890 // Initialize a SharedFunctionInfo from a parsed function literal.
6891 static void InitFromFunctionLiteral(Handle<SharedFunctionInfo> shared_info,
6892 FunctionLiteral* lit);
6894 // Dispatched behavior.
6895 DECLARE_PRINTER(SharedFunctionInfo)
6896 DECLARE_VERIFIER(SharedFunctionInfo)
6898 void ResetForNewContext(int new_ic_age);
6900 DECLARE_CAST(SharedFunctionInfo)
6903 static const int kDontAdaptArgumentsSentinel = -1;
6905 // Layout description.
6907 static const int kNameOffset = HeapObject::kHeaderSize;
6908 static const int kCodeOffset = kNameOffset + kPointerSize;
6909 static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
6910 static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
6911 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
6912 static const int kInstanceClassNameOffset =
6913 kConstructStubOffset + kPointerSize;
6914 static const int kFunctionDataOffset =
6915 kInstanceClassNameOffset + kPointerSize;
6916 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
6917 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
6918 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
6919 static const int kFeedbackVectorOffset =
6920 kInferredNameOffset + kPointerSize;
6922 static const int kUniqueIdOffset = kFeedbackVectorOffset + kPointerSize;
6923 static const int kLastPointerFieldOffset = kUniqueIdOffset;
6925 // Just to not break the postmortrem support with conditional offsets
6926 static const int kUniqueIdOffset = kFeedbackVectorOffset;
6927 static const int kLastPointerFieldOffset = kFeedbackVectorOffset;
6930 #if V8_HOST_ARCH_32_BIT
6932 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6933 static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
6934 static const int kExpectedNofPropertiesOffset =
6935 kFormalParameterCountOffset + kPointerSize;
6936 static const int kNumLiteralsOffset =
6937 kExpectedNofPropertiesOffset + kPointerSize;
6938 static const int kStartPositionAndTypeOffset =
6939 kNumLiteralsOffset + kPointerSize;
6940 static const int kEndPositionOffset =
6941 kStartPositionAndTypeOffset + kPointerSize;
6942 static const int kFunctionTokenPositionOffset =
6943 kEndPositionOffset + kPointerSize;
6944 static const int kCompilerHintsOffset =
6945 kFunctionTokenPositionOffset + kPointerSize;
6946 static const int kOptCountAndBailoutReasonOffset =
6947 kCompilerHintsOffset + kPointerSize;
6948 static const int kCountersOffset =
6949 kOptCountAndBailoutReasonOffset + kPointerSize;
6950 static const int kAstNodeCountOffset =
6951 kCountersOffset + kPointerSize;
6952 static const int kProfilerTicksOffset =
6953 kAstNodeCountOffset + kPointerSize;
6956 static const int kSize = kProfilerTicksOffset + kPointerSize;
6958 // The only reason to use smi fields instead of int fields
6959 // is to allow iteration without maps decoding during
6960 // garbage collections.
6961 // To avoid wasting space on 64-bit architectures we use
6962 // the following trick: we group integer fields into pairs
6963 // The least significant integer in each pair is shifted left by 1.
6964 // By doing this we guarantee that LSB of each kPointerSize aligned
6965 // word is not set and thus this word cannot be treated as pointer
6966 // to HeapObject during old space traversal.
6967 #if V8_TARGET_LITTLE_ENDIAN
6968 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6969 static const int kFormalParameterCountOffset =
6970 kLengthOffset + kIntSize;
6972 static const int kExpectedNofPropertiesOffset =
6973 kFormalParameterCountOffset + kIntSize;
6974 static const int kNumLiteralsOffset =
6975 kExpectedNofPropertiesOffset + kIntSize;
6977 static const int kEndPositionOffset =
6978 kNumLiteralsOffset + kIntSize;
6979 static const int kStartPositionAndTypeOffset =
6980 kEndPositionOffset + kIntSize;
6982 static const int kFunctionTokenPositionOffset =
6983 kStartPositionAndTypeOffset + kIntSize;
6984 static const int kCompilerHintsOffset =
6985 kFunctionTokenPositionOffset + kIntSize;
6987 static const int kOptCountAndBailoutReasonOffset =
6988 kCompilerHintsOffset + kIntSize;
6989 static const int kCountersOffset =
6990 kOptCountAndBailoutReasonOffset + kIntSize;
6992 static const int kAstNodeCountOffset =
6993 kCountersOffset + kIntSize;
6994 static const int kProfilerTicksOffset =
6995 kAstNodeCountOffset + kIntSize;
6998 static const int kSize = kProfilerTicksOffset + kIntSize;
7000 #elif V8_TARGET_BIG_ENDIAN
7001 static const int kFormalParameterCountOffset =
7002 kLastPointerFieldOffset + kPointerSize;
7003 static const int kLengthOffset = kFormalParameterCountOffset + kIntSize;
7005 static const int kNumLiteralsOffset = kLengthOffset + kIntSize;
7006 static const int kExpectedNofPropertiesOffset = kNumLiteralsOffset + kIntSize;
7008 static const int kStartPositionAndTypeOffset =
7009 kExpectedNofPropertiesOffset + kIntSize;
7010 static const int kEndPositionOffset = kStartPositionAndTypeOffset + kIntSize;
7012 static const int kCompilerHintsOffset = kEndPositionOffset + kIntSize;
7013 static const int kFunctionTokenPositionOffset =
7014 kCompilerHintsOffset + kIntSize;
7016 static const int kCountersOffset = kFunctionTokenPositionOffset + kIntSize;
7017 static const int kOptCountAndBailoutReasonOffset = kCountersOffset + kIntSize;
7019 static const int kProfilerTicksOffset =
7020 kOptCountAndBailoutReasonOffset + kIntSize;
7021 static const int kAstNodeCountOffset = kProfilerTicksOffset + kIntSize;
7024 static const int kSize = kAstNodeCountOffset + kIntSize;
7027 #error Unknown byte ordering
7028 #endif // Big endian
7032 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
7034 typedef FixedBodyDescriptor<kNameOffset,
7035 kLastPointerFieldOffset + kPointerSize,
7036 kSize> BodyDescriptor;
7038 // Bit positions in start_position_and_type.
7039 // The source code start position is in the 30 most significant bits of
7040 // the start_position_and_type field.
7041 static const int kIsExpressionBit = 0;
7042 static const int kIsTopLevelBit = 1;
7043 static const int kStartPositionShift = 2;
7044 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
7046 // Bit positions in compiler_hints.
7047 enum CompilerHints {
7048 kAllowLazyCompilation,
7049 kAllowLazyCompilationWithoutContext,
7050 kOptimizationDisabled,
7051 kStrictModeFunction,
7052 kStrongModeFunction,
7055 kHasDuplicateParameters,
7060 kNameShouldPrintAsAnonymous,
7067 kIsAccessorFunction,
7068 kIsDefaultConstructor,
7069 kIsSubclassConstructor,
7075 kCompilerHintsCount // Pseudo entry
7077 // Add hints for other modes when they're added.
7078 STATIC_ASSERT(LANGUAGE_END == 3);
7080 class FunctionKindBits : public BitField<FunctionKind, kIsArrow, 8> {};
7082 class DeoptCountBits : public BitField<int, 0, 4> {};
7083 class OptReenableTriesBits : public BitField<int, 4, 18> {};
7084 class ICAgeBits : public BitField<int, 22, 8> {};
7086 class OptCountBits : public BitField<int, 0, 22> {};
7087 class DisabledOptimizationReasonBits : public BitField<int, 22, 8> {};
7090 #if V8_HOST_ARCH_32_BIT
7091 // On 32 bit platforms, compiler hints is a smi.
7092 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
7093 static const int kCompilerHintsSize = kPointerSize;
7095 // On 64 bit platforms, compiler hints is not a smi, see comment above.
7096 static const int kCompilerHintsSmiTagSize = 0;
7097 static const int kCompilerHintsSize = kIntSize;
7100 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
7101 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
7104 // Constants for optimizing codegen for strict mode function and
7106 // Allows to use byte-width instructions.
7107 static const int kStrictModeBitWithinByte =
7108 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
7109 static const int kStrongModeBitWithinByte =
7110 (kStrongModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
7112 static const int kNativeBitWithinByte =
7113 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
7115 #if defined(V8_TARGET_LITTLE_ENDIAN)
7116 static const int kStrictModeByteOffset = kCompilerHintsOffset +
7117 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
7118 static const int kStrongModeByteOffset =
7119 kCompilerHintsOffset +
7120 (kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
7121 static const int kNativeByteOffset = kCompilerHintsOffset +
7122 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
7123 #elif defined(V8_TARGET_BIG_ENDIAN)
7124 static const int kStrictModeByteOffset = kCompilerHintsOffset +
7125 (kCompilerHintsSize - 1) -
7126 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
7127 static const int kStrongModeByteOffset =
7128 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
7129 ((kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
7130 static const int kNativeByteOffset = kCompilerHintsOffset +
7131 (kCompilerHintsSize - 1) -
7132 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
7134 #error Unknown byte ordering
7138 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
7142 // Printing support.
7143 struct SourceCodeOf {
7144 explicit SourceCodeOf(SharedFunctionInfo* v, int max = -1)
7145 : value(v), max_length(max) {}
7146 const SharedFunctionInfo* value;
7151 std::ostream& operator<<(std::ostream& os, const SourceCodeOf& v);
7154 class JSGeneratorObject: public JSObject {
7156 // [function]: The function corresponding to this generator object.
7157 DECL_ACCESSORS(function, JSFunction)
7159 // [context]: The context of the suspended computation.
7160 DECL_ACCESSORS(context, Context)
7162 // [receiver]: The receiver of the suspended computation.
7163 DECL_ACCESSORS(receiver, Object)
7165 // [continuation]: Offset into code of continuation.
7167 // A positive offset indicates a suspended generator. The special
7168 // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
7169 // cannot be resumed.
7170 inline int continuation() const;
7171 inline void set_continuation(int continuation);
7172 inline bool is_closed();
7173 inline bool is_executing();
7174 inline bool is_suspended();
7176 // [operand_stack]: Saved operand stack.
7177 DECL_ACCESSORS(operand_stack, FixedArray)
7179 DECLARE_CAST(JSGeneratorObject)
7181 // Dispatched behavior.
7182 DECLARE_PRINTER(JSGeneratorObject)
7183 DECLARE_VERIFIER(JSGeneratorObject)
7185 // Magic sentinel values for the continuation.
7186 static const int kGeneratorExecuting = -1;
7187 static const int kGeneratorClosed = 0;
7189 // Layout description.
7190 static const int kFunctionOffset = JSObject::kHeaderSize;
7191 static const int kContextOffset = kFunctionOffset + kPointerSize;
7192 static const int kReceiverOffset = kContextOffset + kPointerSize;
7193 static const int kContinuationOffset = kReceiverOffset + kPointerSize;
7194 static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
7195 static const int kSize = kOperandStackOffset + kPointerSize;
7197 // Resume mode, for use by runtime functions.
7198 enum ResumeMode { NEXT, THROW };
7200 // Yielding from a generator returns an object with the following inobject
7201 // properties. See Context::iterator_result_map() for the map.
7202 static const int kResultValuePropertyIndex = 0;
7203 static const int kResultDonePropertyIndex = 1;
7204 static const int kResultPropertyCount = 2;
7206 static const int kResultValuePropertyOffset = JSObject::kHeaderSize;
7207 static const int kResultDonePropertyOffset =
7208 kResultValuePropertyOffset + kPointerSize;
7209 static const int kResultSize = kResultDonePropertyOffset + kPointerSize;
7212 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
7216 // Representation for module instance objects.
7217 class JSModule: public JSObject {
7219 // [context]: the context holding the module's locals, or undefined if none.
7220 DECL_ACCESSORS(context, Object)
7222 // [scope_info]: Scope info.
7223 DECL_ACCESSORS(scope_info, ScopeInfo)
7225 DECLARE_CAST(JSModule)
7227 // Dispatched behavior.
7228 DECLARE_PRINTER(JSModule)
7229 DECLARE_VERIFIER(JSModule)
7231 // Layout description.
7232 static const int kContextOffset = JSObject::kHeaderSize;
7233 static const int kScopeInfoOffset = kContextOffset + kPointerSize;
7234 static const int kSize = kScopeInfoOffset + kPointerSize;
7237 DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
7241 // JSFunction describes JavaScript functions.
7242 class JSFunction: public JSObject {
7244 // [prototype_or_initial_map]:
7245 DECL_ACCESSORS(prototype_or_initial_map, Object)
7247 // [shared]: The information about the function that
7248 // can be shared by instances.
7249 DECL_ACCESSORS(shared, SharedFunctionInfo)
7251 // [context]: The context for this function.
7252 inline Context* context();
7253 inline void set_context(Object* context);
7254 inline JSObject* global_proxy();
7256 // [code]: The generated code object for this function. Executed
7257 // when the function is invoked, e.g. foo() or new foo(). See
7258 // [[Call]] and [[Construct]] description in ECMA-262, section
7260 inline Code* code();
7261 inline void set_code(Code* code);
7262 inline void set_code_no_write_barrier(Code* code);
7263 inline void ReplaceCode(Code* code);
7265 // Tells whether this function is builtin.
7266 inline bool IsBuiltin();
7268 // Tells whether this function inlines the given shared function info.
7269 bool Inlines(SharedFunctionInfo* candidate);
7271 // Tells whether this function should be subject to debugging.
7272 inline bool IsSubjectToDebugging();
7274 // Tells whether or not the function needs arguments adaption.
7275 inline bool NeedsArgumentsAdaption();
7277 // Tells whether or not this function has been optimized.
7278 inline bool IsOptimized();
7280 // Mark this function for lazy recompilation. The function will be
7281 // recompiled the next time it is executed.
7282 void MarkForOptimization();
7283 void AttemptConcurrentOptimization();
7285 // Tells whether or not the function is already marked for lazy
7287 inline bool IsMarkedForOptimization();
7288 inline bool IsMarkedForConcurrentOptimization();
7290 // Tells whether or not the function is on the concurrent recompilation queue.
7291 inline bool IsInOptimizationQueue();
7293 // Inobject slack tracking is the way to reclaim unused inobject space.
7295 // The instance size is initially determined by adding some slack to
7296 // expected_nof_properties (to allow for a few extra properties added
7297 // after the constructor). There is no guarantee that the extra space
7298 // will not be wasted.
7300 // Here is the algorithm to reclaim the unused inobject space:
7301 // - Detect the first constructor call for this JSFunction.
7302 // When it happens enter the "in progress" state: initialize construction
7303 // counter in the initial_map.
7304 // - While the tracking is in progress create objects filled with
7305 // one_pointer_filler_map instead of undefined_value. This way they can be
7306 // resized quickly and safely.
7307 // - Once enough objects have been created compute the 'slack'
7308 // (traverse the map transition tree starting from the
7309 // initial_map and find the lowest value of unused_property_fields).
7310 // - Traverse the transition tree again and decrease the instance size
7311 // of every map. Existing objects will resize automatically (they are
7312 // filled with one_pointer_filler_map). All further allocations will
7313 // use the adjusted instance size.
7314 // - SharedFunctionInfo's expected_nof_properties left unmodified since
7315 // allocations made using different closures could actually create different
7316 // kind of objects (see prototype inheritance pattern).
7318 // Important: inobject slack tracking is not attempted during the snapshot
7321 // True if the initial_map is set and the object constructions countdown
7322 // counter is not zero.
7323 static const int kGenerousAllocationCount =
7324 Map::kSlackTrackingCounterStart - Map::kSlackTrackingCounterEnd + 1;
7325 inline bool IsInobjectSlackTrackingInProgress();
7327 // Starts the tracking.
7328 // Initializes object constructions countdown counter in the initial map.
7329 void StartInobjectSlackTracking();
7331 // Completes the tracking.
7332 void CompleteInobjectSlackTracking();
7334 // [literals_or_bindings]: Fixed array holding either
7335 // the materialized literals or the bindings of a bound function.
7337 // If the function contains object, regexp or array literals, the
7338 // literals array prefix contains the object, regexp, and array
7339 // function to be used when creating these literals. This is
7340 // necessary so that we do not dynamically lookup the object, regexp
7341 // or array functions. Performing a dynamic lookup, we might end up
7342 // using the functions from a new context that we should not have
7345 // On bound functions, the array is a (copy-on-write) fixed-array containing
7346 // the function that was bound, bound this-value and any bound
7347 // arguments. Bound functions never contain literals.
7348 DECL_ACCESSORS(literals_or_bindings, FixedArray)
7350 inline FixedArray* literals();
7351 inline void set_literals(FixedArray* literals);
7353 inline FixedArray* function_bindings();
7354 inline void set_function_bindings(FixedArray* bindings);
7356 // The initial map for an object created by this constructor.
7357 inline Map* initial_map();
7358 static void SetInitialMap(Handle<JSFunction> function, Handle<Map> map,
7359 Handle<Object> prototype);
7360 inline bool has_initial_map();
7361 static void EnsureHasInitialMap(Handle<JSFunction> function);
7363 // Get and set the prototype property on a JSFunction. If the
7364 // function has an initial map the prototype is set on the initial
7365 // map. Otherwise, the prototype is put in the initial map field
7366 // until an initial map is needed.
7367 inline bool has_prototype();
7368 inline bool has_instance_prototype();
7369 inline Object* prototype();
7370 inline Object* instance_prototype();
7371 static void SetPrototype(Handle<JSFunction> function,
7372 Handle<Object> value);
7373 static void SetInstancePrototype(Handle<JSFunction> function,
7374 Handle<Object> value);
7376 // Creates a new closure for the fucntion with the same bindings,
7377 // bound values, and prototype. An equivalent of spec operations
7378 // ``CloneMethod`` and ``CloneBoundFunction``.
7379 static Handle<JSFunction> CloneClosure(Handle<JSFunction> function);
7381 // After prototype is removed, it will not be created when accessed, and
7382 // [[Construct]] from this function will not be allowed.
7383 bool RemovePrototype();
7384 inline bool should_have_prototype();
7386 // Accessor for this function's initial map's [[class]]
7387 // property. This is primarily used by ECMA native functions. This
7388 // method sets the class_name field of this function's initial map
7389 // to a given value. It creates an initial map if this function does
7390 // not have one. Note that this method does not copy the initial map
7391 // if it has one already, but simply replaces it with the new value.
7392 // Instances created afterwards will have a map whose [[class]] is
7393 // set to 'value', but there is no guarantees on instances created
7395 void SetInstanceClassName(String* name);
7397 // Returns if this function has been compiled to native code yet.
7398 inline bool is_compiled();
7400 // Returns `false` if formal parameters include rest parameters, optional
7401 // parameters, or destructuring parameters.
7402 // TODO(caitp): make this a flag set during parsing
7403 inline bool is_simple_parameter_list();
7405 // [next_function_link]: Links functions into various lists, e.g. the list
7406 // of optimized functions hanging off the native_context. The CodeFlusher
7407 // uses this link to chain together flushing candidates. Treated weakly
7408 // by the garbage collector.
7409 DECL_ACCESSORS(next_function_link, Object)
7411 // Prints the name of the function using PrintF.
7412 void PrintName(FILE* out = stdout);
7414 DECLARE_CAST(JSFunction)
7416 // Iterates the objects, including code objects indirectly referenced
7417 // through pointers to the first instruction in the code object.
7418 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
7420 // Dispatched behavior.
7421 DECLARE_PRINTER(JSFunction)
7422 DECLARE_VERIFIER(JSFunction)
7424 // Returns the number of allocated literals.
7425 inline int NumberOfLiterals();
7427 // Used for flags such as --hydrogen-filter.
7428 bool PassesFilter(const char* raw_filter);
7430 // The function's name if it is configured, otherwise shared function info
7432 static Handle<String> GetDebugName(Handle<JSFunction> function);
7434 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
7435 // kSize) is weak and has special handling during garbage collection.
7436 static const int kCodeEntryOffset = JSObject::kHeaderSize;
7437 static const int kPrototypeOrInitialMapOffset =
7438 kCodeEntryOffset + kPointerSize;
7439 static const int kSharedFunctionInfoOffset =
7440 kPrototypeOrInitialMapOffset + kPointerSize;
7441 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
7442 static const int kLiteralsOffset = kContextOffset + kPointerSize;
7443 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
7444 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
7445 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
7447 // Layout of the bound-function binding array.
7448 static const int kBoundFunctionIndex = 0;
7449 static const int kBoundThisIndex = 1;
7450 static const int kBoundArgumentsStartIndex = 2;
7453 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7457 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7458 // and the prototype is hidden. JSGlobalProxy always delegates
7459 // property accesses to its prototype if the prototype is not null.
7461 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7463 // Accessing a JSGlobalProxy requires security check.
7465 class JSGlobalProxy : public JSObject {
7467 // [native_context]: the owner native context of this global proxy object.
7468 // It is null value if this object is not used by any context.
7469 DECL_ACCESSORS(native_context, Object)
7471 // [hash]: The hash code property (undefined if not initialized yet).
7472 DECL_ACCESSORS(hash, Object)
7474 DECLARE_CAST(JSGlobalProxy)
7476 inline bool IsDetachedFrom(GlobalObject* global) const;
7478 // Dispatched behavior.
7479 DECLARE_PRINTER(JSGlobalProxy)
7480 DECLARE_VERIFIER(JSGlobalProxy)
7482 // Layout description.
7483 static const int kNativeContextOffset = JSObject::kHeaderSize;
7484 static const int kHashOffset = kNativeContextOffset + kPointerSize;
7485 static const int kSize = kHashOffset + kPointerSize;
7488 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7492 // Common super class for JavaScript global objects and the special
7493 // builtins global objects.
7494 class GlobalObject: public JSObject {
7496 // [builtins]: the object holding the runtime routines written in JS.
7497 DECL_ACCESSORS(builtins, JSBuiltinsObject)
7499 // [native context]: the natives corresponding to this global object.
7500 DECL_ACCESSORS(native_context, Context)
7502 // [global proxy]: the global proxy object of the context
7503 DECL_ACCESSORS(global_proxy, JSObject)
7505 DECLARE_CAST(GlobalObject)
7507 static void InvalidatePropertyCell(Handle<GlobalObject> object,
7509 // Ensure that the global object has a cell for the given property name.
7510 static Handle<PropertyCell> EnsurePropertyCell(Handle<GlobalObject> global,
7513 // Layout description.
7514 static const int kBuiltinsOffset = JSObject::kHeaderSize;
7515 static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7516 static const int kGlobalProxyOffset = kNativeContextOffset + kPointerSize;
7517 static const int kHeaderSize = kGlobalProxyOffset + kPointerSize;
7520 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7524 // JavaScript global object.
7525 class JSGlobalObject: public GlobalObject {
7527 DECLARE_CAST(JSGlobalObject)
7529 inline bool IsDetached();
7531 // Dispatched behavior.
7532 DECLARE_PRINTER(JSGlobalObject)
7533 DECLARE_VERIFIER(JSGlobalObject)
7535 // Layout description.
7536 static const int kSize = GlobalObject::kHeaderSize;
7539 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7543 // Builtins global object which holds the runtime routines written in
7545 class JSBuiltinsObject: public GlobalObject {
7547 // Accessors for the runtime routines written in JavaScript.
7548 inline Object* javascript_builtin(Builtins::JavaScript id);
7549 inline void set_javascript_builtin(Builtins::JavaScript id, Object* value);
7551 DECLARE_CAST(JSBuiltinsObject)
7553 // Dispatched behavior.
7554 DECLARE_PRINTER(JSBuiltinsObject)
7555 DECLARE_VERIFIER(JSBuiltinsObject)
7557 // Layout description. The size of the builtins object includes
7558 // room for two pointers per runtime routine written in javascript
7559 // (function and code object).
7560 static const int kJSBuiltinsCount = Builtins::id_count;
7561 static const int kJSBuiltinsOffset = GlobalObject::kHeaderSize;
7562 static const int kSize =
7563 GlobalObject::kHeaderSize + (kJSBuiltinsCount * kPointerSize);
7565 static int OffsetOfFunctionWithId(Builtins::JavaScript id) {
7566 return kJSBuiltinsOffset + id * kPointerSize;
7570 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7574 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
7575 class JSValue: public JSObject {
7577 // [value]: the object being wrapped.
7578 DECL_ACCESSORS(value, Object)
7580 DECLARE_CAST(JSValue)
7582 // Dispatched behavior.
7583 DECLARE_PRINTER(JSValue)
7584 DECLARE_VERIFIER(JSValue)
7586 // Layout description.
7587 static const int kValueOffset = JSObject::kHeaderSize;
7588 static const int kSize = kValueOffset + kPointerSize;
7591 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
7597 // Representation for JS date objects.
7598 class JSDate: public JSObject {
7600 // If one component is NaN, all of them are, indicating a NaN time value.
7601 // [value]: the time value.
7602 DECL_ACCESSORS(value, Object)
7603 // [year]: caches year. Either undefined, smi, or NaN.
7604 DECL_ACCESSORS(year, Object)
7605 // [month]: caches month. Either undefined, smi, or NaN.
7606 DECL_ACCESSORS(month, Object)
7607 // [day]: caches day. Either undefined, smi, or NaN.
7608 DECL_ACCESSORS(day, Object)
7609 // [weekday]: caches day of week. Either undefined, smi, or NaN.
7610 DECL_ACCESSORS(weekday, Object)
7611 // [hour]: caches hours. Either undefined, smi, or NaN.
7612 DECL_ACCESSORS(hour, Object)
7613 // [min]: caches minutes. Either undefined, smi, or NaN.
7614 DECL_ACCESSORS(min, Object)
7615 // [sec]: caches seconds. Either undefined, smi, or NaN.
7616 DECL_ACCESSORS(sec, Object)
7617 // [cache stamp]: sample of the date cache stamp at the
7618 // moment when chached fields were cached.
7619 DECL_ACCESSORS(cache_stamp, Object)
7621 DECLARE_CAST(JSDate)
7623 // Returns the date field with the specified index.
7624 // See FieldIndex for the list of date fields.
7625 static Object* GetField(Object* date, Smi* index);
7627 void SetValue(Object* value, bool is_value_nan);
7630 // Dispatched behavior.
7631 DECLARE_PRINTER(JSDate)
7632 DECLARE_VERIFIER(JSDate)
7634 // The order is important. It must be kept in sync with date macros
7645 kFirstUncachedField,
7646 kMillisecond = kFirstUncachedField,
7650 kYearUTC = kFirstUTCField,
7663 // Layout description.
7664 static const int kValueOffset = JSObject::kHeaderSize;
7665 static const int kYearOffset = kValueOffset + kPointerSize;
7666 static const int kMonthOffset = kYearOffset + kPointerSize;
7667 static const int kDayOffset = kMonthOffset + kPointerSize;
7668 static const int kWeekdayOffset = kDayOffset + kPointerSize;
7669 static const int kHourOffset = kWeekdayOffset + kPointerSize;
7670 static const int kMinOffset = kHourOffset + kPointerSize;
7671 static const int kSecOffset = kMinOffset + kPointerSize;
7672 static const int kCacheStampOffset = kSecOffset + kPointerSize;
7673 static const int kSize = kCacheStampOffset + kPointerSize;
7676 inline Object* DoGetField(FieldIndex index);
7678 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
7680 // Computes and caches the cacheable fields of the date.
7681 inline void SetCachedFields(int64_t local_time_ms, DateCache* date_cache);
7684 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
7688 // Representation of message objects used for error reporting through
7689 // the API. The messages are formatted in JavaScript so this object is
7690 // a real JavaScript object. The information used for formatting the
7691 // error messages are not directly accessible from JavaScript to
7692 // prevent leaking information to user code called during error
7694 class JSMessageObject: public JSObject {
7696 // [type]: the type of error message.
7697 inline int type() const;
7698 inline void set_type(int value);
7700 // [arguments]: the arguments for formatting the error message.
7701 DECL_ACCESSORS(argument, Object)
7703 // [script]: the script from which the error message originated.
7704 DECL_ACCESSORS(script, Object)
7706 // [stack_frames]: an array of stack frames for this error object.
7707 DECL_ACCESSORS(stack_frames, Object)
7709 // [start_position]: the start position in the script for the error message.
7710 inline int start_position() const;
7711 inline void set_start_position(int value);
7713 // [end_position]: the end position in the script for the error message.
7714 inline int end_position() const;
7715 inline void set_end_position(int value);
7717 DECLARE_CAST(JSMessageObject)
7719 // Dispatched behavior.
7720 DECLARE_PRINTER(JSMessageObject)
7721 DECLARE_VERIFIER(JSMessageObject)
7723 // Layout description.
7724 static const int kTypeOffset = JSObject::kHeaderSize;
7725 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
7726 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
7727 static const int kStackFramesOffset = kScriptOffset + kPointerSize;
7728 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
7729 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
7730 static const int kSize = kEndPositionOffset + kPointerSize;
7732 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
7733 kStackFramesOffset + kPointerSize,
7734 kSize> BodyDescriptor;
7738 // Regular expressions
7739 // The regular expression holds a single reference to a FixedArray in
7740 // the kDataOffset field.
7741 // The FixedArray contains the following data:
7742 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
7743 // - reference to the original source string
7744 // - reference to the original flag string
7745 // If it is an atom regexp
7746 // - a reference to a literal string to search for
7747 // If it is an irregexp regexp:
7748 // - a reference to code for Latin1 inputs (bytecode or compiled), or a smi
7749 // used for tracking the last usage (used for code flushing).
7750 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
7751 // used for tracking the last usage (used for code flushing)..
7752 // - max number of registers used by irregexp implementations.
7753 // - number of capture registers (output values) of the regexp.
7754 class JSRegExp: public JSObject {
7757 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
7758 // ATOM: A simple string to match against using an indexOf operation.
7759 // IRREGEXP: Compiled with Irregexp.
7760 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
7761 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
7768 UNICODE_ESCAPES = 16
7773 explicit Flags(uint32_t value) : value_(value) { }
7774 bool is_global() { return (value_ & GLOBAL) != 0; }
7775 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
7776 bool is_multiline() { return (value_ & MULTILINE) != 0; }
7777 bool is_sticky() { return (value_ & STICKY) != 0; }
7778 bool is_unicode() { return (value_ & UNICODE_ESCAPES) != 0; }
7779 uint32_t value() { return value_; }
7784 DECL_ACCESSORS(data, Object)
7786 inline Type TypeTag();
7787 inline int CaptureCount();
7788 inline Flags GetFlags();
7789 inline String* Pattern();
7790 inline Object* DataAt(int index);
7791 // Set implementation data after the object has been prepared.
7792 inline void SetDataAt(int index, Object* value);
7794 static int code_index(bool is_latin1) {
7796 return kIrregexpLatin1CodeIndex;
7798 return kIrregexpUC16CodeIndex;
7802 static int saved_code_index(bool is_latin1) {
7804 return kIrregexpLatin1CodeSavedIndex;
7806 return kIrregexpUC16CodeSavedIndex;
7810 DECLARE_CAST(JSRegExp)
7812 // Dispatched behavior.
7813 DECLARE_VERIFIER(JSRegExp)
7815 static const int kDataOffset = JSObject::kHeaderSize;
7816 static const int kSize = kDataOffset + kPointerSize;
7818 // Indices in the data array.
7819 static const int kTagIndex = 0;
7820 static const int kSourceIndex = kTagIndex + 1;
7821 static const int kFlagsIndex = kSourceIndex + 1;
7822 static const int kDataIndex = kFlagsIndex + 1;
7823 // The data fields are used in different ways depending on the
7824 // value of the tag.
7825 // Atom regexps (literal strings).
7826 static const int kAtomPatternIndex = kDataIndex;
7828 static const int kAtomDataSize = kAtomPatternIndex + 1;
7830 // Irregexp compiled code or bytecode for Latin1. If compilation
7831 // fails, this fields hold an exception object that should be
7832 // thrown if the regexp is used again.
7833 static const int kIrregexpLatin1CodeIndex = kDataIndex;
7834 // Irregexp compiled code or bytecode for UC16. If compilation
7835 // fails, this fields hold an exception object that should be
7836 // thrown if the regexp is used again.
7837 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
7839 // Saved instance of Irregexp compiled code or bytecode for Latin1 that
7840 // is a potential candidate for flushing.
7841 static const int kIrregexpLatin1CodeSavedIndex = kDataIndex + 2;
7842 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
7843 // a potential candidate for flushing.
7844 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
7846 // Maximal number of registers used by either Latin1 or UC16.
7847 // Only used to check that there is enough stack space
7848 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
7849 // Number of captures in the compiled regexp.
7850 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
7852 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
7854 // Offsets directly into the data fixed array.
7855 static const int kDataTagOffset =
7856 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
7857 static const int kDataOneByteCodeOffset =
7858 FixedArray::kHeaderSize + kIrregexpLatin1CodeIndex * kPointerSize;
7859 static const int kDataUC16CodeOffset =
7860 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
7861 static const int kIrregexpCaptureCountOffset =
7862 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
7864 // In-object fields.
7865 static const int kSourceFieldIndex = 0;
7866 static const int kGlobalFieldIndex = 1;
7867 static const int kIgnoreCaseFieldIndex = 2;
7868 static const int kMultilineFieldIndex = 3;
7869 static const int kLastIndexFieldIndex = 4;
7870 static const int kInObjectFieldCount = 5;
7872 // The uninitialized value for a regexp code object.
7873 static const int kUninitializedValue = -1;
7875 // The compilation error value for the regexp code object. The real error
7876 // object is in the saved code field.
7877 static const int kCompilationErrorValue = -2;
7879 // When we store the sweep generation at which we moved the code from the
7880 // code index to the saved code index we mask it of to be in the [0:255]
7882 static const int kCodeAgeMask = 0xff;
7886 class CompilationCacheShape : public BaseShape<HashTableKey*> {
7888 static inline bool IsMatch(HashTableKey* key, Object* value) {
7889 return key->IsMatch(value);
7892 static inline uint32_t Hash(HashTableKey* key) {
7896 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7897 return key->HashForObject(object);
7900 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7902 static const int kPrefixSize = 0;
7903 static const int kEntrySize = 2;
7907 // This cache is used in two different variants. For regexp caching, it simply
7908 // maps identifying info of the regexp to the cached regexp object. Scripts and
7909 // eval code only gets cached after a second probe for the code object. To do
7910 // so, on first "put" only a hash identifying the source is entered into the
7911 // cache, mapping it to a lifetime count of the hash. On each call to Age all
7912 // such lifetimes get reduced, and removed once they reach zero. If a second put
7913 // is called while such a hash is live in the cache, the hash gets replaced by
7914 // an actual cache entry. Age also removes stale live entries from the cache.
7915 // Such entries are identified by SharedFunctionInfos pointing to either the
7916 // recompilation stub, or to "old" code. This avoids memory leaks due to
7917 // premature caching of scripts and eval strings that are never needed later.
7918 class CompilationCacheTable: public HashTable<CompilationCacheTable,
7919 CompilationCacheShape,
7922 // Find cached value for a string key, otherwise return null.
7923 Handle<Object> Lookup(
7924 Handle<String> src, Handle<Context> context, LanguageMode language_mode);
7925 Handle<Object> LookupEval(
7926 Handle<String> src, Handle<SharedFunctionInfo> shared,
7927 LanguageMode language_mode, int scope_position);
7928 Handle<Object> LookupRegExp(Handle<String> source, JSRegExp::Flags flags);
7929 static Handle<CompilationCacheTable> Put(
7930 Handle<CompilationCacheTable> cache, Handle<String> src,
7931 Handle<Context> context, LanguageMode language_mode,
7932 Handle<Object> value);
7933 static Handle<CompilationCacheTable> PutEval(
7934 Handle<CompilationCacheTable> cache, Handle<String> src,
7935 Handle<SharedFunctionInfo> context, Handle<SharedFunctionInfo> value,
7936 int scope_position);
7937 static Handle<CompilationCacheTable> PutRegExp(
7938 Handle<CompilationCacheTable> cache, Handle<String> src,
7939 JSRegExp::Flags flags, Handle<FixedArray> value);
7940 void Remove(Object* value);
7942 static const int kHashGenerations = 10;
7944 DECLARE_CAST(CompilationCacheTable)
7947 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
7951 class CodeCache: public Struct {
7953 DECL_ACCESSORS(default_cache, FixedArray)
7954 DECL_ACCESSORS(normal_type_cache, Object)
7956 // Add the code object to the cache.
7958 Handle<CodeCache> cache, Handle<Name> name, Handle<Code> code);
7960 // Lookup code object in the cache. Returns code object if found and undefined
7962 Object* Lookup(Name* name, Code::Flags flags);
7964 // Get the internal index of a code object in the cache. Returns -1 if the
7965 // code object is not in that cache. This index can be used to later call
7966 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
7968 int GetIndex(Object* name, Code* code);
7970 // Remove an object from the cache with the provided internal index.
7971 void RemoveByIndex(Object* name, Code* code, int index);
7973 DECLARE_CAST(CodeCache)
7975 // Dispatched behavior.
7976 DECLARE_PRINTER(CodeCache)
7977 DECLARE_VERIFIER(CodeCache)
7979 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
7980 static const int kNormalTypeCacheOffset =
7981 kDefaultCacheOffset + kPointerSize;
7982 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
7985 static void UpdateDefaultCache(
7986 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7987 static void UpdateNormalTypeCache(
7988 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7989 Object* LookupDefaultCache(Name* name, Code::Flags flags);
7990 Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
7992 // Code cache layout of the default cache. Elements are alternating name and
7993 // code objects for non normal load/store/call IC's.
7994 static const int kCodeCacheEntrySize = 2;
7995 static const int kCodeCacheEntryNameOffset = 0;
7996 static const int kCodeCacheEntryCodeOffset = 1;
7998 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
8002 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
8004 static inline bool IsMatch(HashTableKey* key, Object* value) {
8005 return key->IsMatch(value);
8008 static inline uint32_t Hash(HashTableKey* key) {
8012 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
8013 return key->HashForObject(object);
8016 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
8018 static const int kPrefixSize = 0;
8019 static const int kEntrySize = 2;
8023 class CodeCacheHashTable: public HashTable<CodeCacheHashTable,
8024 CodeCacheHashTableShape,
8027 Object* Lookup(Name* name, Code::Flags flags);
8028 static Handle<CodeCacheHashTable> Put(
8029 Handle<CodeCacheHashTable> table,
8033 int GetIndex(Name* name, Code::Flags flags);
8034 void RemoveByIndex(int index);
8036 DECLARE_CAST(CodeCacheHashTable)
8038 // Initial size of the fixed array backing the hash table.
8039 static const int kInitialSize = 64;
8042 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
8046 class PolymorphicCodeCache: public Struct {
8048 DECL_ACCESSORS(cache, Object)
8050 static void Update(Handle<PolymorphicCodeCache> cache,
8051 MapHandleList* maps,
8056 // Returns an undefined value if the entry is not found.
8057 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
8059 DECLARE_CAST(PolymorphicCodeCache)
8061 // Dispatched behavior.
8062 DECLARE_PRINTER(PolymorphicCodeCache)
8063 DECLARE_VERIFIER(PolymorphicCodeCache)
8065 static const int kCacheOffset = HeapObject::kHeaderSize;
8066 static const int kSize = kCacheOffset + kPointerSize;
8069 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
8073 class PolymorphicCodeCacheHashTable
8074 : public HashTable<PolymorphicCodeCacheHashTable,
8075 CodeCacheHashTableShape,
8078 Object* Lookup(MapHandleList* maps, int code_kind);
8080 static Handle<PolymorphicCodeCacheHashTable> Put(
8081 Handle<PolymorphicCodeCacheHashTable> hash_table,
8082 MapHandleList* maps,
8086 DECLARE_CAST(PolymorphicCodeCacheHashTable)
8088 static const int kInitialSize = 64;
8090 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
8094 class TypeFeedbackInfo: public Struct {
8096 inline int ic_total_count();
8097 inline void set_ic_total_count(int count);
8099 inline int ic_with_type_info_count();
8100 inline void change_ic_with_type_info_count(int delta);
8102 inline int ic_generic_count();
8103 inline void change_ic_generic_count(int delta);
8105 inline void initialize_storage();
8107 inline void change_own_type_change_checksum();
8108 inline int own_type_change_checksum();
8110 inline void set_inlined_type_change_checksum(int checksum);
8111 inline bool matches_inlined_type_change_checksum(int checksum);
8113 DECLARE_CAST(TypeFeedbackInfo)
8115 // Dispatched behavior.
8116 DECLARE_PRINTER(TypeFeedbackInfo)
8117 DECLARE_VERIFIER(TypeFeedbackInfo)
8119 static const int kStorage1Offset = HeapObject::kHeaderSize;
8120 static const int kStorage2Offset = kStorage1Offset + kPointerSize;
8121 static const int kStorage3Offset = kStorage2Offset + kPointerSize;
8122 static const int kSize = kStorage3Offset + kPointerSize;
8125 static const int kTypeChangeChecksumBits = 7;
8127 class ICTotalCountField: public BitField<int, 0,
8128 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
8129 class OwnTypeChangeChecksum: public BitField<int,
8130 kSmiValueSize - kTypeChangeChecksumBits,
8131 kTypeChangeChecksumBits> {}; // NOLINT
8132 class ICsWithTypeInfoCountField: public BitField<int, 0,
8133 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
8134 class InlinedTypeChangeChecksum: public BitField<int,
8135 kSmiValueSize - kTypeChangeChecksumBits,
8136 kTypeChangeChecksumBits> {}; // NOLINT
8138 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
8142 enum AllocationSiteMode {
8143 DONT_TRACK_ALLOCATION_SITE,
8144 TRACK_ALLOCATION_SITE,
8145 LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
8149 class AllocationSite: public Struct {
8151 static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
8152 static const double kPretenureRatio;
8153 static const int kPretenureMinimumCreated = 100;
8155 // Values for pretenure decision field.
8156 enum PretenureDecision {
8162 kLastPretenureDecisionValue = kZombie
8165 const char* PretenureDecisionName(PretenureDecision decision);
8167 DECL_ACCESSORS(transition_info, Object)
8168 // nested_site threads a list of sites that represent nested literals
8169 // walked in a particular order. So [[1, 2], 1, 2] will have one
8170 // nested_site, but [[1, 2], 3, [4]] will have a list of two.
8171 DECL_ACCESSORS(nested_site, Object)
8172 DECL_ACCESSORS(pretenure_data, Smi)
8173 DECL_ACCESSORS(pretenure_create_count, Smi)
8174 DECL_ACCESSORS(dependent_code, DependentCode)
8175 DECL_ACCESSORS(weak_next, Object)
8177 inline void Initialize();
8179 // This method is expensive, it should only be called for reporting.
8180 bool IsNestedSite();
8182 // transition_info bitfields, for constructed array transition info.
8183 class ElementsKindBits: public BitField<ElementsKind, 0, 15> {};
8184 class UnusedBits: public BitField<int, 15, 14> {};
8185 class DoNotInlineBit: public BitField<bool, 29, 1> {};
8187 // Bitfields for pretenure_data
8188 class MementoFoundCountBits: public BitField<int, 0, 26> {};
8189 class PretenureDecisionBits: public BitField<PretenureDecision, 26, 3> {};
8190 class DeoptDependentCodeBit: public BitField<bool, 29, 1> {};
8191 STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
8193 // Increments the mementos found counter and returns true when the first
8194 // memento was found for a given allocation site.
8195 inline bool IncrementMementoFoundCount();
8197 inline void IncrementMementoCreateCount();
8199 PretenureFlag GetPretenureMode();
8201 void ResetPretenureDecision();
8203 PretenureDecision pretenure_decision() {
8204 int value = pretenure_data()->value();
8205 return PretenureDecisionBits::decode(value);
8208 void set_pretenure_decision(PretenureDecision decision) {
8209 int value = pretenure_data()->value();
8211 Smi::FromInt(PretenureDecisionBits::update(value, decision)),
8212 SKIP_WRITE_BARRIER);
8215 bool deopt_dependent_code() {
8216 int value = pretenure_data()->value();
8217 return DeoptDependentCodeBit::decode(value);
8220 void set_deopt_dependent_code(bool deopt) {
8221 int value = pretenure_data()->value();
8223 Smi::FromInt(DeoptDependentCodeBit::update(value, deopt)),
8224 SKIP_WRITE_BARRIER);
8227 int memento_found_count() {
8228 int value = pretenure_data()->value();
8229 return MementoFoundCountBits::decode(value);
8232 inline void set_memento_found_count(int count);
8234 int memento_create_count() {
8235 return pretenure_create_count()->value();
8238 void set_memento_create_count(int count) {
8239 set_pretenure_create_count(Smi::FromInt(count), SKIP_WRITE_BARRIER);
8242 // The pretenuring decision is made during gc, and the zombie state allows
8243 // us to recognize when an allocation site is just being kept alive because
8244 // a later traversal of new space may discover AllocationMementos that point
8245 // to this AllocationSite.
8247 return pretenure_decision() == kZombie;
8250 bool IsMaybeTenure() {
8251 return pretenure_decision() == kMaybeTenure;
8254 inline void MarkZombie();
8256 inline bool MakePretenureDecision(PretenureDecision current_decision,
8258 bool maximum_size_scavenge);
8260 inline bool DigestPretenuringFeedback(bool maximum_size_scavenge);
8262 ElementsKind GetElementsKind() {
8263 DCHECK(!SitePointsToLiteral());
8264 int value = Smi::cast(transition_info())->value();
8265 return ElementsKindBits::decode(value);
8268 void SetElementsKind(ElementsKind kind) {
8269 int value = Smi::cast(transition_info())->value();
8270 set_transition_info(Smi::FromInt(ElementsKindBits::update(value, kind)),
8271 SKIP_WRITE_BARRIER);
8274 bool CanInlineCall() {
8275 int value = Smi::cast(transition_info())->value();
8276 return DoNotInlineBit::decode(value) == 0;
8279 void SetDoNotInlineCall() {
8280 int value = Smi::cast(transition_info())->value();
8281 set_transition_info(Smi::FromInt(DoNotInlineBit::update(value, true)),
8282 SKIP_WRITE_BARRIER);
8285 bool SitePointsToLiteral() {
8286 // If transition_info is a smi, then it represents an ElementsKind
8287 // for a constructed array. Otherwise, it must be a boilerplate
8288 // for an object or array literal.
8289 return transition_info()->IsJSArray() || transition_info()->IsJSObject();
8292 static void DigestTransitionFeedback(Handle<AllocationSite> site,
8293 ElementsKind to_kind);
8295 DECLARE_PRINTER(AllocationSite)
8296 DECLARE_VERIFIER(AllocationSite)
8298 DECLARE_CAST(AllocationSite)
8299 static inline AllocationSiteMode GetMode(
8300 ElementsKind boilerplate_elements_kind);
8301 static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
8302 static inline bool CanTrack(InstanceType type);
8304 static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
8305 static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
8306 static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
8307 static const int kPretenureCreateCountOffset =
8308 kPretenureDataOffset + kPointerSize;
8309 static const int kDependentCodeOffset =
8310 kPretenureCreateCountOffset + kPointerSize;
8311 static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
8312 static const int kSize = kWeakNextOffset + kPointerSize;
8314 // During mark compact we need to take special care for the dependent code
8316 static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
8317 static const int kPointerFieldsEndOffset = kWeakNextOffset;
8319 // For other visitors, use the fixed body descriptor below.
8320 typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
8321 kDependentCodeOffset + kPointerSize,
8322 kSize> BodyDescriptor;
8325 bool PretenuringDecisionMade() {
8326 return pretenure_decision() != kUndecided;
8329 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
8333 class AllocationMemento: public Struct {
8335 static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
8336 static const int kSize = kAllocationSiteOffset + kPointerSize;
8338 DECL_ACCESSORS(allocation_site, Object)
8341 return allocation_site()->IsAllocationSite() &&
8342 !AllocationSite::cast(allocation_site())->IsZombie();
8344 AllocationSite* GetAllocationSite() {
8346 return AllocationSite::cast(allocation_site());
8349 DECLARE_PRINTER(AllocationMemento)
8350 DECLARE_VERIFIER(AllocationMemento)
8352 DECLARE_CAST(AllocationMemento)
8355 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
8359 // Representation of a slow alias as part of a sloppy arguments objects.
8360 // For fast aliases (if HasSloppyArgumentsElements()):
8361 // - the parameter map contains an index into the context
8362 // - all attributes of the element have default values
8363 // For slow aliases (if HasDictionaryArgumentsElements()):
8364 // - the parameter map contains no fast alias mapping (i.e. the hole)
8365 // - this struct (in the slow backing store) contains an index into the context
8366 // - all attributes are available as part if the property details
8367 class AliasedArgumentsEntry: public Struct {
8369 inline int aliased_context_slot() const;
8370 inline void set_aliased_context_slot(int count);
8372 DECLARE_CAST(AliasedArgumentsEntry)
8374 // Dispatched behavior.
8375 DECLARE_PRINTER(AliasedArgumentsEntry)
8376 DECLARE_VERIFIER(AliasedArgumentsEntry)
8378 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
8379 static const int kSize = kAliasedContextSlot + kPointerSize;
8382 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
8386 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
8387 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
8390 class StringHasher {
8392 explicit inline StringHasher(int length, uint32_t seed);
8394 template <typename schar>
8395 static inline uint32_t HashSequentialString(const schar* chars,
8399 // Reads all the data, even for long strings and computes the utf16 length.
8400 static uint32_t ComputeUtf8Hash(Vector<const char> chars,
8402 int* utf16_length_out);
8404 // Calculated hash value for a string consisting of 1 to
8405 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
8406 // value is represented decimal value.
8407 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
8409 // No string is allowed to have a hash of zero. That value is reserved
8410 // for internal properties. If the hash calculation yields zero then we
8412 static const int kZeroHash = 27;
8414 // Reusable parts of the hashing algorithm.
8415 INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
8416 INLINE(static uint32_t GetHashCore(uint32_t running_hash));
8417 INLINE(static uint32_t ComputeRunningHash(uint32_t running_hash,
8418 const uc16* chars, int length));
8419 INLINE(static uint32_t ComputeRunningHashOneByte(uint32_t running_hash,
8424 // Returns the value to store in the hash field of a string with
8425 // the given length and contents.
8426 uint32_t GetHashField();
8427 // Returns true if the hash of this string can be computed without
8428 // looking at the contents.
8429 inline bool has_trivial_hash();
8430 // Adds a block of characters to the hash.
8431 template<typename Char>
8432 inline void AddCharacters(const Char* chars, int len);
8435 // Add a character to the hash.
8436 inline void AddCharacter(uint16_t c);
8437 // Update index. Returns true if string is still an index.
8438 inline bool UpdateIndex(uint16_t c);
8441 uint32_t raw_running_hash_;
8442 uint32_t array_index_;
8443 bool is_array_index_;
8444 bool is_first_char_;
8445 DISALLOW_COPY_AND_ASSIGN(StringHasher);
8449 class IteratingStringHasher : public StringHasher {
8451 static inline uint32_t Hash(String* string, uint32_t seed);
8452 inline void VisitOneByteString(const uint8_t* chars, int length);
8453 inline void VisitTwoByteString(const uint16_t* chars, int length);
8456 inline IteratingStringHasher(int len, uint32_t seed)
8457 : StringHasher(len, seed) {}
8458 void VisitConsString(ConsString* cons_string);
8459 DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher);
8463 // The characteristics of a string are stored in its map. Retrieving these
8464 // few bits of information is moderately expensive, involving two memory
8465 // loads where the second is dependent on the first. To improve efficiency
8466 // the shape of the string is given its own class so that it can be retrieved
8467 // once and used for several string operations. A StringShape is small enough
8468 // to be passed by value and is immutable, but be aware that flattening a
8469 // string can potentially alter its shape. Also be aware that a GC caused by
8470 // something else can alter the shape of a string due to ConsString
8471 // shortcutting. Keeping these restrictions in mind has proven to be error-
8472 // prone and so we no longer put StringShapes in variables unless there is a
8473 // concrete performance benefit at that particular point in the code.
8474 class StringShape BASE_EMBEDDED {
8476 inline explicit StringShape(const String* s);
8477 inline explicit StringShape(Map* s);
8478 inline explicit StringShape(InstanceType t);
8479 inline bool IsSequential();
8480 inline bool IsExternal();
8481 inline bool IsCons();
8482 inline bool IsSliced();
8483 inline bool IsIndirect();
8484 inline bool IsExternalOneByte();
8485 inline bool IsExternalTwoByte();
8486 inline bool IsSequentialOneByte();
8487 inline bool IsSequentialTwoByte();
8488 inline bool IsInternalized();
8489 inline StringRepresentationTag representation_tag();
8490 inline uint32_t encoding_tag();
8491 inline uint32_t full_representation_tag();
8492 inline uint32_t size_tag();
8494 inline uint32_t type() { return type_; }
8495 inline void invalidate() { valid_ = false; }
8496 inline bool valid() { return valid_; }
8498 inline void invalidate() { }
8504 inline void set_valid() { valid_ = true; }
8507 inline void set_valid() { }
8512 // The Name abstract class captures anything that can be used as a property
8513 // name, i.e., strings and symbols. All names store a hash value.
8514 class Name: public HeapObject {
8516 // Get and set the hash field of the name.
8517 inline uint32_t hash_field();
8518 inline void set_hash_field(uint32_t value);
8520 // Tells whether the hash code has been computed.
8521 inline bool HasHashCode();
8523 // Returns a hash value used for the property table
8524 inline uint32_t Hash();
8526 // Equality operations.
8527 inline bool Equals(Name* other);
8528 inline static bool Equals(Handle<Name> one, Handle<Name> two);
8531 inline bool AsArrayIndex(uint32_t* index);
8533 // If the name is private, it can only name own properties.
8534 inline bool IsPrivate();
8536 // If the name is a non-flat string, this method returns a flat version of the
8537 // string. Otherwise it'll just return the input.
8538 static inline Handle<Name> Flatten(Handle<Name> name,
8539 PretenureFlag pretenure = NOT_TENURED);
8543 DECLARE_PRINTER(Name)
8545 void NameShortPrint();
8546 int NameShortPrint(Vector<char> str);
8549 // Layout description.
8550 static const int kHashFieldSlot = HeapObject::kHeaderSize;
8551 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
8552 static const int kHashFieldOffset = kHashFieldSlot;
8554 static const int kHashFieldOffset = kHashFieldSlot + kIntSize;
8556 static const int kSize = kHashFieldSlot + kPointerSize;
8558 // Mask constant for checking if a name has a computed hash code
8559 // and if it is a string that is an array index. The least significant bit
8560 // indicates whether a hash code has been computed. If the hash code has
8561 // been computed the 2nd bit tells whether the string can be used as an
8563 static const int kHashNotComputedMask = 1;
8564 static const int kIsNotArrayIndexMask = 1 << 1;
8565 static const int kNofHashBitFields = 2;
8567 // Shift constant retrieving hash code from hash field.
8568 static const int kHashShift = kNofHashBitFields;
8570 // Only these bits are relevant in the hash, since the top two are shifted
8572 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8574 // Array index strings this short can keep their index in the hash field.
8575 static const int kMaxCachedArrayIndexLength = 7;
8577 // For strings which are array indexes the hash value has the string length
8578 // mixed into the hash, mainly to avoid a hash value of zero which would be
8579 // the case for the string '0'. 24 bits are used for the array index value.
8580 static const int kArrayIndexValueBits = 24;
8581 static const int kArrayIndexLengthBits =
8582 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8584 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8586 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8587 kArrayIndexValueBits> {}; // NOLINT
8588 class ArrayIndexLengthBits : public BitField<unsigned int,
8589 kNofHashBitFields + kArrayIndexValueBits,
8590 kArrayIndexLengthBits> {}; // NOLINT
8592 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8593 // could use a mask to test if the length of string is less than or equal to
8594 // kMaxCachedArrayIndexLength.
8595 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8597 static const unsigned int kContainsCachedArrayIndexMask =
8598 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8599 << ArrayIndexLengthBits::kShift) |
8600 kIsNotArrayIndexMask;
8602 // Value of empty hash field indicating that the hash is not computed.
8603 static const int kEmptyHashField =
8604 kIsNotArrayIndexMask | kHashNotComputedMask;
8607 static inline bool IsHashFieldComputed(uint32_t field);
8610 DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8615 class Symbol: public Name {
8617 // [name]: The print name of a symbol, or undefined if none.
8618 DECL_ACCESSORS(name, Object)
8620 DECL_ACCESSORS(flags, Smi)
8622 // [is_private]: Whether this is a private symbol. Private symbols can only
8623 // be used to designate own properties of objects.
8624 DECL_BOOLEAN_ACCESSORS(is_private)
8626 DECLARE_CAST(Symbol)
8628 // Dispatched behavior.
8629 DECLARE_PRINTER(Symbol)
8630 DECLARE_VERIFIER(Symbol)
8632 // Layout description.
8633 static const int kNameOffset = Name::kSize;
8634 static const int kFlagsOffset = kNameOffset + kPointerSize;
8635 static const int kSize = kFlagsOffset + kPointerSize;
8637 typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
8639 void SymbolShortPrint(std::ostream& os);
8642 static const int kPrivateBit = 0;
8644 const char* PrivateSymbolToName() const;
8647 friend class Name; // For PrivateSymbolToName.
8650 DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
8656 // The String abstract class captures JavaScript string values:
8659 // 4.3.16 String Value
8660 // A string value is a member of the type String and is a finite
8661 // ordered sequence of zero or more 16-bit unsigned integer values.
8663 // All string values have a length field.
8664 class String: public Name {
8666 enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
8668 // Array index strings this short can keep their index in the hash field.
8669 static const int kMaxCachedArrayIndexLength = 7;
8671 // For strings which are array indexes the hash value has the string length
8672 // mixed into the hash, mainly to avoid a hash value of zero which would be
8673 // the case for the string '0'. 24 bits are used for the array index value.
8674 static const int kArrayIndexValueBits = 24;
8675 static const int kArrayIndexLengthBits =
8676 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8678 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8680 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8681 kArrayIndexValueBits> {}; // NOLINT
8682 class ArrayIndexLengthBits : public BitField<unsigned int,
8683 kNofHashBitFields + kArrayIndexValueBits,
8684 kArrayIndexLengthBits> {}; // NOLINT
8686 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8687 // could use a mask to test if the length of string is less than or equal to
8688 // kMaxCachedArrayIndexLength.
8689 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8691 static const unsigned int kContainsCachedArrayIndexMask =
8692 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8693 << ArrayIndexLengthBits::kShift) |
8694 kIsNotArrayIndexMask;
8696 class SubStringRange {
8698 explicit SubStringRange(String* string, int first = 0, int length = -1)
8701 length_(length == -1 ? string->length() : length) {}
8703 inline iterator begin();
8704 inline iterator end();
8712 // Representation of the flat content of a String.
8713 // A non-flat string doesn't have flat content.
8714 // A flat string has content that's encoded as a sequence of either
8715 // one-byte chars or two-byte UC16.
8716 // Returned by String::GetFlatContent().
8719 // Returns true if the string is flat and this structure contains content.
8720 bool IsFlat() { return state_ != NON_FLAT; }
8721 // Returns true if the structure contains one-byte content.
8722 bool IsOneByte() { return state_ == ONE_BYTE; }
8723 // Returns true if the structure contains two-byte content.
8724 bool IsTwoByte() { return state_ == TWO_BYTE; }
8726 // Return the one byte content of the string. Only use if IsOneByte()
8728 Vector<const uint8_t> ToOneByteVector() {
8729 DCHECK_EQ(ONE_BYTE, state_);
8730 return Vector<const uint8_t>(onebyte_start, length_);
8732 // Return the two-byte content of the string. Only use if IsTwoByte()
8734 Vector<const uc16> ToUC16Vector() {
8735 DCHECK_EQ(TWO_BYTE, state_);
8736 return Vector<const uc16>(twobyte_start, length_);
8740 DCHECK(i < length_);
8741 DCHECK(state_ != NON_FLAT);
8742 if (state_ == ONE_BYTE) return onebyte_start[i];
8743 return twobyte_start[i];
8746 bool UsesSameString(const FlatContent& other) const {
8747 return onebyte_start == other.onebyte_start;
8751 enum State { NON_FLAT, ONE_BYTE, TWO_BYTE };
8753 // Constructors only used by String::GetFlatContent().
8754 explicit FlatContent(const uint8_t* start, int length)
8755 : onebyte_start(start), length_(length), state_(ONE_BYTE) {}
8756 explicit FlatContent(const uc16* start, int length)
8757 : twobyte_start(start), length_(length), state_(TWO_BYTE) { }
8758 FlatContent() : onebyte_start(NULL), length_(0), state_(NON_FLAT) { }
8761 const uint8_t* onebyte_start;
8762 const uc16* twobyte_start;
8767 friend class String;
8768 friend class IterableSubString;
8771 template <typename Char>
8772 INLINE(Vector<const Char> GetCharVector());
8774 // Get and set the length of the string.
8775 inline int length() const;
8776 inline void set_length(int value);
8778 // Get and set the length of the string using acquire loads and release
8780 inline int synchronized_length() const;
8781 inline void synchronized_set_length(int value);
8783 // Returns whether this string has only one-byte chars, i.e. all of them can
8784 // be one-byte encoded. This might be the case even if the string is
8785 // two-byte. Such strings may appear when the embedder prefers
8786 // two-byte external representations even for one-byte data.
8787 inline bool IsOneByteRepresentation() const;
8788 inline bool IsTwoByteRepresentation() const;
8790 // Cons and slices have an encoding flag that may not represent the actual
8791 // encoding of the underlying string. This is taken into account here.
8792 // Requires: this->IsFlat()
8793 inline bool IsOneByteRepresentationUnderneath();
8794 inline bool IsTwoByteRepresentationUnderneath();
8796 // NOTE: this should be considered only a hint. False negatives are
8798 inline bool HasOnlyOneByteChars();
8800 // Get and set individual two byte chars in the string.
8801 inline void Set(int index, uint16_t value);
8802 // Get individual two byte char in the string. Repeated calls
8803 // to this method are not efficient unless the string is flat.
8804 INLINE(uint16_t Get(int index));
8806 // Flattens the string. Checks first inline to see if it is
8807 // necessary. Does nothing if the string is not a cons string.
8808 // Flattening allocates a sequential string with the same data as
8809 // the given string and mutates the cons string to a degenerate
8810 // form, where the first component is the new sequential string and
8811 // the second component is the empty string. If allocation fails,
8812 // this function returns a failure. If flattening succeeds, this
8813 // function returns the sequential string that is now the first
8814 // component of the cons string.
8816 // Degenerate cons strings are handled specially by the garbage
8817 // collector (see IsShortcutCandidate).
8819 static inline Handle<String> Flatten(Handle<String> string,
8820 PretenureFlag pretenure = NOT_TENURED);
8822 // Tries to return the content of a flat string as a structure holding either
8823 // a flat vector of char or of uc16.
8824 // If the string isn't flat, and therefore doesn't have flat content, the
8825 // returned structure will report so, and can't provide a vector of either
8827 FlatContent GetFlatContent();
8829 // Returns the parent of a sliced string or first part of a flat cons string.
8830 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
8831 inline String* GetUnderlying();
8833 // String equality operations.
8834 inline bool Equals(String* other);
8835 inline static bool Equals(Handle<String> one, Handle<String> two);
8836 bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
8837 bool IsOneByteEqualTo(Vector<const uint8_t> str);
8838 bool IsTwoByteEqualTo(Vector<const uc16> str);
8840 // Return a UTF8 representation of the string. The string is null
8841 // terminated but may optionally contain nulls. Length is returned
8842 // in length_output if length_output is not a null pointer The string
8843 // should be nearly flat, otherwise the performance of this method may
8844 // be very slow (quadratic in the length). 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<char> ToCString(AllowNullsFlag allow_nulls,
8849 RobustnessFlag robustness_flag,
8850 int offset, int length,
8851 int* length_output = 0);
8852 base::SmartArrayPointer<char> ToCString(
8853 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
8854 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
8855 int* length_output = 0);
8857 // Return a 16 bit Unicode representation of the string.
8858 // The string should be nearly flat, otherwise the performance of
8859 // of this method may be very bad. Setting robustness_flag to
8860 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8861 // handles unexpected data without causing assert failures and it does not
8862 // do any heap allocations. This is useful when printing stack traces.
8863 base::SmartArrayPointer<uc16> ToWideCString(
8864 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
8866 bool ComputeArrayIndex(uint32_t* index);
8869 bool MakeExternal(v8::String::ExternalStringResource* resource);
8870 bool MakeExternal(v8::String::ExternalOneByteStringResource* resource);
8873 inline bool AsArrayIndex(uint32_t* index);
8875 DECLARE_CAST(String)
8877 void PrintOn(FILE* out);
8879 // For use during stack traces. Performs rudimentary sanity check.
8882 // Dispatched behavior.
8883 void StringShortPrint(StringStream* accumulator);
8884 void PrintUC16(std::ostream& os, int start = 0, int end = -1); // NOLINT
8885 #if defined(DEBUG) || defined(OBJECT_PRINT)
8886 char* ToAsciiArray();
8888 DECLARE_PRINTER(String)
8889 DECLARE_VERIFIER(String)
8891 inline bool IsFlat();
8893 // Layout description.
8894 static const int kLengthOffset = Name::kSize;
8895 static const int kSize = kLengthOffset + kPointerSize;
8897 // Maximum number of characters to consider when trying to convert a string
8898 // value into an array index.
8899 static const int kMaxArrayIndexSize = 10;
8900 STATIC_ASSERT(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
8903 static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
8904 static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
8905 static const int kMaxUtf16CodeUnit = 0xffff;
8906 static const uint32_t kMaxUtf16CodeUnitU = kMaxUtf16CodeUnit;
8908 // Value of hash field containing computed hash equal to zero.
8909 static const int kEmptyStringHash = kIsNotArrayIndexMask;
8911 // Maximal string length.
8912 static const int kMaxLength = (1 << 28) - 16;
8914 // Max length for computing hash. For strings longer than this limit the
8915 // string length is used as the hash value.
8916 static const int kMaxHashCalcLength = 16383;
8918 // Limit for truncation in short printing.
8919 static const int kMaxShortPrintLength = 1024;
8921 // Support for regular expressions.
8922 const uc16* GetTwoByteData(unsigned start);
8924 // Helper function for flattening strings.
8925 template <typename sinkchar>
8926 static void WriteToFlat(String* source,
8931 // The return value may point to the first aligned word containing the first
8932 // non-one-byte character, rather than directly to the non-one-byte character.
8933 // If the return value is >= the passed length, the entire string was
8935 static inline int NonAsciiStart(const char* chars, int length) {
8936 const char* start = chars;
8937 const char* limit = chars + length;
8939 if (length >= kIntptrSize) {
8940 // Check unaligned bytes.
8941 while (!IsAligned(reinterpret_cast<intptr_t>(chars), sizeof(uintptr_t))) {
8942 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8943 return static_cast<int>(chars - start);
8947 // Check aligned words.
8948 DCHECK(unibrow::Utf8::kMaxOneByteChar == 0x7F);
8949 const uintptr_t non_one_byte_mask = kUintptrAllBitsSet / 0xFF * 0x80;
8950 while (chars + sizeof(uintptr_t) <= limit) {
8951 if (*reinterpret_cast<const uintptr_t*>(chars) & non_one_byte_mask) {
8952 return static_cast<int>(chars - start);
8954 chars += sizeof(uintptr_t);
8957 // Check remaining unaligned bytes.
8958 while (chars < limit) {
8959 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8960 return static_cast<int>(chars - start);
8965 return static_cast<int>(chars - start);
8968 static inline bool IsAscii(const char* chars, int length) {
8969 return NonAsciiStart(chars, length) >= length;
8972 static inline bool IsAscii(const uint8_t* chars, int length) {
8974 NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
8977 static inline int NonOneByteStart(const uc16* chars, int length) {
8978 const uc16* limit = chars + length;
8979 const uc16* start = chars;
8980 while (chars < limit) {
8981 if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
8984 return static_cast<int>(chars - start);
8987 static inline bool IsOneByte(const uc16* chars, int length) {
8988 return NonOneByteStart(chars, length) >= length;
8991 template<class Visitor>
8992 static inline ConsString* VisitFlat(Visitor* visitor,
8996 static Handle<FixedArray> CalculateLineEnds(Handle<String> string,
8997 bool include_ending_line);
8999 // Use the hash field to forward to the canonical internalized string
9000 // when deserializing an internalized string.
9001 inline void SetForwardedInternalizedString(String* string);
9002 inline String* GetForwardedInternalizedString();
9006 friend class StringTableInsertionKey;
9008 static Handle<String> SlowFlatten(Handle<ConsString> cons,
9009 PretenureFlag tenure);
9011 // Slow case of String::Equals. This implementation works on any strings
9012 // but it is most efficient on strings that are almost flat.
9013 bool SlowEquals(String* other);
9015 static bool SlowEquals(Handle<String> one, Handle<String> two);
9017 // Slow case of AsArrayIndex.
9018 bool SlowAsArrayIndex(uint32_t* index);
9020 // Compute and set the hash code.
9021 uint32_t ComputeAndSetHash();
9023 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
9027 // The SeqString abstract class captures sequential string values.
9028 class SeqString: public String {
9030 DECLARE_CAST(SeqString)
9032 // Layout description.
9033 static const int kHeaderSize = String::kSize;
9035 // Truncate the string in-place if possible and return the result.
9036 // In case of new_length == 0, the empty string is returned without
9037 // truncating the original string.
9038 MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
9041 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
9045 // The OneByteString class captures sequential one-byte string objects.
9046 // Each character in the OneByteString is an one-byte character.
9047 class SeqOneByteString: public SeqString {
9049 static const bool kHasOneByteEncoding = true;
9051 // Dispatched behavior.
9052 inline uint16_t SeqOneByteStringGet(int index);
9053 inline void SeqOneByteStringSet(int index, uint16_t value);
9055 // Get the address of the characters in this string.
9056 inline Address GetCharsAddress();
9058 inline uint8_t* GetChars();
9060 DECLARE_CAST(SeqOneByteString)
9062 // Garbage collection support. This method is called by the
9063 // garbage collector to compute the actual size of an OneByteString
9065 inline int SeqOneByteStringSize(InstanceType instance_type);
9067 // Computes the size for an OneByteString instance of a given length.
9068 static int SizeFor(int length) {
9069 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
9072 // Maximal memory usage for a single sequential one-byte string.
9073 static const int kMaxSize = 512 * MB - 1;
9074 STATIC_ASSERT((kMaxSize - kHeaderSize) >= String::kMaxLength);
9077 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
9081 // The TwoByteString class captures sequential unicode string objects.
9082 // Each character in the TwoByteString is a two-byte uint16_t.
9083 class SeqTwoByteString: public SeqString {
9085 static const bool kHasOneByteEncoding = false;
9087 // Dispatched behavior.
9088 inline uint16_t SeqTwoByteStringGet(int index);
9089 inline void SeqTwoByteStringSet(int index, uint16_t value);
9091 // Get the address of the characters in this string.
9092 inline Address GetCharsAddress();
9094 inline uc16* GetChars();
9097 const uint16_t* SeqTwoByteStringGetData(unsigned start);
9099 DECLARE_CAST(SeqTwoByteString)
9101 // Garbage collection support. This method is called by the
9102 // garbage collector to compute the actual size of a TwoByteString
9104 inline int SeqTwoByteStringSize(InstanceType instance_type);
9106 // Computes the size for a TwoByteString instance of a given length.
9107 static int SizeFor(int length) {
9108 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
9111 // Maximal memory usage for a single sequential two-byte string.
9112 static const int kMaxSize = 512 * MB - 1;
9113 STATIC_ASSERT(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
9114 String::kMaxLength);
9117 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
9121 // The ConsString class describes string values built by using the
9122 // addition operator on strings. A ConsString is a pair where the
9123 // first and second components are pointers to other string values.
9124 // One or both components of a ConsString can be pointers to other
9125 // ConsStrings, creating a binary tree of ConsStrings where the leaves
9126 // are non-ConsString string values. The string value represented by
9127 // a ConsString can be obtained by concatenating the leaf string
9128 // values in a left-to-right depth-first traversal of the tree.
9129 class ConsString: public String {
9131 // First string of the cons cell.
9132 inline String* first();
9133 // Doesn't check that the result is a string, even in debug mode. This is
9134 // useful during GC where the mark bits confuse the checks.
9135 inline Object* unchecked_first();
9136 inline void set_first(String* first,
9137 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9139 // Second string of the cons cell.
9140 inline String* second();
9141 // Doesn't check that the result is a string, even in debug mode. This is
9142 // useful during GC where the mark bits confuse the checks.
9143 inline Object* unchecked_second();
9144 inline void set_second(String* second,
9145 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9147 // Dispatched behavior.
9148 uint16_t ConsStringGet(int index);
9150 DECLARE_CAST(ConsString)
9152 // Layout description.
9153 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
9154 static const int kSecondOffset = kFirstOffset + kPointerSize;
9155 static const int kSize = kSecondOffset + kPointerSize;
9157 // Minimum length for a cons string.
9158 static const int kMinLength = 13;
9160 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
9163 DECLARE_VERIFIER(ConsString)
9166 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
9170 // The Sliced String class describes strings that are substrings of another
9171 // sequential string. The motivation is to save time and memory when creating
9172 // a substring. A Sliced String is described as a pointer to the parent,
9173 // the offset from the start of the parent string and the length. Using
9174 // a Sliced String therefore requires unpacking of the parent string and
9175 // adding the offset to the start address. A substring of a Sliced String
9176 // are not nested since the double indirection is simplified when creating
9177 // such a substring.
9178 // Currently missing features are:
9179 // - handling externalized parent strings
9180 // - external strings as parent
9181 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
9182 class SlicedString: public String {
9184 inline String* parent();
9185 inline void set_parent(String* parent,
9186 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9187 inline int offset() const;
9188 inline void set_offset(int offset);
9190 // Dispatched behavior.
9191 uint16_t SlicedStringGet(int index);
9193 DECLARE_CAST(SlicedString)
9195 // Layout description.
9196 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
9197 static const int kOffsetOffset = kParentOffset + kPointerSize;
9198 static const int kSize = kOffsetOffset + kPointerSize;
9200 // Minimum length for a sliced string.
9201 static const int kMinLength = 13;
9203 typedef FixedBodyDescriptor<kParentOffset,
9204 kOffsetOffset + kPointerSize, kSize>
9207 DECLARE_VERIFIER(SlicedString)
9210 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
9214 // The ExternalString class describes string values that are backed by
9215 // a string resource that lies outside the V8 heap. ExternalStrings
9216 // consist of the length field common to all strings, a pointer to the
9217 // external resource. It is important to ensure (externally) that the
9218 // resource is not deallocated while the ExternalString is live in the
9221 // The API expects that all ExternalStrings are created through the
9222 // API. Therefore, ExternalStrings should not be used internally.
9223 class ExternalString: public String {
9225 DECLARE_CAST(ExternalString)
9227 // Layout description.
9228 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
9229 static const int kShortSize = kResourceOffset + kPointerSize;
9230 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
9231 static const int kSize = kResourceDataOffset + kPointerSize;
9233 static const int kMaxShortLength =
9234 (kShortSize - SeqString::kHeaderSize) / kCharSize;
9236 // Return whether external string is short (data pointer is not cached).
9237 inline bool is_short();
9239 STATIC_ASSERT(kResourceOffset == Internals::kStringResourceOffset);
9242 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
9246 // The ExternalOneByteString class is an external string backed by an
9248 class ExternalOneByteString : public ExternalString {
9250 static const bool kHasOneByteEncoding = true;
9252 typedef v8::String::ExternalOneByteStringResource Resource;
9254 // The underlying resource.
9255 inline const Resource* resource();
9256 inline void set_resource(const Resource* buffer);
9258 // Update the pointer cache to the external character array.
9259 // The cached pointer is always valid, as the external character array does =
9260 // not move during lifetime. Deserialization is the only exception, after
9261 // which the pointer cache has to be refreshed.
9262 inline void update_data_cache();
9264 inline const uint8_t* GetChars();
9266 // Dispatched behavior.
9267 inline uint16_t ExternalOneByteStringGet(int index);
9269 DECLARE_CAST(ExternalOneByteString)
9271 // Garbage collection support.
9272 inline void ExternalOneByteStringIterateBody(ObjectVisitor* v);
9274 template <typename StaticVisitor>
9275 inline void ExternalOneByteStringIterateBody();
9278 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalOneByteString);
9282 // The ExternalTwoByteString class is an external string backed by a UTF-16
9284 class ExternalTwoByteString: public ExternalString {
9286 static const bool kHasOneByteEncoding = false;
9288 typedef v8::String::ExternalStringResource Resource;
9290 // The underlying string resource.
9291 inline const Resource* resource();
9292 inline void set_resource(const Resource* buffer);
9294 // Update the pointer cache to the external character array.
9295 // The cached pointer is always valid, as the external character array does =
9296 // not move during lifetime. Deserialization is the only exception, after
9297 // which the pointer cache has to be refreshed.
9298 inline void update_data_cache();
9300 inline const uint16_t* GetChars();
9302 // Dispatched behavior.
9303 inline uint16_t ExternalTwoByteStringGet(int index);
9306 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
9308 DECLARE_CAST(ExternalTwoByteString)
9310 // Garbage collection support.
9311 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
9313 template<typename StaticVisitor>
9314 inline void ExternalTwoByteStringIterateBody();
9317 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
9321 // Utility superclass for stack-allocated objects that must be updated
9322 // on gc. It provides two ways for the gc to update instances, either
9323 // iterating or updating after gc.
9324 class Relocatable BASE_EMBEDDED {
9326 explicit inline Relocatable(Isolate* isolate);
9327 inline virtual ~Relocatable();
9328 virtual void IterateInstance(ObjectVisitor* v) { }
9329 virtual void PostGarbageCollection() { }
9331 static void PostGarbageCollectionProcessing(Isolate* isolate);
9332 static int ArchiveSpacePerThread();
9333 static char* ArchiveState(Isolate* isolate, char* to);
9334 static char* RestoreState(Isolate* isolate, char* from);
9335 static void Iterate(Isolate* isolate, ObjectVisitor* v);
9336 static void Iterate(ObjectVisitor* v, Relocatable* top);
9337 static char* Iterate(ObjectVisitor* v, char* t);
9345 // A flat string reader provides random access to the contents of a
9346 // string independent of the character width of the string. The handle
9347 // must be valid as long as the reader is being used.
9348 class FlatStringReader : public Relocatable {
9350 FlatStringReader(Isolate* isolate, Handle<String> str);
9351 FlatStringReader(Isolate* isolate, Vector<const char> input);
9352 void PostGarbageCollection();
9353 inline uc32 Get(int index);
9354 template <typename Char>
9355 inline Char Get(int index);
9356 int length() { return length_; }
9365 // This maintains an off-stack representation of the stack frames required
9366 // to traverse a ConsString, allowing an entirely iterative and restartable
9367 // traversal of the entire string
9368 class ConsStringIterator {
9370 inline ConsStringIterator() {}
9371 inline explicit ConsStringIterator(ConsString* cons_string, int offset = 0) {
9372 Reset(cons_string, offset);
9374 inline void Reset(ConsString* cons_string, int offset = 0) {
9376 // Next will always return NULL.
9377 if (cons_string == NULL) return;
9378 Initialize(cons_string, offset);
9380 // Returns NULL when complete.
9381 inline String* Next(int* offset_out) {
9383 if (depth_ == 0) return NULL;
9384 return Continue(offset_out);
9388 static const int kStackSize = 32;
9389 // Use a mask instead of doing modulo operations for stack wrapping.
9390 static const int kDepthMask = kStackSize-1;
9391 STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
9392 static inline int OffsetForDepth(int depth);
9394 inline void PushLeft(ConsString* string);
9395 inline void PushRight(ConsString* string);
9396 inline void AdjustMaximumDepth();
9398 inline bool StackBlown() { return maximum_depth_ - depth_ == kStackSize; }
9399 void Initialize(ConsString* cons_string, int offset);
9400 String* Continue(int* offset_out);
9401 String* NextLeaf(bool* blew_stack);
9402 String* Search(int* offset_out);
9404 // Stack must always contain only frames for which right traversal
9405 // has not yet been performed.
9406 ConsString* frames_[kStackSize];
9411 DISALLOW_COPY_AND_ASSIGN(ConsStringIterator);
9415 class StringCharacterStream {
9417 inline StringCharacterStream(String* string,
9419 inline uint16_t GetNext();
9420 inline bool HasMore();
9421 inline void Reset(String* string, int offset = 0);
9422 inline void VisitOneByteString(const uint8_t* chars, int length);
9423 inline void VisitTwoByteString(const uint16_t* chars, int length);
9426 ConsStringIterator iter_;
9429 const uint8_t* buffer8_;
9430 const uint16_t* buffer16_;
9432 const uint8_t* end_;
9433 DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
9437 template <typename T>
9438 class VectorIterator {
9440 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
9441 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
9442 T GetNext() { return data_[index_++]; }
9443 bool has_more() { return index_ < data_.length(); }
9445 Vector<const T> data_;
9450 // The Oddball describes objects null, undefined, true, and false.
9451 class Oddball: public HeapObject {
9453 // [to_string]: Cached to_string computed at startup.
9454 DECL_ACCESSORS(to_string, String)
9456 // [to_number]: Cached to_number computed at startup.
9457 DECL_ACCESSORS(to_number, Object)
9459 inline byte kind() const;
9460 inline void set_kind(byte kind);
9462 DECLARE_CAST(Oddball)
9464 // Dispatched behavior.
9465 DECLARE_VERIFIER(Oddball)
9467 // Initialize the fields.
9468 static void Initialize(Isolate* isolate,
9469 Handle<Oddball> oddball,
9470 const char* to_string,
9471 Handle<Object> to_number,
9474 // Layout description.
9475 static const int kToStringOffset = HeapObject::kHeaderSize;
9476 static const int kToNumberOffset = kToStringOffset + kPointerSize;
9477 static const int kKindOffset = kToNumberOffset + kPointerSize;
9478 static const int kSize = kKindOffset + kPointerSize;
9480 static const byte kFalse = 0;
9481 static const byte kTrue = 1;
9482 static const byte kNotBooleanMask = ~1;
9483 static const byte kTheHole = 2;
9484 static const byte kNull = 3;
9485 static const byte kArgumentMarker = 4;
9486 static const byte kUndefined = 5;
9487 static const byte kUninitialized = 6;
9488 static const byte kOther = 7;
9489 static const byte kException = 8;
9491 typedef FixedBodyDescriptor<kToStringOffset,
9492 kToNumberOffset + kPointerSize,
9493 kSize> BodyDescriptor;
9495 STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset);
9496 STATIC_ASSERT(kNull == Internals::kNullOddballKind);
9497 STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind);
9500 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
9504 class Cell: public HeapObject {
9506 // [value]: value of the cell.
9507 DECL_ACCESSORS(value, Object)
9511 static inline Cell* FromValueAddress(Address value) {
9512 Object* result = FromAddress(value - kValueOffset);
9513 return static_cast<Cell*>(result);
9516 inline Address ValueAddress() {
9517 return address() + kValueOffset;
9520 // Dispatched behavior.
9521 DECLARE_PRINTER(Cell)
9522 DECLARE_VERIFIER(Cell)
9524 // Layout description.
9525 static const int kValueOffset = HeapObject::kHeaderSize;
9526 static const int kSize = kValueOffset + kPointerSize;
9528 typedef FixedBodyDescriptor<kValueOffset,
9529 kValueOffset + kPointerSize,
9530 kSize> BodyDescriptor;
9533 DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9537 class PropertyCell : public HeapObject {
9539 // [property_details]: details of the global property.
9540 DECL_ACCESSORS(property_details_raw, Object)
9541 // [value]: value of the global property.
9542 DECL_ACCESSORS(value, Object)
9543 // [dependent_code]: dependent code that depends on the type of the global
9545 DECL_ACCESSORS(dependent_code, DependentCode)
9547 PropertyDetails property_details() {
9548 return PropertyDetails(Smi::cast(property_details_raw()));
9551 void set_property_details(PropertyDetails details) {
9552 set_property_details_raw(details.AsSmi());
9555 PropertyCellConstantType GetConstantType();
9557 // Computes the new type of the cell's contents for the given value, but
9558 // without actually modifying the details.
9559 static PropertyCellType UpdatedType(Handle<PropertyCell> cell,
9560 Handle<Object> value,
9561 PropertyDetails details);
9562 static void UpdateCell(Handle<GlobalDictionary> dictionary, int entry,
9563 Handle<Object> value, PropertyDetails details);
9565 static Handle<PropertyCell> InvalidateEntry(
9566 Handle<GlobalDictionary> dictionary, int entry);
9568 static void SetValueWithInvalidation(Handle<PropertyCell> cell,
9569 Handle<Object> new_value);
9571 DECLARE_CAST(PropertyCell)
9573 // Dispatched behavior.
9574 DECLARE_PRINTER(PropertyCell)
9575 DECLARE_VERIFIER(PropertyCell)
9577 // Layout description.
9578 static const int kDetailsOffset = HeapObject::kHeaderSize;
9579 static const int kValueOffset = kDetailsOffset + kPointerSize;
9580 static const int kDependentCodeOffset = kValueOffset + kPointerSize;
9581 static const int kSize = kDependentCodeOffset + kPointerSize;
9583 static const int kPointerFieldsBeginOffset = kValueOffset;
9584 static const int kPointerFieldsEndOffset = kSize;
9586 typedef FixedBodyDescriptor<kValueOffset,
9588 kSize> BodyDescriptor;
9591 DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9595 class WeakCell : public HeapObject {
9597 inline Object* value() const;
9599 // This should not be called by anyone except GC.
9600 inline void clear();
9602 // This should not be called by anyone except allocator.
9603 inline void initialize(HeapObject* value);
9605 inline bool cleared() const;
9607 DECL_ACCESSORS(next, Object)
9609 inline void clear_next(Heap* heap);
9611 inline bool next_cleared();
9613 DECLARE_CAST(WeakCell)
9615 DECLARE_PRINTER(WeakCell)
9616 DECLARE_VERIFIER(WeakCell)
9618 // Layout description.
9619 static const int kValueOffset = HeapObject::kHeaderSize;
9620 static const int kNextOffset = kValueOffset + kPointerSize;
9621 static const int kSize = kNextOffset + kPointerSize;
9623 typedef FixedBodyDescriptor<kValueOffset, kSize, kSize> BodyDescriptor;
9626 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakCell);
9630 // The JSProxy describes EcmaScript Harmony proxies
9631 class JSProxy: public JSReceiver {
9633 // [handler]: The handler property.
9634 DECL_ACCESSORS(handler, Object)
9636 // [hash]: The hash code property (undefined if not initialized yet).
9637 DECL_ACCESSORS(hash, Object)
9639 DECLARE_CAST(JSProxy)
9641 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithHandler(
9642 Handle<JSProxy> proxy,
9643 Handle<Object> receiver,
9646 // If the handler defines an accessor property with a setter, invoke it.
9647 // If it defines an accessor property without a setter, or a data property
9648 // that is read-only, throw. In all these cases set '*done' to true,
9649 // otherwise set it to false.
9651 static MaybeHandle<Object> SetPropertyViaPrototypesWithHandler(
9652 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9653 Handle<Object> value, LanguageMode language_mode, bool* done);
9655 MUST_USE_RESULT static Maybe<PropertyAttributes>
9656 GetPropertyAttributesWithHandler(Handle<JSProxy> proxy,
9657 Handle<Object> receiver,
9659 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithHandler(
9660 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9661 Handle<Object> value, LanguageMode language_mode);
9663 // Turn the proxy into an (empty) JSObject.
9664 static void Fix(Handle<JSProxy> proxy);
9666 // Initializes the body after the handler slot.
9667 inline void InitializeBody(int object_size, Object* value);
9669 // Invoke a trap by name. If the trap does not exist on this's handler,
9670 // but derived_trap is non-NULL, invoke that instead. May cause GC.
9671 MUST_USE_RESULT static MaybeHandle<Object> CallTrap(
9672 Handle<JSProxy> proxy,
9674 Handle<Object> derived_trap,
9676 Handle<Object> args[]);
9678 // Dispatched behavior.
9679 DECLARE_PRINTER(JSProxy)
9680 DECLARE_VERIFIER(JSProxy)
9682 // Layout description. We add padding so that a proxy has the same
9683 // size as a virgin JSObject. This is essential for becoming a JSObject
9685 static const int kHandlerOffset = HeapObject::kHeaderSize;
9686 static const int kHashOffset = kHandlerOffset + kPointerSize;
9687 static const int kPaddingOffset = kHashOffset + kPointerSize;
9688 static const int kSize = JSObject::kHeaderSize;
9689 static const int kHeaderSize = kPaddingOffset;
9690 static const int kPaddingSize = kSize - kPaddingOffset;
9692 STATIC_ASSERT(kPaddingSize >= 0);
9694 typedef FixedBodyDescriptor<kHandlerOffset,
9696 kSize> BodyDescriptor;
9699 friend class JSReceiver;
9701 MUST_USE_RESULT static Maybe<bool> HasPropertyWithHandler(
9702 Handle<JSProxy> proxy, Handle<Name> name);
9704 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithHandler(
9705 Handle<JSProxy> proxy, Handle<Name> name, LanguageMode language_mode);
9707 MUST_USE_RESULT Object* GetIdentityHash();
9709 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
9711 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
9715 class JSFunctionProxy: public JSProxy {
9717 // [call_trap]: The call trap.
9718 DECL_ACCESSORS(call_trap, Object)
9720 // [construct_trap]: The construct trap.
9721 DECL_ACCESSORS(construct_trap, Object)
9723 DECLARE_CAST(JSFunctionProxy)
9725 // Dispatched behavior.
9726 DECLARE_PRINTER(JSFunctionProxy)
9727 DECLARE_VERIFIER(JSFunctionProxy)
9729 // Layout description.
9730 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
9731 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
9732 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
9733 static const int kSize = JSFunction::kSize;
9734 static const int kPaddingSize = kSize - kPaddingOffset;
9736 STATIC_ASSERT(kPaddingSize >= 0);
9738 typedef FixedBodyDescriptor<kHandlerOffset,
9739 kConstructTrapOffset + kPointerSize,
9740 kSize> BodyDescriptor;
9743 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
9747 class JSCollection : public JSObject {
9749 // [table]: the backing hash table
9750 DECL_ACCESSORS(table, Object)
9752 static const int kTableOffset = JSObject::kHeaderSize;
9753 static const int kSize = kTableOffset + kPointerSize;
9756 DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollection);
9760 // The JSSet describes EcmaScript Harmony sets
9761 class JSSet : public JSCollection {
9765 // Dispatched behavior.
9766 DECLARE_PRINTER(JSSet)
9767 DECLARE_VERIFIER(JSSet)
9770 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
9774 // The JSMap describes EcmaScript Harmony maps
9775 class JSMap : public JSCollection {
9779 // Dispatched behavior.
9780 DECLARE_PRINTER(JSMap)
9781 DECLARE_VERIFIER(JSMap)
9784 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
9788 // OrderedHashTableIterator is an iterator that iterates over the keys and
9789 // values of an OrderedHashTable.
9791 // The iterator has a reference to the underlying OrderedHashTable data,
9792 // [table], as well as the current [index] the iterator is at.
9794 // When the OrderedHashTable is rehashed it adds a reference from the old table
9795 // to the new table as well as storing enough data about the changes so that the
9796 // iterator [index] can be adjusted accordingly.
9798 // When the [Next] result from the iterator is requested, the iterator checks if
9799 // there is a newer table that it needs to transition to.
9800 template<class Derived, class TableType>
9801 class OrderedHashTableIterator: public JSObject {
9803 // [table]: the backing hash table mapping keys to values.
9804 DECL_ACCESSORS(table, Object)
9806 // [index]: The index into the data table.
9807 DECL_ACCESSORS(index, Object)
9809 // [kind]: The kind of iteration this is. One of the [Kind] enum values.
9810 DECL_ACCESSORS(kind, Object)
9813 void OrderedHashTableIteratorPrint(std::ostream& os); // NOLINT
9816 static const int kTableOffset = JSObject::kHeaderSize;
9817 static const int kIndexOffset = kTableOffset + kPointerSize;
9818 static const int kKindOffset = kIndexOffset + kPointerSize;
9819 static const int kSize = kKindOffset + kPointerSize;
9827 // Whether the iterator has more elements. This needs to be called before
9828 // calling |CurrentKey| and/or |CurrentValue|.
9831 // Move the index forward one.
9833 set_index(Smi::FromInt(Smi::cast(index())->value() + 1));
9836 // Populates the array with the next key and value and then moves the iterator
9838 // This returns the |kind| or 0 if the iterator is already at the end.
9839 Smi* Next(JSArray* value_array);
9841 // Returns the current key of the iterator. This should only be called when
9842 // |HasMore| returns true.
9843 inline Object* CurrentKey();
9846 // Transitions the iterator to the non obsolete backing store. This is a NOP
9847 // if the [table] is not obsolete.
9850 DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
9854 class JSSetIterator: public OrderedHashTableIterator<JSSetIterator,
9857 // Dispatched behavior.
9858 DECLARE_PRINTER(JSSetIterator)
9859 DECLARE_VERIFIER(JSSetIterator)
9861 DECLARE_CAST(JSSetIterator)
9863 // Called by |Next| to populate the array. This allows the subclasses to
9864 // populate the array differently.
9865 inline void PopulateValueArray(FixedArray* array);
9868 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSetIterator);
9872 class JSMapIterator: public OrderedHashTableIterator<JSMapIterator,
9875 // Dispatched behavior.
9876 DECLARE_PRINTER(JSMapIterator)
9877 DECLARE_VERIFIER(JSMapIterator)
9879 DECLARE_CAST(JSMapIterator)
9881 // Called by |Next| to populate the array. This allows the subclasses to
9882 // populate the array differently.
9883 inline void PopulateValueArray(FixedArray* array);
9886 // Returns the current value of the iterator. This should only be called when
9887 // |HasMore| returns true.
9888 inline Object* CurrentValue();
9890 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMapIterator);
9894 // Base class for both JSWeakMap and JSWeakSet
9895 class JSWeakCollection: public JSObject {
9897 // [table]: the backing hash table mapping keys to values.
9898 DECL_ACCESSORS(table, Object)
9900 // [next]: linked list of encountered weak maps during GC.
9901 DECL_ACCESSORS(next, Object)
9903 static const int kTableOffset = JSObject::kHeaderSize;
9904 static const int kNextOffset = kTableOffset + kPointerSize;
9905 static const int kSize = kNextOffset + kPointerSize;
9908 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
9912 // The JSWeakMap describes EcmaScript Harmony weak maps
9913 class JSWeakMap: public JSWeakCollection {
9915 DECLARE_CAST(JSWeakMap)
9917 // Dispatched behavior.
9918 DECLARE_PRINTER(JSWeakMap)
9919 DECLARE_VERIFIER(JSWeakMap)
9922 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
9926 // The JSWeakSet describes EcmaScript Harmony weak sets
9927 class JSWeakSet: public JSWeakCollection {
9929 DECLARE_CAST(JSWeakSet)
9931 // Dispatched behavior.
9932 DECLARE_PRINTER(JSWeakSet)
9933 DECLARE_VERIFIER(JSWeakSet)
9936 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
9940 // Whether a JSArrayBuffer is a SharedArrayBuffer or not.
9941 enum class SharedFlag { kNotShared, kShared };
9944 class JSArrayBuffer: public JSObject {
9946 // [backing_store]: backing memory for this array
9947 DECL_ACCESSORS(backing_store, void)
9949 // [byte_length]: length in bytes
9950 DECL_ACCESSORS(byte_length, Object)
9952 inline uint32_t bit_field() const;
9953 inline void set_bit_field(uint32_t bits);
9955 inline bool is_external();
9956 inline void set_is_external(bool value);
9958 inline bool is_neuterable();
9959 inline void set_is_neuterable(bool value);
9961 inline bool was_neutered();
9962 inline void set_was_neutered(bool value);
9964 inline bool is_shared();
9965 inline void set_is_shared(bool value);
9967 DECLARE_CAST(JSArrayBuffer)
9971 // Dispatched behavior.
9972 DECLARE_PRINTER(JSArrayBuffer)
9973 DECLARE_VERIFIER(JSArrayBuffer)
9975 static const int kBackingStoreOffset = JSObject::kHeaderSize;
9976 static const int kByteLengthOffset = kBackingStoreOffset + kPointerSize;
9977 static const int kBitFieldSlot = kByteLengthOffset + kPointerSize;
9978 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
9979 static const int kBitFieldOffset = kBitFieldSlot;
9981 static const int kBitFieldOffset = kBitFieldSlot + kIntSize;
9983 static const int kSize = kBitFieldSlot + kPointerSize;
9985 static const int kSizeWithInternalFields =
9986 kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
9988 class IsExternal : public BitField<bool, 1, 1> {};
9989 class IsNeuterable : public BitField<bool, 2, 1> {};
9990 class WasNeutered : public BitField<bool, 3, 1> {};
9991 class IsShared : public BitField<bool, 4, 1> {};
9994 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
9998 class JSArrayBufferView: public JSObject {
10000 // [buffer]: ArrayBuffer that this typed array views.
10001 DECL_ACCESSORS(buffer, Object)
10003 // [byte_offset]: offset of typed array in bytes.
10004 DECL_ACCESSORS(byte_offset, Object)
10006 // [byte_length]: length of typed array in bytes.
10007 DECL_ACCESSORS(byte_length, Object)
10009 DECLARE_CAST(JSArrayBufferView)
10011 DECLARE_VERIFIER(JSArrayBufferView)
10013 inline bool WasNeutered() const;
10015 static const int kBufferOffset = JSObject::kHeaderSize;
10016 static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
10017 static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
10018 static const int kViewSize = kByteLengthOffset + kPointerSize;
10022 DECL_ACCESSORS(raw_byte_offset, Object)
10023 DECL_ACCESSORS(raw_byte_length, Object)
10026 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
10030 class JSTypedArray: public JSArrayBufferView {
10032 // [length]: length of typed array in elements.
10033 DECL_ACCESSORS(length, Object)
10034 inline uint32_t length_value() const;
10036 DECLARE_CAST(JSTypedArray)
10038 ExternalArrayType type();
10039 size_t element_size();
10041 Handle<JSArrayBuffer> GetBuffer();
10043 // Dispatched behavior.
10044 DECLARE_PRINTER(JSTypedArray)
10045 DECLARE_VERIFIER(JSTypedArray)
10047 static const int kLengthOffset = kViewSize + kPointerSize;
10048 static const int kSize = kLengthOffset + kPointerSize;
10050 static const int kSizeWithInternalFields =
10051 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
10054 static Handle<JSArrayBuffer> MaterializeArrayBuffer(
10055 Handle<JSTypedArray> typed_array);
10057 DECL_ACCESSORS(raw_length, Object)
10060 DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
10064 class JSDataView: public JSArrayBufferView {
10066 DECLARE_CAST(JSDataView)
10068 // Dispatched behavior.
10069 DECLARE_PRINTER(JSDataView)
10070 DECLARE_VERIFIER(JSDataView)
10072 static const int kSize = kViewSize;
10074 static const int kSizeWithInternalFields =
10075 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
10078 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
10082 // Foreign describes objects pointing from JavaScript to C structures.
10083 class Foreign: public HeapObject {
10085 // [address]: field containing the address.
10086 inline Address foreign_address();
10087 inline void set_foreign_address(Address value);
10089 DECLARE_CAST(Foreign)
10091 // Dispatched behavior.
10092 inline void ForeignIterateBody(ObjectVisitor* v);
10094 template<typename StaticVisitor>
10095 inline void ForeignIterateBody();
10097 // Dispatched behavior.
10098 DECLARE_PRINTER(Foreign)
10099 DECLARE_VERIFIER(Foreign)
10101 // Layout description.
10103 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
10104 static const int kSize = kForeignAddressOffset + kPointerSize;
10106 STATIC_ASSERT(kForeignAddressOffset == Internals::kForeignAddressOffset);
10109 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
10113 // The JSArray describes JavaScript Arrays
10114 // Such an array can be in one of two modes:
10115 // - fast, backing storage is a FixedArray and length <= elements.length();
10116 // Please note: push and pop can be used to grow and shrink the array.
10117 // - slow, backing storage is a HashTable with numbers as keys.
10118 class JSArray: public JSObject {
10120 // [length]: The length property.
10121 DECL_ACCESSORS(length, Object)
10123 // Overload the length setter to skip write barrier when the length
10124 // is set to a smi. This matches the set function on FixedArray.
10125 inline void set_length(Smi* length);
10127 static bool HasReadOnlyLength(Handle<JSArray> array);
10128 static bool WouldChangeReadOnlyLength(Handle<JSArray> array, uint32_t index);
10129 static MaybeHandle<Object> ReadOnlyLengthError(Handle<JSArray> array);
10131 // Initialize the array with the given capacity. The function may
10132 // fail due to out-of-memory situations, but only if the requested
10133 // capacity is non-zero.
10134 static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
10136 // If the JSArray has fast elements, and new_length would result in
10137 // normalization, returns true.
10138 bool SetLengthWouldNormalize(uint32_t new_length);
10139 static inline bool SetLengthWouldNormalize(Heap* heap, uint32_t new_length);
10141 // Initializes the array to a certain length.
10142 inline bool AllowsSetLength();
10144 static void SetLength(Handle<JSArray> array, uint32_t length);
10145 // Same as above but will also queue splice records if |array| is observed.
10146 static MaybeHandle<Object> ObservableSetLength(Handle<JSArray> array,
10149 // Set the content of the array to the content of storage.
10150 static inline void SetContent(Handle<JSArray> array,
10151 Handle<FixedArrayBase> storage);
10153 DECLARE_CAST(JSArray)
10155 // Dispatched behavior.
10156 DECLARE_PRINTER(JSArray)
10157 DECLARE_VERIFIER(JSArray)
10159 // Number of element slots to pre-allocate for an empty array.
10160 static const int kPreallocatedArrayElements = 4;
10162 // Layout description.
10163 static const int kLengthOffset = JSObject::kHeaderSize;
10164 static const int kSize = kLengthOffset + kPointerSize;
10167 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
10171 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
10172 Handle<Map> initial_map);
10175 // JSRegExpResult is just a JSArray with a specific initial map.
10176 // This initial map adds in-object properties for "index" and "input"
10177 // properties, as assigned by RegExp.prototype.exec, which allows
10178 // faster creation of RegExp exec results.
10179 // This class just holds constants used when creating the result.
10180 // After creation the result must be treated as a JSArray in all regards.
10181 class JSRegExpResult: public JSArray {
10183 // Offsets of object fields.
10184 static const int kIndexOffset = JSArray::kSize;
10185 static const int kInputOffset = kIndexOffset + kPointerSize;
10186 static const int kSize = kInputOffset + kPointerSize;
10187 // Indices of in-object properties.
10188 static const int kIndexIndex = 0;
10189 static const int kInputIndex = 1;
10191 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
10195 class AccessorInfo: public Struct {
10197 DECL_ACCESSORS(name, Object)
10198 DECL_ACCESSORS(flag, Smi)
10199 DECL_ACCESSORS(expected_receiver_type, Object)
10201 inline bool all_can_read();
10202 inline void set_all_can_read(bool value);
10204 inline bool all_can_write();
10205 inline void set_all_can_write(bool value);
10207 inline bool is_special_data_property();
10208 inline void set_is_special_data_property(bool value);
10210 inline PropertyAttributes property_attributes();
10211 inline void set_property_attributes(PropertyAttributes attributes);
10213 // Checks whether the given receiver is compatible with this accessor.
10214 static bool IsCompatibleReceiverMap(Isolate* isolate,
10215 Handle<AccessorInfo> info,
10217 inline bool IsCompatibleReceiver(Object* receiver);
10219 DECLARE_CAST(AccessorInfo)
10221 // Dispatched behavior.
10222 DECLARE_VERIFIER(AccessorInfo)
10224 // Append all descriptors to the array that are not already there.
10225 // Return number added.
10226 static int AppendUnique(Handle<Object> descriptors,
10227 Handle<FixedArray> array,
10228 int valid_descriptors);
10230 static const int kNameOffset = HeapObject::kHeaderSize;
10231 static const int kFlagOffset = kNameOffset + kPointerSize;
10232 static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
10233 static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
10236 inline bool HasExpectedReceiverType() {
10237 return expected_receiver_type()->IsFunctionTemplateInfo();
10239 // Bit positions in flag.
10240 static const int kAllCanReadBit = 0;
10241 static const int kAllCanWriteBit = 1;
10242 static const int kSpecialDataProperty = 2;
10243 class AttributesField : public BitField<PropertyAttributes, 3, 3> {};
10245 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
10249 // An accessor must have a getter, but can have no setter.
10251 // When setting a property, V8 searches accessors in prototypes.
10252 // If an accessor was found and it does not have a setter,
10253 // the request is ignored.
10255 // If the accessor in the prototype has the READ_ONLY property attribute, then
10256 // a new value is added to the derived object when the property is set.
10257 // This shadows the accessor in the prototype.
10258 class ExecutableAccessorInfo: public AccessorInfo {
10260 DECL_ACCESSORS(getter, Object)
10261 DECL_ACCESSORS(setter, Object)
10262 DECL_ACCESSORS(data, Object)
10264 DECLARE_CAST(ExecutableAccessorInfo)
10266 // Dispatched behavior.
10267 DECLARE_PRINTER(ExecutableAccessorInfo)
10268 DECLARE_VERIFIER(ExecutableAccessorInfo)
10270 static const int kGetterOffset = AccessorInfo::kSize;
10271 static const int kSetterOffset = kGetterOffset + kPointerSize;
10272 static const int kDataOffset = kSetterOffset + kPointerSize;
10273 static const int kSize = kDataOffset + kPointerSize;
10275 static void ClearSetter(Handle<ExecutableAccessorInfo> info);
10278 DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
10282 // Support for JavaScript accessors: A pair of a getter and a setter. Each
10283 // accessor can either be
10284 // * a pointer to a JavaScript function or proxy: a real accessor
10285 // * undefined: considered an accessor by the spec, too, strangely enough
10286 // * the hole: an accessor which has not been set
10287 // * a pointer to a map: a transition used to ensure map sharing
10288 class AccessorPair: public Struct {
10290 DECL_ACCESSORS(getter, Object)
10291 DECL_ACCESSORS(setter, Object)
10293 DECLARE_CAST(AccessorPair)
10295 static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
10297 Object* get(AccessorComponent component) {
10298 return component == ACCESSOR_GETTER ? getter() : setter();
10301 void set(AccessorComponent component, Object* value) {
10302 if (component == ACCESSOR_GETTER) {
10309 // Note: Returns undefined instead in case of a hole.
10310 Object* GetComponent(AccessorComponent component);
10312 // Set both components, skipping arguments which are a JavaScript null.
10313 void SetComponents(Object* getter, Object* setter) {
10314 if (!getter->IsNull()) set_getter(getter);
10315 if (!setter->IsNull()) set_setter(setter);
10318 bool Equals(AccessorPair* pair) {
10319 return (this == pair) || pair->Equals(getter(), setter());
10322 bool Equals(Object* getter_value, Object* setter_value) {
10323 return (getter() == getter_value) && (setter() == setter_value);
10326 bool ContainsAccessor() {
10327 return IsJSAccessor(getter()) || IsJSAccessor(setter());
10330 // Dispatched behavior.
10331 DECLARE_PRINTER(AccessorPair)
10332 DECLARE_VERIFIER(AccessorPair)
10334 static const int kGetterOffset = HeapObject::kHeaderSize;
10335 static const int kSetterOffset = kGetterOffset + kPointerSize;
10336 static const int kSize = kSetterOffset + kPointerSize;
10339 // Strangely enough, in addition to functions and harmony proxies, the spec
10340 // requires us to consider undefined as a kind of accessor, too:
10342 // Object.defineProperty(obj, "foo", {get: undefined});
10343 // assertTrue("foo" in obj);
10344 bool IsJSAccessor(Object* obj) {
10345 return obj->IsSpecFunction() || obj->IsUndefined();
10348 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
10352 class AccessCheckInfo: public Struct {
10354 DECL_ACCESSORS(named_callback, Object)
10355 DECL_ACCESSORS(indexed_callback, Object)
10356 DECL_ACCESSORS(data, Object)
10358 DECLARE_CAST(AccessCheckInfo)
10360 // Dispatched behavior.
10361 DECLARE_PRINTER(AccessCheckInfo)
10362 DECLARE_VERIFIER(AccessCheckInfo)
10364 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
10365 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
10366 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
10367 static const int kSize = kDataOffset + kPointerSize;
10370 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
10374 class InterceptorInfo: public Struct {
10376 DECL_ACCESSORS(getter, Object)
10377 DECL_ACCESSORS(setter, Object)
10378 DECL_ACCESSORS(query, Object)
10379 DECL_ACCESSORS(deleter, Object)
10380 DECL_ACCESSORS(enumerator, Object)
10381 DECL_ACCESSORS(data, Object)
10382 DECL_BOOLEAN_ACCESSORS(can_intercept_symbols)
10383 DECL_BOOLEAN_ACCESSORS(all_can_read)
10384 DECL_BOOLEAN_ACCESSORS(non_masking)
10386 inline int flags() const;
10387 inline void set_flags(int flags);
10389 DECLARE_CAST(InterceptorInfo)
10391 // Dispatched behavior.
10392 DECLARE_PRINTER(InterceptorInfo)
10393 DECLARE_VERIFIER(InterceptorInfo)
10395 static const int kGetterOffset = HeapObject::kHeaderSize;
10396 static const int kSetterOffset = kGetterOffset + kPointerSize;
10397 static const int kQueryOffset = kSetterOffset + kPointerSize;
10398 static const int kDeleterOffset = kQueryOffset + kPointerSize;
10399 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
10400 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
10401 static const int kFlagsOffset = kDataOffset + kPointerSize;
10402 static const int kSize = kFlagsOffset + kPointerSize;
10404 static const int kCanInterceptSymbolsBit = 0;
10405 static const int kAllCanReadBit = 1;
10406 static const int kNonMasking = 2;
10409 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
10413 class CallHandlerInfo: public Struct {
10415 DECL_ACCESSORS(callback, Object)
10416 DECL_ACCESSORS(data, Object)
10418 DECLARE_CAST(CallHandlerInfo)
10420 // Dispatched behavior.
10421 DECLARE_PRINTER(CallHandlerInfo)
10422 DECLARE_VERIFIER(CallHandlerInfo)
10424 static const int kCallbackOffset = HeapObject::kHeaderSize;
10425 static const int kDataOffset = kCallbackOffset + kPointerSize;
10426 static const int kSize = kDataOffset + kPointerSize;
10429 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
10433 class TemplateInfo: public Struct {
10435 DECL_ACCESSORS(tag, Object)
10436 inline int number_of_properties() const;
10437 inline void set_number_of_properties(int value);
10438 DECL_ACCESSORS(property_list, Object)
10439 DECL_ACCESSORS(property_accessors, Object)
10441 DECLARE_VERIFIER(TemplateInfo)
10443 static const int kTagOffset = HeapObject::kHeaderSize;
10444 static const int kNumberOfProperties = kTagOffset + kPointerSize;
10445 static const int kPropertyListOffset = kNumberOfProperties + kPointerSize;
10446 static const int kPropertyAccessorsOffset =
10447 kPropertyListOffset + kPointerSize;
10448 static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
10451 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
10455 class FunctionTemplateInfo: public TemplateInfo {
10457 DECL_ACCESSORS(serial_number, Object)
10458 DECL_ACCESSORS(call_code, Object)
10459 DECL_ACCESSORS(prototype_template, Object)
10460 DECL_ACCESSORS(parent_template, Object)
10461 DECL_ACCESSORS(named_property_handler, Object)
10462 DECL_ACCESSORS(indexed_property_handler, Object)
10463 DECL_ACCESSORS(instance_template, Object)
10464 DECL_ACCESSORS(class_name, Object)
10465 DECL_ACCESSORS(signature, Object)
10466 DECL_ACCESSORS(instance_call_handler, Object)
10467 DECL_ACCESSORS(access_check_info, Object)
10468 DECL_ACCESSORS(flag, Smi)
10470 inline int length() const;
10471 inline void set_length(int value);
10473 // Following properties use flag bits.
10474 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
10475 DECL_BOOLEAN_ACCESSORS(undetectable)
10476 // If the bit is set, object instances created by this function
10477 // requires access check.
10478 DECL_BOOLEAN_ACCESSORS(needs_access_check)
10479 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
10480 DECL_BOOLEAN_ACCESSORS(remove_prototype)
10481 DECL_BOOLEAN_ACCESSORS(do_not_cache)
10482 DECL_BOOLEAN_ACCESSORS(instantiated)
10483 DECL_BOOLEAN_ACCESSORS(accept_any_receiver)
10485 DECLARE_CAST(FunctionTemplateInfo)
10487 // Dispatched behavior.
10488 DECLARE_PRINTER(FunctionTemplateInfo)
10489 DECLARE_VERIFIER(FunctionTemplateInfo)
10491 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
10492 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
10493 static const int kPrototypeTemplateOffset =
10494 kCallCodeOffset + kPointerSize;
10495 static const int kParentTemplateOffset =
10496 kPrototypeTemplateOffset + kPointerSize;
10497 static const int kNamedPropertyHandlerOffset =
10498 kParentTemplateOffset + kPointerSize;
10499 static const int kIndexedPropertyHandlerOffset =
10500 kNamedPropertyHandlerOffset + kPointerSize;
10501 static const int kInstanceTemplateOffset =
10502 kIndexedPropertyHandlerOffset + kPointerSize;
10503 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
10504 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
10505 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
10506 static const int kAccessCheckInfoOffset =
10507 kInstanceCallHandlerOffset + kPointerSize;
10508 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
10509 static const int kLengthOffset = kFlagOffset + kPointerSize;
10510 static const int kSize = kLengthOffset + kPointerSize;
10512 // Returns true if |object| is an instance of this function template.
10513 bool IsTemplateFor(Object* object);
10514 bool IsTemplateFor(Map* map);
10516 // Returns the holder JSObject if the function can legally be called with this
10517 // receiver. Returns Heap::null_value() if the call is illegal.
10518 Object* GetCompatibleReceiver(Isolate* isolate, Object* receiver);
10521 // Bit position in the flag, from least significant bit position.
10522 static const int kHiddenPrototypeBit = 0;
10523 static const int kUndetectableBit = 1;
10524 static const int kNeedsAccessCheckBit = 2;
10525 static const int kReadOnlyPrototypeBit = 3;
10526 static const int kRemovePrototypeBit = 4;
10527 static const int kDoNotCacheBit = 5;
10528 static const int kInstantiatedBit = 6;
10529 static const int kAcceptAnyReceiver = 7;
10531 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
10535 class ObjectTemplateInfo: public TemplateInfo {
10537 DECL_ACCESSORS(constructor, Object)
10538 DECL_ACCESSORS(internal_field_count, Object)
10540 DECLARE_CAST(ObjectTemplateInfo)
10542 // Dispatched behavior.
10543 DECLARE_PRINTER(ObjectTemplateInfo)
10544 DECLARE_VERIFIER(ObjectTemplateInfo)
10546 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10547 static const int kInternalFieldCountOffset =
10548 kConstructorOffset + kPointerSize;
10549 static const int kSize = kInternalFieldCountOffset + kPointerSize;
10553 class TypeSwitchInfo: public Struct {
10555 DECL_ACCESSORS(types, Object)
10557 DECLARE_CAST(TypeSwitchInfo)
10559 // Dispatched behavior.
10560 DECLARE_PRINTER(TypeSwitchInfo)
10561 DECLARE_VERIFIER(TypeSwitchInfo)
10563 static const int kTypesOffset = Struct::kHeaderSize;
10564 static const int kSize = kTypesOffset + kPointerSize;
10568 // The DebugInfo class holds additional information for a function being
10570 class DebugInfo: public Struct {
10572 // The shared function info for the source being debugged.
10573 DECL_ACCESSORS(shared, SharedFunctionInfo)
10574 // Code object for the patched code. This code object is the code object
10575 // currently active for the function.
10576 DECL_ACCESSORS(code, Code)
10577 // Fixed array holding status information for each active break point.
10578 DECL_ACCESSORS(break_points, FixedArray)
10580 // Check if there is a break point at a code position.
10581 bool HasBreakPoint(int code_position);
10582 // Get the break point info object for a code position.
10583 Object* GetBreakPointInfo(int code_position);
10584 // Clear a break point.
10585 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
10587 Handle<Object> break_point_object);
10588 // Set a break point.
10589 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
10590 int source_position, int statement_position,
10591 Handle<Object> break_point_object);
10592 // Get the break point objects for a code position.
10593 Handle<Object> GetBreakPointObjects(int code_position);
10594 // Find the break point info holding this break point object.
10595 static Handle<Object> FindBreakPointInfo(Handle<DebugInfo> debug_info,
10596 Handle<Object> break_point_object);
10597 // Get the number of break points for this function.
10598 int GetBreakPointCount();
10600 DECLARE_CAST(DebugInfo)
10602 // Dispatched behavior.
10603 DECLARE_PRINTER(DebugInfo)
10604 DECLARE_VERIFIER(DebugInfo)
10606 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
10607 static const int kCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
10608 static const int kBreakPointsStateIndex = kCodeIndex + kPointerSize;
10609 static const int kSize = kBreakPointsStateIndex + kPointerSize;
10611 static const int kEstimatedNofBreakPointsInFunction = 16;
10614 static const int kNoBreakPointInfo = -1;
10616 // Lookup the index in the break_points array for a code position.
10617 int GetBreakPointInfoIndex(int code_position);
10619 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
10623 // The BreakPointInfo class holds information for break points set in a
10624 // function. The DebugInfo object holds a BreakPointInfo object for each code
10625 // position with one or more break points.
10626 class BreakPointInfo: public Struct {
10628 // The position in the code for the break point.
10629 DECL_ACCESSORS(code_position, Smi)
10630 // The position in the source for the break position.
10631 DECL_ACCESSORS(source_position, Smi)
10632 // The position in the source for the last statement before this break
10634 DECL_ACCESSORS(statement_position, Smi)
10635 // List of related JavaScript break points.
10636 DECL_ACCESSORS(break_point_objects, Object)
10638 // Removes a break point.
10639 static void ClearBreakPoint(Handle<BreakPointInfo> info,
10640 Handle<Object> break_point_object);
10641 // Set a break point.
10642 static void SetBreakPoint(Handle<BreakPointInfo> info,
10643 Handle<Object> break_point_object);
10644 // Check if break point info has this break point object.
10645 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
10646 Handle<Object> break_point_object);
10647 // Get the number of break points for this code position.
10648 int GetBreakPointCount();
10650 DECLARE_CAST(BreakPointInfo)
10652 // Dispatched behavior.
10653 DECLARE_PRINTER(BreakPointInfo)
10654 DECLARE_VERIFIER(BreakPointInfo)
10656 static const int kCodePositionIndex = Struct::kHeaderSize;
10657 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
10658 static const int kStatementPositionIndex =
10659 kSourcePositionIndex + kPointerSize;
10660 static const int kBreakPointObjectsIndex =
10661 kStatementPositionIndex + kPointerSize;
10662 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
10665 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
10669 #undef DECL_BOOLEAN_ACCESSORS
10670 #undef DECL_ACCESSORS
10671 #undef DECLARE_CAST
10672 #undef DECLARE_VERIFIER
10674 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
10675 V(kStringTable, "string_table", "(Internalized strings)") \
10676 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
10677 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
10678 V(kSmiRootList, "smi_root_list", "(Smi roots)") \
10679 V(kInternalizedString, "internalized_string", "(Internal string)") \
10680 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
10681 V(kTop, "top", "(Isolate)") \
10682 V(kRelocatable, "relocatable", "(Relocatable)") \
10683 V(kDebug, "debug", "(Debugger)") \
10684 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
10685 V(kHandleScope, "handlescope", "(Handle scope)") \
10686 V(kBuiltins, "builtins", "(Builtins)") \
10687 V(kGlobalHandles, "globalhandles", "(Global handles)") \
10688 V(kEternalHandles, "eternalhandles", "(Eternal handles)") \
10689 V(kThreadManager, "threadmanager", "(Thread manager)") \
10690 V(kStrongRoots, "strong roots", "(Strong roots)") \
10691 V(kExtensions, "Extensions", "(Extensions)")
10693 class VisitorSynchronization : public AllStatic {
10695 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
10697 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
10700 #undef DECLARE_ENUM
10702 static const char* const kTags[kNumberOfSyncTags];
10703 static const char* const kTagNames[kNumberOfSyncTags];
10706 // Abstract base class for visiting, and optionally modifying, the
10707 // pointers contained in Objects. Used in GC and serialization/deserialization.
10708 class ObjectVisitor BASE_EMBEDDED {
10710 virtual ~ObjectVisitor() {}
10712 // Visits a contiguous arrays of pointers in the half-open range
10713 // [start, end). Any or all of the values may be modified on return.
10714 virtual void VisitPointers(Object** start, Object** end) = 0;
10716 // Handy shorthand for visiting a single pointer.
10717 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
10719 // Visit weak next_code_link in Code object.
10720 virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
10722 // To allow lazy clearing of inline caches the visitor has
10723 // a rich interface for iterating over Code objects..
10725 // Visits a code target in the instruction stream.
10726 virtual void VisitCodeTarget(RelocInfo* rinfo);
10728 // Visits a code entry in a JS function.
10729 virtual void VisitCodeEntry(Address entry_address);
10731 // Visits a global property cell reference in the instruction stream.
10732 virtual void VisitCell(RelocInfo* rinfo);
10734 // Visits a runtime entry in the instruction stream.
10735 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
10737 // Visits the resource of an one-byte or two-byte string.
10738 virtual void VisitExternalOneByteString(
10739 v8::String::ExternalOneByteStringResource** resource) {}
10740 virtual void VisitExternalTwoByteString(
10741 v8::String::ExternalStringResource** resource) {}
10743 // Visits a debug call target in the instruction stream.
10744 virtual void VisitDebugTarget(RelocInfo* rinfo);
10746 // Visits the byte sequence in a function's prologue that contains information
10747 // about the code's age.
10748 virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
10750 // Visit pointer embedded into a code object.
10751 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
10753 // Visits an external reference embedded into a code object.
10754 virtual void VisitExternalReference(RelocInfo* rinfo);
10756 // Visits an external reference.
10757 virtual void VisitExternalReference(Address* p) {}
10759 // Visits an (encoded) internal reference.
10760 virtual void VisitInternalReference(RelocInfo* rinfo) {}
10762 // Visits a handle that has an embedder-assigned class ID.
10763 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
10765 // Intended for serialization/deserialization checking: insert, or
10766 // check for the presence of, a tag at this position in the stream.
10767 // Also used for marking up GC roots in heap snapshots.
10768 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
10772 class StructBodyDescriptor : public
10773 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
10775 static inline int SizeOf(Map* map, HeapObject* object) {
10776 return map->instance_size();
10781 // BooleanBit is a helper class for setting and getting a bit in an
10783 class BooleanBit : public AllStatic {
10785 static inline bool get(Smi* smi, int bit_position) {
10786 return get(smi->value(), bit_position);
10789 static inline bool get(int value, int bit_position) {
10790 return (value & (1 << bit_position)) != 0;
10793 static inline Smi* set(Smi* smi, int bit_position, bool v) {
10794 return Smi::FromInt(set(smi->value(), bit_position, v));
10797 static inline int set(int value, int bit_position, bool v) {
10799 value |= (1 << bit_position);
10801 value &= ~(1 << bit_position);
10807 } } // namespace v8::internal
10809 #endif // V8_OBJECTS_H_