1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
10 #include "src/allocation.h"
11 #include "src/assert-scope.h"
12 #include "src/bailout-reason.h"
13 #include "src/base/bits.h"
14 #include "src/base/smart-pointers.h"
15 #include "src/builtins.h"
16 #include "src/checks.h"
17 #include "src/elements-kind.h"
18 #include "src/field-index.h"
19 #include "src/flags.h"
21 #include "src/property-details.h"
22 #include "src/unicode-inl.h"
23 #include "src/unicode-decoder.h"
26 #if V8_TARGET_ARCH_ARM
27 #include "src/arm/constants-arm.h" // NOLINT
28 #elif V8_TARGET_ARCH_ARM64
29 #include "src/arm64/constants-arm64.h" // NOLINT
30 #elif V8_TARGET_ARCH_MIPS
31 #include "src/mips/constants-mips.h" // NOLINT
32 #elif V8_TARGET_ARCH_MIPS64
33 #include "src/mips64/constants-mips64.h" // NOLINT
34 #elif V8_TARGET_ARCH_PPC
35 #include "src/ppc/constants-ppc.h" // NOLINT
40 // Most object types in the V8 JavaScript are described in this file.
42 // Inheritance hierarchy:
44 // - Smi (immediate small integer)
45 // - HeapObject (superclass for everything allocated in the heap)
46 // - JSReceiver (suitable for property access)
50 // - JSArrayBufferView
63 // - JSGeneratorObject
82 // - CompilationCacheTable
83 // - CodeCacheHashTable
89 // - TypeFeedbackVector
90 // - JSFunctionResultCache
93 // - ScriptContextTable
97 // - ExternalUint8ClampedArray
98 // - ExternalInt8Array
99 // - ExternalUint8Array
100 // - ExternalInt16Array
101 // - ExternalUint16Array
102 // - ExternalInt32Array
103 // - ExternalUint32Array
104 // - ExternalFloat32Array
108 // - SeqOneByteString
109 // - SeqTwoByteString
113 // - ExternalOneByteString
114 // - ExternalTwoByteString
115 // - InternalizedString
116 // - SeqInternalizedString
117 // - SeqOneByteInternalizedString
118 // - SeqTwoByteInternalizedString
119 // - ConsInternalizedString
120 // - ExternalInternalizedString
121 // - ExternalOneByteInternalizedString
122 // - ExternalTwoByteInternalizedString
132 // - SharedFunctionInfo
136 // - ExecutableAccessorInfo
142 // - FunctionTemplateInfo
143 // - ObjectTemplateInfo
152 // Formats of Object*:
153 // Smi: [31 bit signed int] 0
154 // HeapObject: [32 bit direct pointer] (4 byte aligned) | 01
159 enum KeyedAccessStoreMode {
161 STORE_TRANSITION_SMI_TO_OBJECT,
162 STORE_TRANSITION_SMI_TO_DOUBLE,
163 STORE_TRANSITION_DOUBLE_TO_OBJECT,
164 STORE_TRANSITION_HOLEY_SMI_TO_OBJECT,
165 STORE_TRANSITION_HOLEY_SMI_TO_DOUBLE,
166 STORE_TRANSITION_HOLEY_DOUBLE_TO_OBJECT,
167 STORE_AND_GROW_NO_TRANSITION,
168 STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT,
169 STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE,
170 STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT,
171 STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_OBJECT,
172 STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_DOUBLE,
173 STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT,
174 STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS,
175 STORE_NO_TRANSITION_HANDLE_COW
179 enum TypeofMode { INSIDE_TYPEOF, NOT_INSIDE_TYPEOF };
188 enum ExternalArrayType {
189 kExternalInt8Array = 1,
192 kExternalUint16Array,
194 kExternalUint32Array,
195 kExternalFloat32Array,
196 kExternalFloat64Array,
197 kExternalUint8ClampedArray,
201 static const int kGrowICDelta = STORE_AND_GROW_NO_TRANSITION -
203 STATIC_ASSERT(STANDARD_STORE == 0);
204 STATIC_ASSERT(kGrowICDelta ==
205 STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT -
206 STORE_TRANSITION_SMI_TO_OBJECT);
207 STATIC_ASSERT(kGrowICDelta ==
208 STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE -
209 STORE_TRANSITION_SMI_TO_DOUBLE);
210 STATIC_ASSERT(kGrowICDelta ==
211 STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT -
212 STORE_TRANSITION_DOUBLE_TO_OBJECT);
215 static inline KeyedAccessStoreMode GetGrowStoreMode(
216 KeyedAccessStoreMode store_mode) {
217 if (store_mode < STORE_AND_GROW_NO_TRANSITION) {
218 store_mode = static_cast<KeyedAccessStoreMode>(
219 static_cast<int>(store_mode) + kGrowICDelta);
225 static inline bool IsTransitionStoreMode(KeyedAccessStoreMode store_mode) {
226 return store_mode > STANDARD_STORE &&
227 store_mode <= STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT &&
228 store_mode != STORE_AND_GROW_NO_TRANSITION;
232 static inline KeyedAccessStoreMode GetNonTransitioningStoreMode(
233 KeyedAccessStoreMode store_mode) {
234 if (store_mode >= STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS) {
237 if (store_mode >= STORE_AND_GROW_NO_TRANSITION) {
238 return STORE_AND_GROW_NO_TRANSITION;
240 return STANDARD_STORE;
244 static inline bool IsGrowStoreMode(KeyedAccessStoreMode store_mode) {
245 return store_mode >= STORE_AND_GROW_NO_TRANSITION &&
246 store_mode <= STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT;
250 enum IcCheckType { ELEMENT, PROPERTY };
253 // SKIP_WRITE_BARRIER skips the write barrier.
254 // UPDATE_WEAK_WRITE_BARRIER skips the marking part of the write barrier and
255 // only performs the generational part.
256 // UPDATE_WRITE_BARRIER is doing the full barrier, marking and generational.
257 enum WriteBarrierMode {
259 UPDATE_WEAK_WRITE_BARRIER,
264 // Indicates whether a value can be loaded as a constant.
265 enum StoreMode { ALLOW_IN_DESCRIPTOR, FORCE_FIELD };
268 // PropertyNormalizationMode is used to specify whether to keep
269 // inobject properties when normalizing properties of a JSObject.
270 enum PropertyNormalizationMode {
271 CLEAR_INOBJECT_PROPERTIES,
272 KEEP_INOBJECT_PROPERTIES
276 // Indicates how aggressively the prototype should be optimized. FAST_PROTOTYPE
277 // will give the fastest result by tailoring the map to the prototype, but that
278 // will cause polymorphism with other objects. REGULAR_PROTOTYPE is to be used
279 // (at least for now) when dynamically modifying the prototype chain of an
280 // object using __proto__ or Object.setPrototypeOf.
281 enum PrototypeOptimizationMode { REGULAR_PROTOTYPE, FAST_PROTOTYPE };
284 // Indicates whether transitions can be added to a source map or not.
285 enum TransitionFlag {
291 // Indicates whether the transition is simple: the target map of the transition
292 // either extends the current map with a new property, or it modifies the
293 // property that was added last to the current map.
294 enum SimpleTransitionFlag {
295 SIMPLE_PROPERTY_TRANSITION,
301 // Indicates whether we are only interested in the descriptors of a particular
302 // map, or in all descriptors in the descriptor array.
303 enum DescriptorFlag {
308 // The GC maintains a bit of information, the MarkingParity, which toggles
309 // from odd to even and back every time marking is completed. Incremental
310 // marking can visit an object twice during a marking phase, so algorithms that
311 // that piggy-back on marking can use the parity to ensure that they only
312 // perform an operation on an object once per marking phase: they record the
313 // MarkingParity when they visit an object, and only re-visit the object when it
314 // is marked again and the MarkingParity changes.
321 // ICs store extra state in a Code object. The default extra state is
323 typedef int ExtraICState;
324 static const ExtraICState kNoExtraICState = 0;
326 // Instance size sentinel for objects of variable size.
327 const int kVariableSizeSentinel = 0;
329 // We may store the unsigned bit field as signed Smi value and do not
331 const int kStubMajorKeyBits = 7;
332 const int kStubMinorKeyBits = kSmiValueSize - kStubMajorKeyBits - 1;
334 // All Maps have a field instance_type containing a InstanceType.
335 // It describes the type of the instances.
337 // As an example, a JavaScript object is a heap object and its map
338 // instance_type is JS_OBJECT_TYPE.
340 // The names of the string instance types are intended to systematically
341 // mirror their encoding in the instance_type field of the map. The default
342 // encoding is considered TWO_BYTE. It is not mentioned in the name. ONE_BYTE
343 // encoding is mentioned explicitly in the name. Likewise, the default
344 // representation is considered sequential. It is not mentioned in the
345 // name. The other representations (e.g. CONS, EXTERNAL) are explicitly
346 // mentioned. Finally, the string is either a STRING_TYPE (if it is a normal
347 // string) or a INTERNALIZED_STRING_TYPE (if it is a internalized string).
349 // NOTE: The following things are some that depend on the string types having
350 // instance_types that are less than those of all other types:
351 // HeapObject::Size, HeapObject::IterateBody, the typeof operator, and
354 // NOTE: Everything following JS_VALUE_TYPE is considered a
355 // JSObject for GC purposes. The first four entries here have typeof
356 // 'object', whereas JS_FUNCTION_TYPE has typeof 'function'.
357 #define INSTANCE_TYPE_LIST(V) \
359 V(ONE_BYTE_STRING_TYPE) \
360 V(CONS_STRING_TYPE) \
361 V(CONS_ONE_BYTE_STRING_TYPE) \
362 V(SLICED_STRING_TYPE) \
363 V(SLICED_ONE_BYTE_STRING_TYPE) \
364 V(EXTERNAL_STRING_TYPE) \
365 V(EXTERNAL_ONE_BYTE_STRING_TYPE) \
366 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
367 V(SHORT_EXTERNAL_STRING_TYPE) \
368 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE) \
369 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
371 V(INTERNALIZED_STRING_TYPE) \
372 V(ONE_BYTE_INTERNALIZED_STRING_TYPE) \
373 V(EXTERNAL_INTERNALIZED_STRING_TYPE) \
374 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
375 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
376 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE) \
377 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
378 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
387 V(PROPERTY_CELL_TYPE) \
389 V(HEAP_NUMBER_TYPE) \
390 V(MUTABLE_HEAP_NUMBER_TYPE) \
393 V(BYTECODE_ARRAY_TYPE) \
395 /* Note: the order of these external array */ \
396 /* types is relied upon in */ \
397 /* Object::IsExternalArray(). */ \
398 V(EXTERNAL_INT8_ARRAY_TYPE) \
399 V(EXTERNAL_UINT8_ARRAY_TYPE) \
400 V(EXTERNAL_INT16_ARRAY_TYPE) \
401 V(EXTERNAL_UINT16_ARRAY_TYPE) \
402 V(EXTERNAL_INT32_ARRAY_TYPE) \
403 V(EXTERNAL_UINT32_ARRAY_TYPE) \
404 V(EXTERNAL_FLOAT32_ARRAY_TYPE) \
405 V(EXTERNAL_FLOAT64_ARRAY_TYPE) \
406 V(EXTERNAL_UINT8_CLAMPED_ARRAY_TYPE) \
408 V(FIXED_INT8_ARRAY_TYPE) \
409 V(FIXED_UINT8_ARRAY_TYPE) \
410 V(FIXED_INT16_ARRAY_TYPE) \
411 V(FIXED_UINT16_ARRAY_TYPE) \
412 V(FIXED_INT32_ARRAY_TYPE) \
413 V(FIXED_UINT32_ARRAY_TYPE) \
414 V(FIXED_FLOAT32_ARRAY_TYPE) \
415 V(FIXED_FLOAT64_ARRAY_TYPE) \
416 V(FIXED_UINT8_CLAMPED_ARRAY_TYPE) \
420 V(DECLARED_ACCESSOR_DESCRIPTOR_TYPE) \
421 V(DECLARED_ACCESSOR_INFO_TYPE) \
422 V(EXECUTABLE_ACCESSOR_INFO_TYPE) \
423 V(ACCESSOR_PAIR_TYPE) \
424 V(ACCESS_CHECK_INFO_TYPE) \
425 V(INTERCEPTOR_INFO_TYPE) \
426 V(CALL_HANDLER_INFO_TYPE) \
427 V(FUNCTION_TEMPLATE_INFO_TYPE) \
428 V(OBJECT_TEMPLATE_INFO_TYPE) \
429 V(SIGNATURE_INFO_TYPE) \
430 V(TYPE_SWITCH_INFO_TYPE) \
431 V(ALLOCATION_MEMENTO_TYPE) \
432 V(ALLOCATION_SITE_TYPE) \
435 V(POLYMORPHIC_CODE_CACHE_TYPE) \
436 V(TYPE_FEEDBACK_INFO_TYPE) \
437 V(ALIASED_ARGUMENTS_ENTRY_TYPE) \
439 V(PROTOTYPE_INFO_TYPE) \
441 V(FIXED_ARRAY_TYPE) \
442 V(FIXED_DOUBLE_ARRAY_TYPE) \
443 V(SHARED_FUNCTION_INFO_TYPE) \
446 V(JS_MESSAGE_OBJECT_TYPE) \
451 V(JS_CONTEXT_EXTENSION_OBJECT_TYPE) \
452 V(JS_GENERATOR_OBJECT_TYPE) \
454 V(JS_GLOBAL_OBJECT_TYPE) \
455 V(JS_BUILTINS_OBJECT_TYPE) \
456 V(JS_GLOBAL_PROXY_TYPE) \
458 V(JS_ARRAY_BUFFER_TYPE) \
459 V(JS_TYPED_ARRAY_TYPE) \
460 V(JS_DATA_VIEW_TYPE) \
464 V(JS_SET_ITERATOR_TYPE) \
465 V(JS_MAP_ITERATOR_TYPE) \
466 V(JS_WEAK_MAP_TYPE) \
467 V(JS_WEAK_SET_TYPE) \
470 V(JS_FUNCTION_TYPE) \
471 V(JS_FUNCTION_PROXY_TYPE) \
473 V(BREAK_POINT_INFO_TYPE)
476 // Since string types are not consecutive, this macro is used to
477 // iterate over them.
478 #define STRING_TYPE_LIST(V) \
479 V(STRING_TYPE, kVariableSizeSentinel, string, String) \
480 V(ONE_BYTE_STRING_TYPE, kVariableSizeSentinel, one_byte_string, \
482 V(CONS_STRING_TYPE, ConsString::kSize, cons_string, ConsString) \
483 V(CONS_ONE_BYTE_STRING_TYPE, ConsString::kSize, cons_one_byte_string, \
485 V(SLICED_STRING_TYPE, SlicedString::kSize, sliced_string, SlicedString) \
486 V(SLICED_ONE_BYTE_STRING_TYPE, SlicedString::kSize, sliced_one_byte_string, \
487 SlicedOneByteString) \
488 V(EXTERNAL_STRING_TYPE, ExternalTwoByteString::kSize, external_string, \
490 V(EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kSize, \
491 external_one_byte_string, ExternalOneByteString) \
492 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, ExternalTwoByteString::kSize, \
493 external_string_with_one_byte_data, ExternalStringWithOneByteData) \
494 V(SHORT_EXTERNAL_STRING_TYPE, ExternalTwoByteString::kShortSize, \
495 short_external_string, ShortExternalString) \
496 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kShortSize, \
497 short_external_one_byte_string, ShortExternalOneByteString) \
498 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, \
499 ExternalTwoByteString::kShortSize, \
500 short_external_string_with_one_byte_data, \
501 ShortExternalStringWithOneByteData) \
503 V(INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, internalized_string, \
504 InternalizedString) \
505 V(ONE_BYTE_INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, \
506 one_byte_internalized_string, OneByteInternalizedString) \
507 V(EXTERNAL_INTERNALIZED_STRING_TYPE, ExternalTwoByteString::kSize, \
508 external_internalized_string, ExternalInternalizedString) \
509 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, ExternalOneByteString::kSize, \
510 external_one_byte_internalized_string, ExternalOneByteInternalizedString) \
511 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
512 ExternalTwoByteString::kSize, \
513 external_internalized_string_with_one_byte_data, \
514 ExternalInternalizedStringWithOneByteData) \
515 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE, \
516 ExternalTwoByteString::kShortSize, short_external_internalized_string, \
517 ShortExternalInternalizedString) \
518 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, \
519 ExternalOneByteString::kShortSize, \
520 short_external_one_byte_internalized_string, \
521 ShortExternalOneByteInternalizedString) \
522 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
523 ExternalTwoByteString::kShortSize, \
524 short_external_internalized_string_with_one_byte_data, \
525 ShortExternalInternalizedStringWithOneByteData)
527 // A struct is a simple object a set of object-valued fields. Including an
528 // object type in this causes the compiler to generate most of the boilerplate
529 // code for the class including allocation and garbage collection routines,
530 // casts and predicates. All you need to define is the class, methods and
531 // object verification routines. Easy, no?
533 // Note that for subtle reasons related to the ordering or numerical values of
534 // type tags, elements in this list have to be added to the INSTANCE_TYPE_LIST
536 #define STRUCT_LIST(V) \
538 V(EXECUTABLE_ACCESSOR_INFO, ExecutableAccessorInfo, \
539 executable_accessor_info) \
540 V(ACCESSOR_PAIR, AccessorPair, accessor_pair) \
541 V(ACCESS_CHECK_INFO, AccessCheckInfo, access_check_info) \
542 V(INTERCEPTOR_INFO, InterceptorInfo, interceptor_info) \
543 V(CALL_HANDLER_INFO, CallHandlerInfo, call_handler_info) \
544 V(FUNCTION_TEMPLATE_INFO, FunctionTemplateInfo, function_template_info) \
545 V(OBJECT_TEMPLATE_INFO, ObjectTemplateInfo, object_template_info) \
546 V(TYPE_SWITCH_INFO, TypeSwitchInfo, type_switch_info) \
547 V(SCRIPT, Script, script) \
548 V(ALLOCATION_SITE, AllocationSite, allocation_site) \
549 V(ALLOCATION_MEMENTO, AllocationMemento, allocation_memento) \
550 V(CODE_CACHE, CodeCache, code_cache) \
551 V(POLYMORPHIC_CODE_CACHE, PolymorphicCodeCache, polymorphic_code_cache) \
552 V(TYPE_FEEDBACK_INFO, TypeFeedbackInfo, type_feedback_info) \
553 V(ALIASED_ARGUMENTS_ENTRY, AliasedArgumentsEntry, aliased_arguments_entry) \
554 V(DEBUG_INFO, DebugInfo, debug_info) \
555 V(BREAK_POINT_INFO, BreakPointInfo, break_point_info) \
556 V(PROTOTYPE_INFO, PrototypeInfo, prototype_info)
558 // We use the full 8 bits of the instance_type field to encode heap object
559 // instance types. The high-order bit (bit 7) is set if the object is not a
560 // string, and cleared if it is a string.
561 const uint32_t kIsNotStringMask = 0x80;
562 const uint32_t kStringTag = 0x0;
563 const uint32_t kNotStringTag = 0x80;
565 // Bit 6 indicates that the object is an internalized string (if set) or not.
566 // Bit 7 has to be clear as well.
567 const uint32_t kIsNotInternalizedMask = 0x40;
568 const uint32_t kNotInternalizedTag = 0x40;
569 const uint32_t kInternalizedTag = 0x0;
571 // If bit 7 is clear then bit 2 indicates whether the string consists of
572 // two-byte characters or one-byte characters.
573 const uint32_t kStringEncodingMask = 0x4;
574 const uint32_t kTwoByteStringTag = 0x0;
575 const uint32_t kOneByteStringTag = 0x4;
577 // If bit 7 is clear, the low-order 2 bits indicate the representation
579 const uint32_t kStringRepresentationMask = 0x03;
580 enum StringRepresentationTag {
582 kConsStringTag = 0x1,
583 kExternalStringTag = 0x2,
584 kSlicedStringTag = 0x3
586 const uint32_t kIsIndirectStringMask = 0x1;
587 const uint32_t kIsIndirectStringTag = 0x1;
588 STATIC_ASSERT((kSeqStringTag & kIsIndirectStringMask) == 0); // NOLINT
589 STATIC_ASSERT((kExternalStringTag & kIsIndirectStringMask) == 0); // NOLINT
590 STATIC_ASSERT((kConsStringTag &
591 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
592 STATIC_ASSERT((kSlicedStringTag &
593 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
595 // Use this mask to distinguish between cons and slice only after making
596 // sure that the string is one of the two (an indirect string).
597 const uint32_t kSlicedNotConsMask = kSlicedStringTag & ~kConsStringTag;
598 STATIC_ASSERT(IS_POWER_OF_TWO(kSlicedNotConsMask));
600 // If bit 7 is clear, then bit 3 indicates whether this two-byte
601 // string actually contains one byte data.
602 const uint32_t kOneByteDataHintMask = 0x08;
603 const uint32_t kOneByteDataHintTag = 0x08;
605 // If bit 7 is clear and string representation indicates an external string,
606 // then bit 4 indicates whether the data pointer is cached.
607 const uint32_t kShortExternalStringMask = 0x10;
608 const uint32_t kShortExternalStringTag = 0x10;
611 // A ConsString with an empty string as the right side is a candidate
612 // for being shortcut by the garbage collector. We don't allocate any
613 // non-flat internalized strings, so we do not shortcut them thereby
614 // avoiding turning internalized strings into strings. The bit-masks
615 // below contain the internalized bit as additional safety.
616 // See heap.cc, mark-compact.cc and objects-visiting.cc.
617 const uint32_t kShortcutTypeMask =
619 kIsNotInternalizedMask |
620 kStringRepresentationMask;
621 const uint32_t kShortcutTypeTag = kConsStringTag | kNotInternalizedTag;
623 static inline bool IsShortcutCandidate(int type) {
624 return ((type & kShortcutTypeMask) == kShortcutTypeTag);
630 INTERNALIZED_STRING_TYPE =
631 kTwoByteStringTag | kSeqStringTag | kInternalizedTag,
632 ONE_BYTE_INTERNALIZED_STRING_TYPE =
633 kOneByteStringTag | kSeqStringTag | kInternalizedTag,
634 EXTERNAL_INTERNALIZED_STRING_TYPE =
635 kTwoByteStringTag | kExternalStringTag | kInternalizedTag,
636 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
637 kOneByteStringTag | kExternalStringTag | kInternalizedTag,
638 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
639 EXTERNAL_INTERNALIZED_STRING_TYPE | kOneByteDataHintTag |
641 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE = EXTERNAL_INTERNALIZED_STRING_TYPE |
642 kShortExternalStringTag |
644 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
645 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kShortExternalStringTag |
647 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
648 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
649 kShortExternalStringTag | kInternalizedTag,
650 STRING_TYPE = INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
651 ONE_BYTE_STRING_TYPE =
652 ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
653 CONS_STRING_TYPE = kTwoByteStringTag | kConsStringTag | kNotInternalizedTag,
654 CONS_ONE_BYTE_STRING_TYPE =
655 kOneByteStringTag | kConsStringTag | kNotInternalizedTag,
657 kTwoByteStringTag | kSlicedStringTag | kNotInternalizedTag,
658 SLICED_ONE_BYTE_STRING_TYPE =
659 kOneByteStringTag | kSlicedStringTag | kNotInternalizedTag,
660 EXTERNAL_STRING_TYPE =
661 EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
662 EXTERNAL_ONE_BYTE_STRING_TYPE =
663 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
664 EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
665 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
667 SHORT_EXTERNAL_STRING_TYPE =
668 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
669 SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE =
670 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
671 SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
672 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
676 SYMBOL_TYPE = kNotStringTag, // FIRST_NONSTRING_TYPE, LAST_NAME_TYPE
678 // Objects allocated in their own spaces (never in new space).
683 // "Data", objects that cannot contain non-map-word pointers to heap
686 MUTABLE_HEAP_NUMBER_TYPE,
687 FLOAT32X4_TYPE, // FIRST_SIMD_TYPE, LAST_SIMD_TYPE
692 EXTERNAL_INT8_ARRAY_TYPE, // FIRST_EXTERNAL_ARRAY_TYPE
693 EXTERNAL_UINT8_ARRAY_TYPE,
694 EXTERNAL_INT16_ARRAY_TYPE,
695 EXTERNAL_UINT16_ARRAY_TYPE,
696 EXTERNAL_INT32_ARRAY_TYPE,
697 EXTERNAL_UINT32_ARRAY_TYPE,
698 EXTERNAL_FLOAT32_ARRAY_TYPE,
699 EXTERNAL_FLOAT64_ARRAY_TYPE,
700 EXTERNAL_UINT8_CLAMPED_ARRAY_TYPE, // LAST_EXTERNAL_ARRAY_TYPE
701 FIXED_INT8_ARRAY_TYPE, // FIRST_FIXED_TYPED_ARRAY_TYPE
702 FIXED_UINT8_ARRAY_TYPE,
703 FIXED_INT16_ARRAY_TYPE,
704 FIXED_UINT16_ARRAY_TYPE,
705 FIXED_INT32_ARRAY_TYPE,
706 FIXED_UINT32_ARRAY_TYPE,
707 FIXED_FLOAT32_ARRAY_TYPE,
708 FIXED_FLOAT64_ARRAY_TYPE,
709 FIXED_UINT8_CLAMPED_ARRAY_TYPE, // LAST_FIXED_TYPED_ARRAY_TYPE
710 FIXED_DOUBLE_ARRAY_TYPE,
711 FILLER_TYPE, // LAST_DATA_TYPE
714 DECLARED_ACCESSOR_DESCRIPTOR_TYPE,
715 DECLARED_ACCESSOR_INFO_TYPE,
716 EXECUTABLE_ACCESSOR_INFO_TYPE,
718 ACCESS_CHECK_INFO_TYPE,
719 INTERCEPTOR_INFO_TYPE,
720 CALL_HANDLER_INFO_TYPE,
721 FUNCTION_TEMPLATE_INFO_TYPE,
722 OBJECT_TEMPLATE_INFO_TYPE,
724 TYPE_SWITCH_INFO_TYPE,
725 ALLOCATION_SITE_TYPE,
726 ALLOCATION_MEMENTO_TYPE,
729 POLYMORPHIC_CODE_CACHE_TYPE,
730 TYPE_FEEDBACK_INFO_TYPE,
731 ALIASED_ARGUMENTS_ENTRY_TYPE,
734 BREAK_POINT_INFO_TYPE,
736 SHARED_FUNCTION_INFO_TYPE,
742 // All the following types are subtypes of JSReceiver, which corresponds to
743 // objects in the JS sense. The first and the last type in this range are
744 // the two forms of function. This organization enables using the same
745 // compares for checking the JS_RECEIVER/SPEC_OBJECT range and the
746 // NONCALLABLE_JS_OBJECT range.
747 JS_FUNCTION_PROXY_TYPE, // FIRST_JS_RECEIVER_TYPE, FIRST_JS_PROXY_TYPE
748 JS_PROXY_TYPE, // LAST_JS_PROXY_TYPE
749 JS_VALUE_TYPE, // FIRST_JS_OBJECT_TYPE
750 JS_MESSAGE_OBJECT_TYPE,
753 JS_CONTEXT_EXTENSION_OBJECT_TYPE,
754 JS_GENERATOR_OBJECT_TYPE,
756 JS_GLOBAL_OBJECT_TYPE,
757 JS_BUILTINS_OBJECT_TYPE,
758 JS_GLOBAL_PROXY_TYPE,
760 JS_ARRAY_BUFFER_TYPE,
765 JS_SET_ITERATOR_TYPE,
766 JS_MAP_ITERATOR_TYPE,
770 JS_FUNCTION_TYPE, // LAST_JS_OBJECT_TYPE, LAST_JS_RECEIVER_TYPE
774 LAST_TYPE = JS_FUNCTION_TYPE,
775 FIRST_NAME_TYPE = FIRST_TYPE,
776 LAST_NAME_TYPE = SYMBOL_TYPE,
777 FIRST_UNIQUE_NAME_TYPE = INTERNALIZED_STRING_TYPE,
778 LAST_UNIQUE_NAME_TYPE = SYMBOL_TYPE,
779 FIRST_NONSTRING_TYPE = SYMBOL_TYPE,
780 // Boundaries for testing for a SIMD type.
781 FIRST_SIMD_TYPE = FLOAT32X4_TYPE,
782 LAST_SIMD_TYPE = FLOAT32X4_TYPE,
783 // Boundaries for testing for an external array.
784 FIRST_EXTERNAL_ARRAY_TYPE = EXTERNAL_INT8_ARRAY_TYPE,
785 LAST_EXTERNAL_ARRAY_TYPE = EXTERNAL_UINT8_CLAMPED_ARRAY_TYPE,
786 // Boundaries for testing for a fixed typed array.
787 FIRST_FIXED_TYPED_ARRAY_TYPE = FIXED_INT8_ARRAY_TYPE,
788 LAST_FIXED_TYPED_ARRAY_TYPE = FIXED_UINT8_CLAMPED_ARRAY_TYPE,
789 // Boundary for promotion to old space.
790 LAST_DATA_TYPE = FILLER_TYPE,
791 // Boundary for objects represented as JSReceiver (i.e. JSObject or JSProxy).
792 // Note that there is no range for JSObject or JSProxy, since their subtypes
793 // are not continuous in this enum! The enum ranges instead reflect the
794 // external class names, where proxies are treated as either ordinary objects,
796 FIRST_JS_RECEIVER_TYPE = JS_FUNCTION_PROXY_TYPE,
797 LAST_JS_RECEIVER_TYPE = LAST_TYPE,
798 // Boundaries for testing the types represented as JSObject
799 FIRST_JS_OBJECT_TYPE = JS_VALUE_TYPE,
800 LAST_JS_OBJECT_TYPE = LAST_TYPE,
801 // Boundaries for testing the types represented as JSProxy
802 FIRST_JS_PROXY_TYPE = JS_FUNCTION_PROXY_TYPE,
803 LAST_JS_PROXY_TYPE = JS_PROXY_TYPE,
804 // Boundaries for testing whether the type is a JavaScript object.
805 FIRST_SPEC_OBJECT_TYPE = FIRST_JS_RECEIVER_TYPE,
806 LAST_SPEC_OBJECT_TYPE = LAST_JS_RECEIVER_TYPE,
807 // Boundaries for testing the types for which typeof is "object".
808 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_PROXY_TYPE,
809 LAST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_REGEXP_TYPE,
810 // Note that the types for which typeof is "function" are not continuous.
811 // Define this so that we can put assertions on discrete checks.
812 NUM_OF_CALLABLE_SPEC_OBJECT_TYPES = 2
815 const int kExternalArrayTypeCount =
816 LAST_EXTERNAL_ARRAY_TYPE - FIRST_EXTERNAL_ARRAY_TYPE + 1;
818 STATIC_ASSERT(JS_OBJECT_TYPE == Internals::kJSObjectType);
819 STATIC_ASSERT(FIRST_NONSTRING_TYPE == Internals::kFirstNonstringType);
820 STATIC_ASSERT(ODDBALL_TYPE == Internals::kOddballType);
821 STATIC_ASSERT(FOREIGN_TYPE == Internals::kForeignType);
824 #define FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(V) \
825 V(FAST_ELEMENTS_SUB_TYPE) \
826 V(DICTIONARY_ELEMENTS_SUB_TYPE) \
827 V(FAST_PROPERTIES_SUB_TYPE) \
828 V(DICTIONARY_PROPERTIES_SUB_TYPE) \
829 V(MAP_CODE_CACHE_SUB_TYPE) \
830 V(SCOPE_INFO_SUB_TYPE) \
831 V(STRING_TABLE_SUB_TYPE) \
832 V(DESCRIPTOR_ARRAY_SUB_TYPE) \
833 V(TRANSITION_ARRAY_SUB_TYPE)
835 enum FixedArraySubInstanceType {
836 #define DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE(name) name,
837 FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE)
838 #undef DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE
839 LAST_FIXED_ARRAY_SUB_TYPE = TRANSITION_ARRAY_SUB_TYPE
852 #define DECL_BOOLEAN_ACCESSORS(name) \
853 inline bool name() const; \
854 inline void set_##name(bool value); \
857 #define DECL_ACCESSORS(name, type) \
858 inline type* name() const; \
859 inline void set_##name(type* value, \
860 WriteBarrierMode mode = UPDATE_WRITE_BARRIER); \
863 #define DECLARE_CAST(type) \
864 INLINE(static type* cast(Object* object)); \
865 INLINE(static const type* cast(const Object* object));
869 class AllocationSite;
870 class AllocationSiteCreationContext;
871 class AllocationSiteUsageContext;
874 class ElementsAccessor;
875 class FixedArrayBase;
876 class FunctionLiteral;
878 class JSBuiltinsObject;
879 class LayoutDescriptor;
880 class LookupIterator;
881 class ObjectHashTable;
884 class SafepointEntry;
885 class SharedFunctionInfo;
887 class TypeFeedbackInfo;
888 class TypeFeedbackVector;
891 // We cannot just say "class HeapType;" if it is created from a template... =8-?
892 template<class> class TypeImpl;
893 struct HeapTypeConfig;
894 typedef TypeImpl<HeapTypeConfig> HeapType;
897 // A template-ized version of the IsXXX functions.
898 template <class C> inline bool Is(Object* obj);
901 #define DECLARE_VERIFIER(Name) void Name##Verify();
903 #define DECLARE_VERIFIER(Name)
907 #define DECLARE_PRINTER(Name) void Name##Print(std::ostream& os); // NOLINT
909 #define DECLARE_PRINTER(Name)
913 #define OBJECT_TYPE_LIST(V) \
918 #define HEAP_OBJECT_TYPE_LIST(V) \
920 V(MutableHeapNumber) \
929 V(ExternalTwoByteString) \
930 V(ExternalOneByteString) \
931 V(SeqTwoByteString) \
932 V(SeqOneByteString) \
933 V(InternalizedString) \
937 V(ExternalInt8Array) \
938 V(ExternalUint8Array) \
939 V(ExternalInt16Array) \
940 V(ExternalUint16Array) \
941 V(ExternalInt32Array) \
942 V(ExternalUint32Array) \
943 V(ExternalFloat32Array) \
944 V(ExternalFloat64Array) \
945 V(ExternalUint8ClampedArray) \
946 V(FixedTypedArrayBase) \
949 V(FixedUint16Array) \
951 V(FixedUint32Array) \
953 V(FixedFloat32Array) \
954 V(FixedFloat64Array) \
955 V(FixedUint8ClampedArray) \
961 V(JSContextExtensionObject) \
962 V(JSGeneratorObject) \
964 V(LayoutDescriptor) \
968 V(TypeFeedbackVector) \
969 V(DeoptimizationInputData) \
970 V(DeoptimizationOutputData) \
974 V(FixedDoubleArray) \
978 V(ScriptContextTable) \
984 V(SharedFunctionInfo) \
993 V(JSArrayBufferView) \
1002 V(JSWeakCollection) \
1009 V(JSFunctionResultCache) \
1010 V(NormalizedMapCache) \
1011 V(CompilationCacheTable) \
1012 V(CodeCacheHashTable) \
1013 V(PolymorphicCodeCacheHashTable) \
1018 V(JSBuiltinsObject) \
1020 V(UndetectableObject) \
1021 V(AccessCheckNeeded) \
1025 V(ObjectHashTable) \
1027 V(WeakValueHashTable) \
1030 // Object is the abstract superclass for all classes in the
1031 // object hierarchy.
1032 // Object does not use any virtual functions to avoid the
1033 // allocation of the C++ vtable.
1034 // Since both Smi and HeapObject are subclasses of Object no
1035 // data members can be present in Object.
1039 bool IsObject() const { return true; }
1041 #define IS_TYPE_FUNCTION_DECL(type_) INLINE(bool Is##type_() const);
1042 OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1043 HEAP_OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1044 #undef IS_TYPE_FUNCTION_DECL
1046 // A non-keyed store is of the form a.x = foo or a["x"] = foo whereas
1047 // a keyed store is of the form a[expression] = foo.
1048 enum StoreFromKeyed {
1049 MAY_BE_STORE_FROM_KEYED,
1050 CERTAINLY_NOT_STORE_FROM_KEYED
1053 INLINE(bool IsFixedArrayBase() const);
1054 INLINE(bool IsExternal() const);
1055 INLINE(bool IsAccessorInfo() const);
1057 INLINE(bool IsStruct() const);
1058 #define DECLARE_STRUCT_PREDICATE(NAME, Name, name) \
1059 INLINE(bool Is##Name() const);
1060 STRUCT_LIST(DECLARE_STRUCT_PREDICATE)
1061 #undef DECLARE_STRUCT_PREDICATE
1063 INLINE(bool IsSpecObject()) const;
1064 INLINE(bool IsSpecFunction()) const;
1065 INLINE(bool IsTemplateInfo()) const;
1066 INLINE(bool IsNameDictionary() const);
1067 INLINE(bool IsGlobalDictionary() const);
1068 INLINE(bool IsSeededNumberDictionary() const);
1069 INLINE(bool IsUnseededNumberDictionary() const);
1070 INLINE(bool IsOrderedHashSet() const);
1071 INLINE(bool IsOrderedHashMap() const);
1072 bool IsCallable() const;
1073 static bool IsPromise(Handle<Object> object);
1076 INLINE(bool IsUndefined() const);
1077 INLINE(bool IsNull() const);
1078 INLINE(bool IsTheHole() const);
1079 INLINE(bool IsException() const);
1080 INLINE(bool IsUninitialized() const);
1081 INLINE(bool IsTrue() const);
1082 INLINE(bool IsFalse() const);
1083 INLINE(bool IsArgumentsMarker() const);
1085 // Filler objects (fillers and free space objects).
1086 INLINE(bool IsFiller() const);
1088 // Extract the number.
1089 inline double Number();
1090 INLINE(bool IsNaN() const);
1091 INLINE(bool IsMinusZero() const);
1092 bool ToInt32(int32_t* value);
1093 bool ToUint32(uint32_t* value);
1095 inline Representation OptimalRepresentation() {
1096 if (!FLAG_track_fields) return Representation::Tagged();
1098 return Representation::Smi();
1099 } else if (FLAG_track_double_fields && IsHeapNumber()) {
1100 return Representation::Double();
1101 } else if (FLAG_track_computed_fields && IsUninitialized()) {
1102 return Representation::None();
1103 } else if (FLAG_track_heap_object_fields) {
1104 DCHECK(IsHeapObject());
1105 return Representation::HeapObject();
1107 return Representation::Tagged();
1111 inline ElementsKind OptimalElementsKind() {
1112 if (IsSmi()) return FAST_SMI_ELEMENTS;
1113 if (IsNumber()) return FAST_DOUBLE_ELEMENTS;
1114 return FAST_ELEMENTS;
1117 inline bool FitsRepresentation(Representation representation) {
1118 if (FLAG_track_fields && representation.IsNone()) {
1120 } else if (FLAG_track_fields && representation.IsSmi()) {
1122 } else if (FLAG_track_double_fields && representation.IsDouble()) {
1123 return IsMutableHeapNumber() || IsNumber();
1124 } else if (FLAG_track_heap_object_fields && representation.IsHeapObject()) {
1125 return IsHeapObject();
1130 // Checks whether two valid primitive encodings of a property name resolve to
1131 // the same logical property. E.g., the smi 1, the string "1" and the double
1132 // 1 all refer to the same property, so this helper will return true.
1133 inline bool KeyEquals(Object* other);
1135 Handle<HeapType> OptimalType(Isolate* isolate, Representation representation);
1137 inline static Handle<Object> NewStorageFor(Isolate* isolate,
1138 Handle<Object> object,
1139 Representation representation);
1141 inline static Handle<Object> WrapForRead(Isolate* isolate,
1142 Handle<Object> object,
1143 Representation representation);
1145 // Returns true if the object is of the correct type to be used as a
1146 // implementation of a JSObject's elements.
1147 inline bool HasValidElements();
1149 inline bool HasSpecificClassOf(String* name);
1151 bool BooleanValue(); // ECMA-262 9.2.
1153 // Convert to a JSObject if needed.
1154 // native_context is used when creating wrapper object.
1155 static inline MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1156 Handle<Object> object);
1157 static MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1158 Handle<Object> object,
1159 Handle<Context> context);
1161 MUST_USE_RESULT static MaybeHandle<Object> GetProperty(
1162 LookupIterator* it, LanguageMode language_mode = SLOPPY);
1164 // Implementation of [[Put]], ECMA-262 5th edition, section 8.12.5.
1165 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1166 Handle<Object> object, Handle<Name> name, Handle<Object> value,
1167 LanguageMode language_mode,
1168 StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
1170 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1171 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1172 StoreFromKeyed store_mode);
1174 MUST_USE_RESULT static MaybeHandle<Object> SetSuperProperty(
1175 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1176 StoreFromKeyed store_mode);
1178 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1179 LookupIterator* it, LanguageMode language_mode);
1180 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1181 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1182 LanguageMode language_mode);
1183 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1184 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1185 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1186 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1187 Handle<Object> value, LanguageMode language_mode);
1188 MUST_USE_RESULT static MaybeHandle<Object> RedefineNonconfigurableProperty(
1189 Isolate* isolate, Handle<Object> name, Handle<Object> value,
1190 LanguageMode language_mode);
1191 MUST_USE_RESULT static MaybeHandle<Object> SetDataProperty(
1192 LookupIterator* it, Handle<Object> value);
1193 MUST_USE_RESULT static MaybeHandle<Object> AddDataProperty(
1194 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1195 LanguageMode language_mode, StoreFromKeyed store_mode);
1196 MUST_USE_RESULT static inline MaybeHandle<Object> GetPropertyOrElement(
1197 Handle<Object> object, Handle<Name> name,
1198 LanguageMode language_mode = SLOPPY);
1199 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1200 Isolate* isolate, Handle<Object> object, const char* key,
1201 LanguageMode language_mode = SLOPPY);
1202 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1203 Handle<Object> object, Handle<Name> name,
1204 LanguageMode language_mode = SLOPPY);
1206 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithAccessor(
1207 LookupIterator* it, LanguageMode language_mode);
1208 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithAccessor(
1209 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1211 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithDefinedGetter(
1212 Handle<Object> receiver,
1213 Handle<JSReceiver> getter);
1214 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithDefinedSetter(
1215 Handle<Object> receiver,
1216 Handle<JSReceiver> setter,
1217 Handle<Object> value);
1219 MUST_USE_RESULT static inline MaybeHandle<Object> GetElement(
1220 Isolate* isolate, Handle<Object> object, uint32_t index,
1221 LanguageMode language_mode = SLOPPY);
1223 MUST_USE_RESULT static inline MaybeHandle<Object> SetElement(
1224 Isolate* isolate, Handle<Object> object, uint32_t index,
1225 Handle<Object> value, LanguageMode language_mode);
1227 static inline Handle<Object> GetPrototypeSkipHiddenPrototypes(
1228 Isolate* isolate, Handle<Object> receiver);
1230 // Returns the permanent hash code associated with this object. May return
1231 // undefined if not yet created.
1234 // Returns undefined for JSObjects, but returns the hash code for simple
1235 // objects. This avoids a double lookup in the cases where we know we will
1236 // add the hash to the JSObject if it does not already exist.
1237 Object* GetSimpleHash();
1239 // Returns the permanent hash code associated with this object depending on
1240 // the actual object type. May create and store a hash code if needed and none
1242 static Handle<Smi> GetOrCreateHash(Isolate* isolate, Handle<Object> object);
1244 // Checks whether this object has the same value as the given one. This
1245 // function is implemented according to ES5, section 9.12 and can be used
1246 // to implement the Harmony "egal" function.
1247 bool SameValue(Object* other);
1249 // Checks whether this object has the same value as the given one.
1250 // +0 and -0 are treated equal. Everything else is the same as SameValue.
1251 // This function is implemented according to ES6, section 7.2.4 and is used
1252 // by ES6 Map and Set.
1253 bool SameValueZero(Object* other);
1255 // Tries to convert an object to an array length. Returns true and sets the
1256 // output parameter if it succeeds.
1257 inline bool ToArrayLength(uint32_t* index);
1259 // Tries to convert an object to an array index. Returns true and sets the
1260 // output parameter if it succeeds. Equivalent to ToArrayLength, but does not
1261 // allow kMaxUInt32.
1262 inline bool ToArrayIndex(uint32_t* index);
1264 // Returns true if this is a JSValue containing a string and the index is
1265 // < the length of the string. Used to implement [] on strings.
1266 inline bool IsStringObjectWithCharacterAt(uint32_t index);
1268 DECLARE_VERIFIER(Object)
1270 // Verify a pointer is a valid object pointer.
1271 static void VerifyPointer(Object* p);
1274 inline void VerifyApiCallResultType();
1276 // Prints this object without details.
1277 void ShortPrint(FILE* out = stdout);
1279 // Prints this object without details to a message accumulator.
1280 void ShortPrint(StringStream* accumulator);
1282 void ShortPrint(std::ostream& os); // NOLINT
1284 DECLARE_CAST(Object)
1286 // Layout description.
1287 static const int kHeaderSize = 0; // Object does not take up any space.
1290 // For our gdb macros, we should perhaps change these in the future.
1293 // Prints this object with details.
1294 void Print(std::ostream& os); // NOLINT
1296 void Print() { ShortPrint(); }
1297 void Print(std::ostream& os) { ShortPrint(os); } // NOLINT
1301 friend class LookupIterator;
1302 friend class PrototypeIterator;
1304 // Return the map of the root of object's prototype chain.
1305 Map* GetRootMap(Isolate* isolate);
1307 // Helper for SetProperty and SetSuperProperty.
1308 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyInternal(
1309 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1310 StoreFromKeyed store_mode, bool* found);
1312 DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
1317 explicit Brief(const Object* const v) : value(v) {}
1318 const Object* value;
1322 std::ostream& operator<<(std::ostream& os, const Brief& v);
1325 // Smi represents integer Numbers that can be stored in 31 bits.
1326 // Smis are immediate which means they are NOT allocated in the heap.
1327 // The this pointer has the following format: [31 bit signed int] 0
1328 // For long smis it has the following format:
1329 // [32 bit signed int] [31 bits zero padding] 0
1330 // Smi stands for small integer.
1331 class Smi: public Object {
1333 // Returns the integer value.
1334 inline int value() const;
1336 // Convert a value to a Smi object.
1337 static inline Smi* FromInt(int value);
1339 static inline Smi* FromIntptr(intptr_t value);
1341 // Returns whether value can be represented in a Smi.
1342 static inline bool IsValid(intptr_t value);
1346 // Dispatched behavior.
1347 void SmiPrint(std::ostream& os) const; // NOLINT
1348 DECLARE_VERIFIER(Smi)
1350 static const int kMinValue =
1351 (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1352 static const int kMaxValue = -(kMinValue + 1);
1355 DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1359 // Heap objects typically have a map pointer in their first word. However,
1360 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1361 // encoded in the first word. The class MapWord is an abstraction of the
1362 // value in a heap object's first word.
1363 class MapWord BASE_EMBEDDED {
1365 // Normal state: the map word contains a map pointer.
1367 // Create a map word from a map pointer.
1368 static inline MapWord FromMap(const Map* map);
1370 // View this map word as a map pointer.
1371 inline Map* ToMap();
1374 // Scavenge collection: the map word of live objects in the from space
1375 // contains a forwarding address (a heap object pointer in the to space).
1377 // True if this map word is a forwarding address for a scavenge
1378 // collection. Only valid during a scavenge collection (specifically,
1379 // when all map words are heap object pointers, i.e. not during a full GC).
1380 inline bool IsForwardingAddress();
1382 // Create a map word from a forwarding address.
1383 static inline MapWord FromForwardingAddress(HeapObject* object);
1385 // View this map word as a forwarding address.
1386 inline HeapObject* ToForwardingAddress();
1388 static inline MapWord FromRawValue(uintptr_t value) {
1389 return MapWord(value);
1392 inline uintptr_t ToRawValue() {
1397 // HeapObject calls the private constructor and directly reads the value.
1398 friend class HeapObject;
1400 explicit MapWord(uintptr_t value) : value_(value) {}
1406 // The content of an heap object (except for the map pointer). kTaggedValues
1407 // objects can contain both heap pointers and Smis, kMixedValues can contain
1408 // heap pointers, Smis, and raw values (e.g. doubles or strings), and kRawValues
1409 // objects can contain raw values and Smis.
1410 enum class HeapObjectContents { kTaggedValues, kMixedValues, kRawValues };
1413 // HeapObject is the superclass for all classes describing heap allocated
1415 class HeapObject: public Object {
1417 // [map]: Contains a map which contains the object's reflective
1419 inline Map* map() const;
1420 inline void set_map(Map* value);
1421 // The no-write-barrier version. This is OK if the object is white and in
1422 // new space, or if the value is an immortal immutable object, like the maps
1423 // of primitive (non-JS) objects like strings, heap numbers etc.
1424 inline void set_map_no_write_barrier(Map* value);
1426 // Get the map using acquire load.
1427 inline Map* synchronized_map();
1428 inline MapWord synchronized_map_word() const;
1430 // Set the map using release store
1431 inline void synchronized_set_map(Map* value);
1432 inline void synchronized_set_map_no_write_barrier(Map* value);
1433 inline void synchronized_set_map_word(MapWord map_word);
1435 // During garbage collection, the map word of a heap object does not
1436 // necessarily contain a map pointer.
1437 inline MapWord map_word() const;
1438 inline void set_map_word(MapWord map_word);
1440 // The Heap the object was allocated in. Used also to access Isolate.
1441 inline Heap* GetHeap() const;
1443 // Convenience method to get current isolate.
1444 inline Isolate* GetIsolate() const;
1446 // Converts an address to a HeapObject pointer.
1447 static inline HeapObject* FromAddress(Address address);
1449 // Returns the address of this HeapObject.
1450 inline Address address();
1452 // Iterates over pointers contained in the object (including the Map)
1453 void Iterate(ObjectVisitor* v);
1455 // Iterates over all pointers contained in the object except the
1456 // first map pointer. The object type is given in the first
1457 // parameter. This function does not access the map pointer in the
1458 // object, and so is safe to call while the map pointer is modified.
1459 void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1461 // Returns the heap object's size in bytes
1464 // Indicates what type of values this heap object may contain.
1465 inline HeapObjectContents ContentType();
1467 // Given a heap object's map pointer, returns the heap size in bytes
1468 // Useful when the map pointer field is used for other purposes.
1470 inline int SizeFromMap(Map* map);
1472 // Returns the field at offset in obj, as a read/write Object* reference.
1473 // Does no checking, and is safe to use during GC, while maps are invalid.
1474 // Does not invoke write barrier, so should only be assigned to
1475 // during marking GC.
1476 static inline Object** RawField(HeapObject* obj, int offset);
1478 // Adds the |code| object related to |name| to the code cache of this map. If
1479 // this map is a dictionary map that is shared, the map copied and installed
1481 static void UpdateMapCodeCache(Handle<HeapObject> object,
1485 DECLARE_CAST(HeapObject)
1487 // Return the write barrier mode for this. Callers of this function
1488 // must be able to present a reference to an DisallowHeapAllocation
1489 // object as a sign that they are not going to use this function
1490 // from code that allocates and thus invalidates the returned write
1492 inline WriteBarrierMode GetWriteBarrierMode(
1493 const DisallowHeapAllocation& promise);
1495 // Dispatched behavior.
1496 void HeapObjectShortPrint(std::ostream& os); // NOLINT
1498 void PrintHeader(std::ostream& os, const char* id); // NOLINT
1500 DECLARE_PRINTER(HeapObject)
1501 DECLARE_VERIFIER(HeapObject)
1503 inline void VerifyObjectField(int offset);
1504 inline void VerifySmiField(int offset);
1506 // Verify a pointer is a valid HeapObject pointer that points to object
1507 // areas in the heap.
1508 static void VerifyHeapPointer(Object* p);
1511 inline AllocationAlignment RequiredAlignment();
1513 // Layout description.
1514 // First field in a heap object is map.
1515 static const int kMapOffset = Object::kHeaderSize;
1516 static const int kHeaderSize = kMapOffset + kPointerSize;
1518 STATIC_ASSERT(kMapOffset == Internals::kHeapObjectMapOffset);
1521 // helpers for calling an ObjectVisitor to iterate over pointers in the
1522 // half-open range [start, end) specified as integer offsets
1523 inline void IteratePointers(ObjectVisitor* v, int start, int end);
1524 // as above, for the single element at "offset"
1525 inline void IteratePointer(ObjectVisitor* v, int offset);
1526 // as above, for the next code link of a code object.
1527 inline void IterateNextCodeLink(ObjectVisitor* v, int offset);
1530 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1534 // This class describes a body of an object of a fixed size
1535 // in which all pointer fields are located in the [start_offset, end_offset)
1537 template<int start_offset, int end_offset, int size>
1538 class FixedBodyDescriptor {
1540 static const int kStartOffset = start_offset;
1541 static const int kEndOffset = end_offset;
1542 static const int kSize = size;
1544 static inline void IterateBody(HeapObject* obj, ObjectVisitor* v);
1546 template<typename StaticVisitor>
1547 static inline void IterateBody(HeapObject* obj) {
1548 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1549 HeapObject::RawField(obj, end_offset));
1554 // This class describes a body of an object of a variable size
1555 // in which all pointer fields are located in the [start_offset, object_size)
1557 template<int start_offset>
1558 class FlexibleBodyDescriptor {
1560 static const int kStartOffset = start_offset;
1562 static inline void IterateBody(HeapObject* obj,
1566 template<typename StaticVisitor>
1567 static inline void IterateBody(HeapObject* obj, int object_size) {
1568 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1569 HeapObject::RawField(obj, object_size));
1574 // The HeapNumber class describes heap allocated numbers that cannot be
1575 // represented in a Smi (small integer)
1576 class HeapNumber: public HeapObject {
1578 // [value]: number value.
1579 inline double value() const;
1580 inline void set_value(double value);
1582 DECLARE_CAST(HeapNumber)
1584 // Dispatched behavior.
1585 bool HeapNumberBooleanValue();
1587 void HeapNumberPrint(std::ostream& os); // NOLINT
1588 DECLARE_VERIFIER(HeapNumber)
1590 inline int get_exponent();
1591 inline int get_sign();
1593 // Layout description.
1594 static const int kValueOffset = HeapObject::kHeaderSize;
1595 // IEEE doubles are two 32 bit words. The first is just mantissa, the second
1596 // is a mixture of sign, exponent and mantissa. The offsets of two 32 bit
1597 // words within double numbers are endian dependent and they are set
1599 #if defined(V8_TARGET_LITTLE_ENDIAN)
1600 static const int kMantissaOffset = kValueOffset;
1601 static const int kExponentOffset = kValueOffset + 4;
1602 #elif defined(V8_TARGET_BIG_ENDIAN)
1603 static const int kMantissaOffset = kValueOffset + 4;
1604 static const int kExponentOffset = kValueOffset;
1606 #error Unknown byte ordering
1609 static const int kSize = kValueOffset + kDoubleSize;
1610 static const uint32_t kSignMask = 0x80000000u;
1611 static const uint32_t kExponentMask = 0x7ff00000u;
1612 static const uint32_t kMantissaMask = 0xfffffu;
1613 static const int kMantissaBits = 52;
1614 static const int kExponentBits = 11;
1615 static const int kExponentBias = 1023;
1616 static const int kExponentShift = 20;
1617 static const int kInfinityOrNanExponent =
1618 (kExponentMask >> kExponentShift) - kExponentBias;
1619 static const int kMantissaBitsInTopWord = 20;
1620 static const int kNonMantissaBitsInTopWord = 12;
1623 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
1627 // The Float32x4 class describes heap allocated SIMD values holding 4 32-bit
1629 class Float32x4 : public HeapObject {
1631 inline float get_lane(int lane) const;
1632 inline void set_lane(int lane, float value);
1634 DECLARE_CAST(Float32x4)
1636 // Dispatched behavior.
1637 void Float32x4Print(std::ostream& os); // NOLINT
1638 DECLARE_VERIFIER(Float32x4)
1640 // Layout description.
1641 static const int kValueOffset = HeapObject::kHeaderSize;
1642 static const int kSize = kValueOffset + kSimd128Size;
1645 DISALLOW_IMPLICIT_CONSTRUCTORS(Float32x4);
1649 enum EnsureElementsMode {
1650 DONT_ALLOW_DOUBLE_ELEMENTS,
1651 ALLOW_COPIED_DOUBLE_ELEMENTS,
1652 ALLOW_CONVERTED_DOUBLE_ELEMENTS
1656 // Indicator for one component of an AccessorPair.
1657 enum AccessorComponent {
1663 // JSReceiver includes types on which properties can be defined, i.e.,
1664 // JSObject and JSProxy.
1665 class JSReceiver: public HeapObject {
1667 DECLARE_CAST(JSReceiver)
1669 // Implementation of [[HasProperty]], ECMA-262 5th edition, section 8.12.6.
1670 MUST_USE_RESULT static inline Maybe<bool> HasProperty(
1671 Handle<JSReceiver> object, Handle<Name> name);
1672 MUST_USE_RESULT static inline Maybe<bool> HasOwnProperty(Handle<JSReceiver>,
1674 MUST_USE_RESULT static inline Maybe<bool> HasElement(
1675 Handle<JSReceiver> object, uint32_t index);
1676 MUST_USE_RESULT static inline Maybe<bool> HasOwnElement(
1677 Handle<JSReceiver> object, uint32_t index);
1679 // Implementation of [[Delete]], ECMA-262 5th edition, section 8.12.7.
1680 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyOrElement(
1681 Handle<JSReceiver> object, Handle<Name> name,
1682 LanguageMode language_mode = SLOPPY);
1683 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1684 Handle<JSReceiver> object, Handle<Name> name,
1685 LanguageMode language_mode = SLOPPY);
1686 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1687 LookupIterator* it, LanguageMode language_mode);
1688 MUST_USE_RESULT static MaybeHandle<Object> DeleteElement(
1689 Handle<JSReceiver> object, uint32_t index,
1690 LanguageMode language_mode = SLOPPY);
1692 // Tests for the fast common case for property enumeration.
1693 bool IsSimpleEnum();
1695 // Returns the class name ([[Class]] property in the specification).
1696 String* class_name();
1698 // Returns the constructor name (the name (possibly, inferred name) of the
1699 // function that was used to instantiate the object).
1700 String* constructor_name();
1702 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetPropertyAttributes(
1703 Handle<JSReceiver> object, Handle<Name> name);
1704 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1705 GetOwnPropertyAttributes(Handle<JSReceiver> object, Handle<Name> name);
1707 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetElementAttributes(
1708 Handle<JSReceiver> object, uint32_t index);
1709 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1710 GetOwnElementAttributes(Handle<JSReceiver> object, uint32_t index);
1712 MUST_USE_RESULT static Maybe<PropertyAttributes> GetPropertyAttributes(
1713 LookupIterator* it);
1716 static Handle<Object> GetDataProperty(Handle<JSReceiver> object,
1718 static Handle<Object> GetDataProperty(LookupIterator* it);
1721 // Retrieves a permanent object identity hash code. The undefined value might
1722 // be returned in case no hash was created yet.
1723 inline Object* GetIdentityHash();
1725 // Retrieves a permanent object identity hash code. May create and store a
1726 // hash code if needed and none exists.
1727 inline static Handle<Smi> GetOrCreateIdentityHash(
1728 Handle<JSReceiver> object);
1730 enum KeyCollectionType { OWN_ONLY, INCLUDE_PROTOS };
1732 // Computes the enumerable keys for a JSObject. Used for implementing
1733 // "for (n in object) { }".
1734 MUST_USE_RESULT static MaybeHandle<FixedArray> GetKeys(
1735 Handle<JSReceiver> object,
1736 KeyCollectionType type);
1739 DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
1743 // The JSObject describes real heap allocated JavaScript objects with
1745 // Note that the map of JSObject changes during execution to enable inline
1747 class JSObject: public JSReceiver {
1749 // [properties]: Backing storage for properties.
1750 // properties is a FixedArray in the fast case and a Dictionary in the
1752 DECL_ACCESSORS(properties, FixedArray) // Get and set fast properties.
1753 inline void initialize_properties();
1754 inline bool HasFastProperties();
1755 // Gets slow properties for non-global objects.
1756 inline NameDictionary* property_dictionary();
1757 // Gets global object properties.
1758 inline GlobalDictionary* global_dictionary();
1760 // [elements]: The elements (properties with names that are integers).
1762 // Elements can be in two general modes: fast and slow. Each mode
1763 // corrensponds to a set of object representations of elements that
1764 // have something in common.
1766 // In the fast mode elements is a FixedArray and so each element can
1767 // be quickly accessed. This fact is used in the generated code. The
1768 // elements array can have one of three maps in this mode:
1769 // fixed_array_map, sloppy_arguments_elements_map or
1770 // fixed_cow_array_map (for copy-on-write arrays). In the latter case
1771 // the elements array may be shared by a few objects and so before
1772 // writing to any element the array must be copied. Use
1773 // EnsureWritableFastElements in this case.
1775 // In the slow mode the elements is either a NumberDictionary, an
1776 // ExternalArray, or a FixedArray parameter map for a (sloppy)
1777 // arguments object.
1778 DECL_ACCESSORS(elements, FixedArrayBase)
1779 inline void initialize_elements();
1780 static void ResetElements(Handle<JSObject> object);
1781 static inline void SetMapAndElements(Handle<JSObject> object,
1783 Handle<FixedArrayBase> elements);
1784 inline ElementsKind GetElementsKind();
1785 ElementsAccessor* GetElementsAccessor();
1786 // Returns true if an object has elements of FAST_SMI_ELEMENTS ElementsKind.
1787 inline bool HasFastSmiElements();
1788 // Returns true if an object has elements of FAST_ELEMENTS ElementsKind.
1789 inline bool HasFastObjectElements();
1790 // Returns true if an object has elements of FAST_ELEMENTS or
1791 // FAST_SMI_ONLY_ELEMENTS.
1792 inline bool HasFastSmiOrObjectElements();
1793 // Returns true if an object has any of the fast elements kinds.
1794 inline bool HasFastElements();
1795 // Returns true if an object has elements of FAST_DOUBLE_ELEMENTS
1797 inline bool HasFastDoubleElements();
1798 // Returns true if an object has elements of FAST_HOLEY_*_ELEMENTS
1800 inline bool HasFastHoleyElements();
1801 inline bool HasSloppyArgumentsElements();
1802 inline bool HasDictionaryElements();
1804 inline bool HasExternalUint8ClampedElements();
1805 inline bool HasExternalArrayElements();
1806 inline bool HasExternalInt8Elements();
1807 inline bool HasExternalUint8Elements();
1808 inline bool HasExternalInt16Elements();
1809 inline bool HasExternalUint16Elements();
1810 inline bool HasExternalInt32Elements();
1811 inline bool HasExternalUint32Elements();
1812 inline bool HasExternalFloat32Elements();
1813 inline bool HasExternalFloat64Elements();
1815 inline bool HasFixedTypedArrayElements();
1817 inline bool HasFixedUint8ClampedElements();
1818 inline bool HasFixedArrayElements();
1819 inline bool HasFixedInt8Elements();
1820 inline bool HasFixedUint8Elements();
1821 inline bool HasFixedInt16Elements();
1822 inline bool HasFixedUint16Elements();
1823 inline bool HasFixedInt32Elements();
1824 inline bool HasFixedUint32Elements();
1825 inline bool HasFixedFloat32Elements();
1826 inline bool HasFixedFloat64Elements();
1828 inline bool HasFastArgumentsElements();
1829 inline bool HasSlowArgumentsElements();
1830 inline SeededNumberDictionary* element_dictionary(); // Gets slow elements.
1832 // Requires: HasFastElements().
1833 static Handle<FixedArray> EnsureWritableFastElements(
1834 Handle<JSObject> object);
1836 // Collects elements starting at index 0.
1837 // Undefined values are placed after non-undefined values.
1838 // Returns the number of non-undefined values.
1839 static Handle<Object> PrepareElementsForSort(Handle<JSObject> object,
1841 // As PrepareElementsForSort, but only on objects where elements is
1842 // a dictionary, and it will stay a dictionary. Collates undefined and
1843 // unexisting elements below limit from position zero of the elements.
1844 static Handle<Object> PrepareSlowElementsForSort(Handle<JSObject> object,
1847 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithInterceptor(
1848 LookupIterator* it, Handle<Object> value);
1850 // SetLocalPropertyIgnoreAttributes converts callbacks to fields. We need to
1851 // grant an exemption to ExecutableAccessor callbacks in some cases.
1852 enum ExecutableAccessorInfoHandling { DEFAULT_HANDLING, DONT_FORCE_FIELD };
1854 MUST_USE_RESULT static MaybeHandle<Object> DefineOwnPropertyIgnoreAttributes(
1855 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1856 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1858 MUST_USE_RESULT static MaybeHandle<Object> SetOwnPropertyIgnoreAttributes(
1859 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1860 PropertyAttributes attributes,
1861 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1863 MUST_USE_RESULT static MaybeHandle<Object> SetOwnElementIgnoreAttributes(
1864 Handle<JSObject> object, uint32_t index, Handle<Object> value,
1865 PropertyAttributes attributes,
1866 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1868 // Equivalent to one of the above depending on whether |name| can be converted
1869 // to an array index.
1870 MUST_USE_RESULT static MaybeHandle<Object>
1871 DefinePropertyOrElementIgnoreAttributes(
1872 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1873 PropertyAttributes attributes = NONE,
1874 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1876 // Adds or reconfigures a property to attributes NONE. It will fail when it
1878 MUST_USE_RESULT static Maybe<bool> CreateDataProperty(LookupIterator* it,
1879 Handle<Object> value);
1881 static void AddProperty(Handle<JSObject> object, Handle<Name> name,
1882 Handle<Object> value, PropertyAttributes attributes);
1884 MUST_USE_RESULT static MaybeHandle<Object> AddDataElement(
1885 Handle<JSObject> receiver, uint32_t index, Handle<Object> value,
1886 PropertyAttributes attributes);
1888 // Extend the receiver with a single fast property appeared first in the
1889 // passed map. This also extends the property backing store if necessary.
1890 static void AllocateStorageForMap(Handle<JSObject> object, Handle<Map> map);
1892 // Migrates the given object to a map whose field representations are the
1893 // lowest upper bound of all known representations for that field.
1894 static void MigrateInstance(Handle<JSObject> instance);
1896 // Migrates the given object only if the target map is already available,
1897 // or returns false if such a map is not yet available.
1898 static bool TryMigrateInstance(Handle<JSObject> instance);
1900 // Sets the property value in a normalized object given (key, value, details).
1901 // Handles the special representation of JS global objects.
1902 static void SetNormalizedProperty(Handle<JSObject> object, Handle<Name> name,
1903 Handle<Object> value,
1904 PropertyDetails details);
1905 static void SetDictionaryElement(Handle<JSObject> object, uint32_t index,
1906 Handle<Object> value,
1907 PropertyAttributes attributes);
1908 static void SetDictionaryArgumentsElement(Handle<JSObject> object,
1910 Handle<Object> value,
1911 PropertyAttributes attributes);
1913 static void OptimizeAsPrototype(Handle<JSObject> object,
1914 PrototypeOptimizationMode mode);
1915 static void ReoptimizeIfPrototype(Handle<JSObject> object);
1916 static void LazyRegisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1917 static bool RegisterPrototypeUserIfNotRegistered(Handle<JSObject> prototype,
1918 Handle<HeapObject> user,
1920 static bool UnregisterPrototypeUser(Handle<JSObject> prototype,
1921 Handle<HeapObject> user);
1922 static void InvalidatePrototypeChains(Map* map);
1924 // Retrieve interceptors.
1925 InterceptorInfo* GetNamedInterceptor();
1926 InterceptorInfo* GetIndexedInterceptor();
1928 // Used from JSReceiver.
1929 MUST_USE_RESULT static Maybe<PropertyAttributes>
1930 GetPropertyAttributesWithInterceptor(LookupIterator* it);
1931 MUST_USE_RESULT static Maybe<PropertyAttributes>
1932 GetPropertyAttributesWithFailedAccessCheck(LookupIterator* it);
1934 // Retrieves an AccessorPair property from the given object. Might return
1935 // undefined if the property doesn't exist or is of a different kind.
1936 MUST_USE_RESULT static MaybeHandle<Object> GetAccessor(
1937 Handle<JSObject> object,
1939 AccessorComponent component);
1941 // Defines an AccessorPair property on the given object.
1942 // TODO(mstarzinger): Rename to SetAccessor().
1943 static MaybeHandle<Object> DefineAccessor(Handle<JSObject> object,
1945 Handle<Object> getter,
1946 Handle<Object> setter,
1947 PropertyAttributes attributes);
1949 // Defines an AccessorInfo property on the given object.
1950 MUST_USE_RESULT static MaybeHandle<Object> SetAccessor(
1951 Handle<JSObject> object,
1952 Handle<AccessorInfo> info);
1954 // The result must be checked first for exceptions. If there's no exception,
1955 // the output parameter |done| indicates whether the interceptor has a result
1957 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithInterceptor(
1958 LookupIterator* it, bool* done);
1960 // Accessors for hidden properties object.
1962 // Hidden properties are not own properties of the object itself.
1963 // Instead they are stored in an auxiliary structure kept as an own
1964 // property with a special name Heap::hidden_string(). But if the
1965 // receiver is a JSGlobalProxy then the auxiliary object is a property
1966 // of its prototype, and if it's a detached proxy, then you can't have
1967 // hidden properties.
1969 // Sets a hidden property on this object. Returns this object if successful,
1970 // undefined if called on a detached proxy.
1971 static Handle<Object> SetHiddenProperty(Handle<JSObject> object,
1973 Handle<Object> value);
1974 // Gets the value of a hidden property with the given key. Returns the hole
1975 // if the property doesn't exist (or if called on a detached proxy),
1976 // otherwise returns the value set for the key.
1977 Object* GetHiddenProperty(Handle<Name> key);
1978 // Deletes a hidden property. Deleting a non-existing property is
1979 // considered successful.
1980 static void DeleteHiddenProperty(Handle<JSObject> object,
1982 // Returns true if the object has a property with the hidden string as name.
1983 static bool HasHiddenProperties(Handle<JSObject> object);
1985 static void SetIdentityHash(Handle<JSObject> object, Handle<Smi> hash);
1987 static void ValidateElements(Handle<JSObject> object);
1989 // Makes sure that this object can contain HeapObject as elements.
1990 static inline void EnsureCanContainHeapObjectElements(Handle<JSObject> obj);
1992 // Makes sure that this object can contain the specified elements.
1993 static inline void EnsureCanContainElements(
1994 Handle<JSObject> object,
1997 EnsureElementsMode mode);
1998 static inline void EnsureCanContainElements(
1999 Handle<JSObject> object,
2000 Handle<FixedArrayBase> elements,
2002 EnsureElementsMode mode);
2003 static void EnsureCanContainElements(
2004 Handle<JSObject> object,
2005 Arguments* arguments,
2008 EnsureElementsMode mode);
2010 // Would we convert a fast elements array to dictionary mode given
2011 // an access at key?
2012 bool WouldConvertToSlowElements(uint32_t index);
2014 // Computes the new capacity when expanding the elements of a JSObject.
2015 static uint32_t NewElementsCapacity(uint32_t old_capacity) {
2016 // (old_capacity + 50%) + 16
2017 return old_capacity + (old_capacity >> 1) + 16;
2020 // These methods do not perform access checks!
2021 static void UpdateAllocationSite(Handle<JSObject> object,
2022 ElementsKind to_kind);
2024 // Lookup interceptors are used for handling properties controlled by host
2026 inline bool HasNamedInterceptor();
2027 inline bool HasIndexedInterceptor();
2029 // Computes the enumerable keys from interceptors. Used for debug mirrors and
2030 // by JSReceiver::GetKeys.
2031 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForNamedInterceptor(
2032 Handle<JSObject> object,
2033 Handle<JSReceiver> receiver);
2034 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForIndexedInterceptor(
2035 Handle<JSObject> object,
2036 Handle<JSReceiver> receiver);
2038 // Support functions for v8 api (needed for correct interceptor behavior).
2039 MUST_USE_RESULT static Maybe<bool> HasRealNamedProperty(
2040 Handle<JSObject> object, Handle<Name> name);
2041 MUST_USE_RESULT static Maybe<bool> HasRealElementProperty(
2042 Handle<JSObject> object, uint32_t index);
2043 MUST_USE_RESULT static Maybe<bool> HasRealNamedCallbackProperty(
2044 Handle<JSObject> object, Handle<Name> name);
2046 // Get the header size for a JSObject. Used to compute the index of
2047 // internal fields as well as the number of internal fields.
2048 inline int GetHeaderSize();
2050 inline int GetInternalFieldCount();
2051 inline int GetInternalFieldOffset(int index);
2052 inline Object* GetInternalField(int index);
2053 inline void SetInternalField(int index, Object* value);
2054 inline void SetInternalField(int index, Smi* value);
2056 // Returns the number of properties on this object filtering out properties
2057 // with the specified attributes (ignoring interceptors).
2058 int NumberOfOwnProperties(PropertyAttributes filter = NONE);
2059 // Fill in details for properties into storage starting at the specified
2060 // index. Returns the number of properties added.
2061 int GetOwnPropertyNames(FixedArray* storage, int index,
2062 PropertyAttributes filter = NONE);
2064 // Returns the number of properties on this object filtering out properties
2065 // with the specified attributes (ignoring interceptors).
2066 int NumberOfOwnElements(PropertyAttributes filter);
2067 // Returns the number of enumerable elements (ignoring interceptors).
2068 int NumberOfEnumElements();
2069 // Returns the number of elements on this object filtering out elements
2070 // with the specified attributes (ignoring interceptors).
2071 int GetOwnElementKeys(FixedArray* storage, PropertyAttributes filter);
2072 // Count and fill in the enumerable elements into storage.
2073 // (storage->length() == NumberOfEnumElements()).
2074 // If storage is NULL, will count the elements without adding
2075 // them to any storage.
2076 // Returns the number of enumerable elements.
2077 int GetEnumElementKeys(FixedArray* storage);
2079 static Handle<FixedArray> GetEnumPropertyKeys(Handle<JSObject> object,
2082 // Returns a new map with all transitions dropped from the object's current
2083 // map and the ElementsKind set.
2084 static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
2085 ElementsKind to_kind);
2086 static void TransitionElementsKind(Handle<JSObject> object,
2087 ElementsKind to_kind);
2089 // Always use this to migrate an object to a new map.
2090 // |expected_additional_properties| is only used for fast-to-slow transitions
2091 // and ignored otherwise.
2092 static void MigrateToMap(Handle<JSObject> object, Handle<Map> new_map,
2093 int expected_additional_properties = 0);
2095 // Convert the object to use the canonical dictionary
2096 // representation. If the object is expected to have additional properties
2097 // added this number can be indicated to have the backing store allocated to
2098 // an initial capacity for holding these properties.
2099 static void NormalizeProperties(Handle<JSObject> object,
2100 PropertyNormalizationMode mode,
2101 int expected_additional_properties,
2102 const char* reason);
2104 // Convert and update the elements backing store to be a
2105 // SeededNumberDictionary dictionary. Returns the backing after conversion.
2106 static Handle<SeededNumberDictionary> NormalizeElements(
2107 Handle<JSObject> object);
2109 void RequireSlowElements(SeededNumberDictionary* dictionary);
2111 // Transform slow named properties to fast variants.
2112 static void MigrateSlowToFast(Handle<JSObject> object,
2113 int unused_property_fields, const char* reason);
2115 inline bool IsUnboxedDoubleField(FieldIndex index);
2117 // Access fast-case object properties at index.
2118 static Handle<Object> FastPropertyAt(Handle<JSObject> object,
2119 Representation representation,
2121 inline Object* RawFastPropertyAt(FieldIndex index);
2122 inline double RawFastDoublePropertyAt(FieldIndex index);
2124 inline void FastPropertyAtPut(FieldIndex index, Object* value);
2125 inline void RawFastPropertyAtPut(FieldIndex index, Object* value);
2126 inline void RawFastDoublePropertyAtPut(FieldIndex index, double value);
2127 inline void WriteToField(int descriptor, Object* value);
2129 // Access to in object properties.
2130 inline int GetInObjectPropertyOffset(int index);
2131 inline Object* InObjectPropertyAt(int index);
2132 inline Object* InObjectPropertyAtPut(int index,
2134 WriteBarrierMode mode
2135 = UPDATE_WRITE_BARRIER);
2137 // Set the object's prototype (only JSReceiver and null are allowed values).
2138 MUST_USE_RESULT static MaybeHandle<Object> SetPrototype(
2139 Handle<JSObject> object, Handle<Object> value, bool from_javascript);
2141 // Initializes the body after properties slot, properties slot is
2142 // initialized by set_properties. Fill the pre-allocated fields with
2143 // pre_allocated_value and the rest with filler_value.
2144 // Note: this call does not update write barrier, the caller is responsible
2145 // to ensure that |filler_value| can be collected without WB here.
2146 inline void InitializeBody(Map* map,
2147 Object* pre_allocated_value,
2148 Object* filler_value);
2150 // Check whether this object references another object
2151 bool ReferencesObject(Object* obj);
2153 // Disalow further properties to be added to the oject.
2154 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensions(
2155 Handle<JSObject> object);
2157 bool IsExtensible();
2160 MUST_USE_RESULT static MaybeHandle<Object> Seal(Handle<JSObject> object);
2162 // ES5 Object.freeze
2163 MUST_USE_RESULT static MaybeHandle<Object> Freeze(Handle<JSObject> object);
2165 // Called the first time an object is observed with ES7 Object.observe.
2166 static void SetObserved(Handle<JSObject> object);
2169 enum DeepCopyHints { kNoHints = 0, kObjectIsShallow = 1 };
2171 MUST_USE_RESULT static MaybeHandle<JSObject> DeepCopy(
2172 Handle<JSObject> object,
2173 AllocationSiteUsageContext* site_context,
2174 DeepCopyHints hints = kNoHints);
2175 MUST_USE_RESULT static MaybeHandle<JSObject> DeepWalk(
2176 Handle<JSObject> object,
2177 AllocationSiteCreationContext* site_context);
2179 DECLARE_CAST(JSObject)
2181 // Dispatched behavior.
2182 void JSObjectShortPrint(StringStream* accumulator);
2183 DECLARE_PRINTER(JSObject)
2184 DECLARE_VERIFIER(JSObject)
2186 void PrintProperties(std::ostream& os); // NOLINT
2187 void PrintElements(std::ostream& os); // NOLINT
2189 #if defined(DEBUG) || defined(OBJECT_PRINT)
2190 void PrintTransitions(std::ostream& os); // NOLINT
2193 static void PrintElementsTransition(
2194 FILE* file, Handle<JSObject> object,
2195 ElementsKind from_kind, Handle<FixedArrayBase> from_elements,
2196 ElementsKind to_kind, Handle<FixedArrayBase> to_elements);
2198 void PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map);
2201 // Structure for collecting spill information about JSObjects.
2202 class SpillInformation {
2206 int number_of_objects_;
2207 int number_of_objects_with_fast_properties_;
2208 int number_of_objects_with_fast_elements_;
2209 int number_of_fast_used_fields_;
2210 int number_of_fast_unused_fields_;
2211 int number_of_slow_used_properties_;
2212 int number_of_slow_unused_properties_;
2213 int number_of_fast_used_elements_;
2214 int number_of_fast_unused_elements_;
2215 int number_of_slow_used_elements_;
2216 int number_of_slow_unused_elements_;
2219 void IncrementSpillStatistics(SpillInformation* info);
2223 // If a GC was caused while constructing this object, the elements pointer
2224 // may point to a one pointer filler map. The object won't be rooted, but
2225 // our heap verification code could stumble across it.
2226 bool ElementsAreSafeToExamine();
2229 Object* SlowReverseLookup(Object* value);
2231 // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2232 // Also maximal value of JSArray's length property.
2233 static const uint32_t kMaxElementCount = 0xffffffffu;
2235 // Constants for heuristics controlling conversion of fast elements
2236 // to slow elements.
2238 // Maximal gap that can be introduced by adding an element beyond
2239 // the current elements length.
2240 static const uint32_t kMaxGap = 1024;
2242 // Maximal length of fast elements array that won't be checked for
2243 // being dense enough on expansion.
2244 static const int kMaxUncheckedFastElementsLength = 5000;
2246 // Same as above but for old arrays. This limit is more strict. We
2247 // don't want to be wasteful with long lived objects.
2248 static const int kMaxUncheckedOldFastElementsLength = 500;
2250 // Note that Page::kMaxRegularHeapObjectSize puts a limit on
2251 // permissible values (see the DCHECK in heap.cc).
2252 static const int kInitialMaxFastElementArray = 100000;
2254 // This constant applies only to the initial map of "global.Object" and
2255 // not to arbitrary other JSObject maps.
2256 static const int kInitialGlobalObjectUnusedPropertiesCount = 4;
2258 static const int kMaxInstanceSize = 255 * kPointerSize;
2259 // When extending the backing storage for property values, we increase
2260 // its size by more than the 1 entry necessary, so sequentially adding fields
2261 // to the same object requires fewer allocations and copies.
2262 static const int kFieldsAdded = 3;
2264 // Layout description.
2265 static const int kPropertiesOffset = HeapObject::kHeaderSize;
2266 static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2267 static const int kHeaderSize = kElementsOffset + kPointerSize;
2269 STATIC_ASSERT(kHeaderSize == Internals::kJSObjectHeaderSize);
2271 class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2273 static inline int SizeOf(Map* map, HeapObject* object);
2276 Context* GetCreationContext();
2278 // Enqueue change record for Object.observe. May cause GC.
2279 MUST_USE_RESULT static MaybeHandle<Object> EnqueueChangeRecord(
2280 Handle<JSObject> object, const char* type, Handle<Name> name,
2281 Handle<Object> old_value);
2283 // Gets the number of currently used elements.
2284 int GetFastElementsUsage();
2286 // Deletes an existing named property in a normalized object.
2287 static void DeleteNormalizedProperty(Handle<JSObject> object,
2288 Handle<Name> name, int entry);
2290 static bool AllCanRead(LookupIterator* it);
2291 static bool AllCanWrite(LookupIterator* it);
2294 friend class JSReceiver;
2295 friend class Object;
2297 static void MigrateFastToFast(Handle<JSObject> object, Handle<Map> new_map);
2298 static void MigrateFastToSlow(Handle<JSObject> object,
2299 Handle<Map> new_map,
2300 int expected_additional_properties);
2302 // Used from Object::GetProperty().
2303 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithFailedAccessCheck(
2304 LookupIterator* it);
2306 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithFailedAccessCheck(
2307 LookupIterator* it, Handle<Object> value);
2309 // Add a property to a slow-case object.
2310 static void AddSlowProperty(Handle<JSObject> object,
2312 Handle<Object> value,
2313 PropertyAttributes attributes);
2315 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithInterceptor(
2316 LookupIterator* it);
2318 bool ReferencesObjectFromElements(FixedArray* elements,
2322 // Return the hash table backing store or the inline stored identity hash,
2323 // whatever is found.
2324 MUST_USE_RESULT Object* GetHiddenPropertiesHashTable();
2326 // Return the hash table backing store for hidden properties. If there is no
2327 // backing store, allocate one.
2328 static Handle<ObjectHashTable> GetOrCreateHiddenPropertiesHashtable(
2329 Handle<JSObject> object);
2331 // Set the hidden property backing store to either a hash table or
2332 // the inline-stored identity hash.
2333 static Handle<Object> SetHiddenPropertiesHashTable(
2334 Handle<JSObject> object,
2335 Handle<Object> value);
2337 MUST_USE_RESULT Object* GetIdentityHash();
2339 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSObject> object);
2341 static Handle<SeededNumberDictionary> GetNormalizedElementDictionary(
2342 Handle<JSObject> object, Handle<FixedArrayBase> elements);
2344 // Helper for fast versions of preventExtensions, seal, and freeze.
2345 // attrs is one of NONE, SEALED, or FROZEN (depending on the operation).
2346 template <PropertyAttributes attrs>
2347 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensionsWithTransition(
2348 Handle<JSObject> object);
2350 DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
2354 // Common superclass for FixedArrays that allow implementations to share
2355 // common accessors and some code paths.
2356 class FixedArrayBase: public HeapObject {
2358 // [length]: length of the array.
2359 inline int length() const;
2360 inline void set_length(int value);
2362 // Get and set the length using acquire loads and release stores.
2363 inline int synchronized_length() const;
2364 inline void synchronized_set_length(int value);
2366 DECLARE_CAST(FixedArrayBase)
2368 // Layout description.
2369 // Length is smi tagged when it is stored.
2370 static const int kLengthOffset = HeapObject::kHeaderSize;
2371 static const int kHeaderSize = kLengthOffset + kPointerSize;
2375 class FixedDoubleArray;
2376 class IncrementalMarking;
2379 // FixedArray describes fixed-sized arrays with element type Object*.
2380 class FixedArray: public FixedArrayBase {
2382 // Setter and getter for elements.
2383 inline Object* get(int index) const;
2384 void SetValue(uint32_t index, Object* value);
2385 static inline Handle<Object> get(Handle<FixedArray> array, int index);
2386 // Setter that uses write barrier.
2387 inline void set(int index, Object* value);
2388 inline bool is_the_hole(int index);
2390 // Setter that doesn't need write barrier.
2391 inline void set(int index, Smi* value);
2392 // Setter with explicit barrier mode.
2393 inline void set(int index, Object* value, WriteBarrierMode mode);
2395 // Setters for frequently used oddballs located in old space.
2396 inline void set_undefined(int index);
2397 inline void set_null(int index);
2398 inline void set_the_hole(int index);
2400 inline Object** GetFirstElementAddress();
2401 inline bool ContainsOnlySmisOrHoles();
2403 // Gives access to raw memory which stores the array's data.
2404 inline Object** data_start();
2406 inline void FillWithHoles(int from, int to);
2408 // Shrink length and insert filler objects.
2409 void Shrink(int length);
2412 static Handle<FixedArray> CopySize(Handle<FixedArray> array,
2414 PretenureFlag pretenure = NOT_TENURED);
2416 enum KeyFilter { ALL_KEYS, NON_SYMBOL_KEYS };
2418 // Add the elements of a JSArray to this FixedArray.
2419 MUST_USE_RESULT static MaybeHandle<FixedArray> AddKeysFromArrayLike(
2420 Handle<FixedArray> content, Handle<JSObject> array,
2421 KeyFilter filter = ALL_KEYS);
2423 // Computes the union of keys and return the result.
2424 // Used for implementing "for (n in object) { }"
2425 MUST_USE_RESULT static MaybeHandle<FixedArray> UnionOfKeys(
2426 Handle<FixedArray> first,
2427 Handle<FixedArray> second);
2429 // Copy a sub array from the receiver to dest.
2430 void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
2432 // Garbage collection support.
2433 static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
2435 // Code Generation support.
2436 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2438 // Garbage collection support.
2439 Object** RawFieldOfElementAt(int index) {
2440 return HeapObject::RawField(this, OffsetOfElementAt(index));
2443 DECLARE_CAST(FixedArray)
2445 // Maximal allowed size, in bytes, of a single FixedArray.
2446 // Prevents overflowing size computations, as well as extreme memory
2448 static const int kMaxSize = 128 * MB * kPointerSize;
2449 // Maximally allowed length of a FixedArray.
2450 static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
2452 // Dispatched behavior.
2453 DECLARE_PRINTER(FixedArray)
2454 DECLARE_VERIFIER(FixedArray)
2456 // Checks if two FixedArrays have identical contents.
2457 bool IsEqualTo(FixedArray* other);
2460 // Swap two elements in a pair of arrays. If this array and the
2461 // numbers array are the same object, the elements are only swapped
2463 void SwapPairs(FixedArray* numbers, int i, int j);
2465 // Sort prefix of this array and the numbers array as pairs wrt. the
2466 // numbers. If the numbers array and the this array are the same
2467 // object, the prefix of this array is sorted.
2468 void SortPairs(FixedArray* numbers, uint32_t len);
2470 class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
2472 static inline int SizeOf(Map* map, HeapObject* object) {
2474 reinterpret_cast<FixedArray*>(object)->synchronized_length());
2479 // Set operation on FixedArray without using write barriers. Can
2480 // only be used for storing old space objects or smis.
2481 static inline void NoWriteBarrierSet(FixedArray* array,
2485 // Set operation on FixedArray without incremental write barrier. Can
2486 // only be used if the object is guaranteed to be white (whiteness witness
2488 static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
2493 STATIC_ASSERT(kHeaderSize == Internals::kFixedArrayHeaderSize);
2495 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
2499 // FixedDoubleArray describes fixed-sized arrays with element type double.
2500 class FixedDoubleArray: public FixedArrayBase {
2502 // Setter and getter for elements.
2503 inline double get_scalar(int index);
2504 inline uint64_t get_representation(int index);
2505 static inline Handle<Object> get(Handle<FixedDoubleArray> array, int index);
2506 // This accessor has to get a Number as |value|.
2507 void SetValue(uint32_t index, Object* value);
2508 inline void set(int index, double value);
2509 inline void set_the_hole(int index);
2511 // Checking for the hole.
2512 inline bool is_the_hole(int index);
2514 // Garbage collection support.
2515 inline static int SizeFor(int length) {
2516 return kHeaderSize + length * kDoubleSize;
2519 // Gives access to raw memory which stores the array's data.
2520 inline double* data_start();
2522 inline void FillWithHoles(int from, int to);
2524 // Code Generation support.
2525 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2527 DECLARE_CAST(FixedDoubleArray)
2529 // Maximal allowed size, in bytes, of a single FixedDoubleArray.
2530 // Prevents overflowing size computations, as well as extreme memory
2532 static const int kMaxSize = 512 * MB;
2533 // Maximally allowed length of a FixedArray.
2534 static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
2536 // Dispatched behavior.
2537 DECLARE_PRINTER(FixedDoubleArray)
2538 DECLARE_VERIFIER(FixedDoubleArray)
2541 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
2545 class WeakFixedArray : public FixedArray {
2547 enum SearchForDuplicates { kAlwaysAdd, kAddIfNotFound };
2549 // If |maybe_array| is not a WeakFixedArray, a fresh one will be allocated.
2550 static Handle<WeakFixedArray> Add(
2551 Handle<Object> maybe_array, Handle<HeapObject> value,
2552 SearchForDuplicates search_for_duplicates = kAlwaysAdd,
2553 bool* was_present = NULL);
2555 // Returns true if an entry was found and removed.
2556 bool Remove(Handle<HeapObject> value);
2560 inline Object* Get(int index) const;
2561 inline void Clear(int index);
2562 inline int Length() const;
2564 inline bool IsEmptySlot(int index) const;
2565 static Object* Empty() { return Smi::FromInt(0); }
2567 DECLARE_CAST(WeakFixedArray)
2570 static const int kLastUsedIndexIndex = 0;
2571 static const int kFirstIndex = 1;
2573 static Handle<WeakFixedArray> Allocate(
2574 Isolate* isolate, int size, Handle<WeakFixedArray> initialize_from);
2576 static void Set(Handle<WeakFixedArray> array, int index,
2577 Handle<HeapObject> value);
2578 inline void clear(int index);
2580 inline int last_used_index() const;
2581 inline void set_last_used_index(int index);
2583 // Disallow inherited setters.
2584 void set(int index, Smi* value);
2585 void set(int index, Object* value);
2586 void set(int index, Object* value, WriteBarrierMode mode);
2587 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakFixedArray);
2591 // Generic array grows dynamically with O(1) amortized insertion.
2592 class ArrayList : public FixedArray {
2596 // Use this if GC can delete elements from the array.
2597 kReloadLengthAfterAllocation,
2599 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj,
2600 AddMode mode = kNone);
2601 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj1,
2602 Handle<Object> obj2, AddMode = kNone);
2603 inline int Length();
2604 inline void SetLength(int length);
2605 inline Object* Get(int index);
2606 inline Object** Slot(int index);
2607 inline void Set(int index, Object* obj);
2608 inline void Clear(int index, Object* undefined);
2609 DECLARE_CAST(ArrayList)
2612 static Handle<ArrayList> EnsureSpace(Handle<ArrayList> array, int length);
2613 static const int kLengthIndex = 0;
2614 static const int kFirstIndex = 1;
2615 DISALLOW_IMPLICIT_CONSTRUCTORS(ArrayList);
2619 // DescriptorArrays are fixed arrays used to hold instance descriptors.
2620 // The format of the these objects is:
2621 // [0]: Number of descriptors
2622 // [1]: Either Smi(0) if uninitialized, or a pointer to small fixed array:
2623 // [0]: pointer to fixed array with enum cache
2624 // [1]: either Smi(0) or pointer to fixed array with indices
2626 // [2 + number of descriptors * kDescriptorSize]: start of slack
2627 class DescriptorArray: public FixedArray {
2629 // Returns true for both shared empty_descriptor_array and for smis, which the
2630 // map uses to encode additional bit fields when the descriptor array is not
2632 inline bool IsEmpty();
2634 // Returns the number of descriptors in the array.
2635 int number_of_descriptors() {
2636 DCHECK(length() >= kFirstIndex || IsEmpty());
2638 return len == 0 ? 0 : Smi::cast(get(kDescriptorLengthIndex))->value();
2641 int number_of_descriptors_storage() {
2643 return len == 0 ? 0 : (len - kFirstIndex) / kDescriptorSize;
2646 int NumberOfSlackDescriptors() {
2647 return number_of_descriptors_storage() - number_of_descriptors();
2650 inline void SetNumberOfDescriptors(int number_of_descriptors);
2651 inline int number_of_entries() { return number_of_descriptors(); }
2653 bool HasEnumCache() {
2654 return !IsEmpty() && !get(kEnumCacheIndex)->IsSmi();
2657 void CopyEnumCacheFrom(DescriptorArray* array) {
2658 set(kEnumCacheIndex, array->get(kEnumCacheIndex));
2661 FixedArray* GetEnumCache() {
2662 DCHECK(HasEnumCache());
2663 FixedArray* bridge = FixedArray::cast(get(kEnumCacheIndex));
2664 return FixedArray::cast(bridge->get(kEnumCacheBridgeCacheIndex));
2667 bool HasEnumIndicesCache() {
2668 if (IsEmpty()) return false;
2669 Object* object = get(kEnumCacheIndex);
2670 if (object->IsSmi()) return false;
2671 FixedArray* bridge = FixedArray::cast(object);
2672 return !bridge->get(kEnumCacheBridgeIndicesCacheIndex)->IsSmi();
2675 FixedArray* GetEnumIndicesCache() {
2676 DCHECK(HasEnumIndicesCache());
2677 FixedArray* bridge = FixedArray::cast(get(kEnumCacheIndex));
2678 return FixedArray::cast(bridge->get(kEnumCacheBridgeIndicesCacheIndex));
2681 Object** GetEnumCacheSlot() {
2682 DCHECK(HasEnumCache());
2683 return HeapObject::RawField(reinterpret_cast<HeapObject*>(this),
2687 void ClearEnumCache();
2689 // Initialize or change the enum cache,
2690 // using the supplied storage for the small "bridge".
2691 void SetEnumCache(FixedArray* bridge_storage,
2692 FixedArray* new_cache,
2693 Object* new_index_cache);
2695 bool CanHoldValue(int descriptor, Object* value);
2697 // Accessors for fetching instance descriptor at descriptor number.
2698 inline Name* GetKey(int descriptor_number);
2699 inline Object** GetKeySlot(int descriptor_number);
2700 inline Object* GetValue(int descriptor_number);
2701 inline void SetValue(int descriptor_number, Object* value);
2702 inline Object** GetValueSlot(int descriptor_number);
2703 static inline int GetValueOffset(int descriptor_number);
2704 inline Object** GetDescriptorStartSlot(int descriptor_number);
2705 inline Object** GetDescriptorEndSlot(int descriptor_number);
2706 inline PropertyDetails GetDetails(int descriptor_number);
2707 inline PropertyType GetType(int descriptor_number);
2708 inline int GetFieldIndex(int descriptor_number);
2709 inline HeapType* GetFieldType(int descriptor_number);
2710 inline Object* GetConstant(int descriptor_number);
2711 inline Object* GetCallbacksObject(int descriptor_number);
2712 inline AccessorDescriptor* GetCallbacks(int descriptor_number);
2714 inline Name* GetSortedKey(int descriptor_number);
2715 inline int GetSortedKeyIndex(int descriptor_number);
2716 inline void SetSortedKey(int pointer, int descriptor_number);
2717 inline void SetRepresentation(int descriptor_number,
2718 Representation representation);
2720 // Accessor for complete descriptor.
2721 inline void Get(int descriptor_number, Descriptor* desc);
2722 inline void Set(int descriptor_number, Descriptor* desc);
2723 void Replace(int descriptor_number, Descriptor* descriptor);
2725 // Append automatically sets the enumeration index. This should only be used
2726 // to add descriptors in bulk at the end, followed by sorting the descriptor
2728 inline void Append(Descriptor* desc);
2730 static Handle<DescriptorArray> CopyUpTo(Handle<DescriptorArray> desc,
2731 int enumeration_index,
2734 static Handle<DescriptorArray> CopyUpToAddAttributes(
2735 Handle<DescriptorArray> desc,
2736 int enumeration_index,
2737 PropertyAttributes attributes,
2740 // Sort the instance descriptors by the hash codes of their keys.
2743 // Search the instance descriptors for given name.
2744 INLINE(int Search(Name* name, int number_of_own_descriptors));
2746 // As the above, but uses DescriptorLookupCache and updates it when
2748 INLINE(int SearchWithCache(Name* name, Map* map));
2750 // Allocates a DescriptorArray, but returns the singleton
2751 // empty descriptor array object if number_of_descriptors is 0.
2752 static Handle<DescriptorArray> Allocate(Isolate* isolate,
2753 int number_of_descriptors,
2756 DECLARE_CAST(DescriptorArray)
2758 // Constant for denoting key was not found.
2759 static const int kNotFound = -1;
2761 static const int kDescriptorLengthIndex = 0;
2762 static const int kEnumCacheIndex = 1;
2763 static const int kFirstIndex = 2;
2765 // The length of the "bridge" to the enum cache.
2766 static const int kEnumCacheBridgeLength = 2;
2767 static const int kEnumCacheBridgeCacheIndex = 0;
2768 static const int kEnumCacheBridgeIndicesCacheIndex = 1;
2770 // Layout description.
2771 static const int kDescriptorLengthOffset = FixedArray::kHeaderSize;
2772 static const int kEnumCacheOffset = kDescriptorLengthOffset + kPointerSize;
2773 static const int kFirstOffset = kEnumCacheOffset + kPointerSize;
2775 // Layout description for the bridge array.
2776 static const int kEnumCacheBridgeCacheOffset = FixedArray::kHeaderSize;
2778 // Layout of descriptor.
2779 static const int kDescriptorKey = 0;
2780 static const int kDescriptorDetails = 1;
2781 static const int kDescriptorValue = 2;
2782 static const int kDescriptorSize = 3;
2784 #if defined(DEBUG) || defined(OBJECT_PRINT)
2785 // For our gdb macros, we should perhaps change these in the future.
2788 // Print all the descriptors.
2789 void PrintDescriptors(std::ostream& os); // NOLINT
2793 // Is the descriptor array sorted and without duplicates?
2794 bool IsSortedNoDuplicates(int valid_descriptors = -1);
2796 // Is the descriptor array consistent with the back pointers in targets?
2797 bool IsConsistentWithBackPointers(Map* current_map);
2799 // Are two DescriptorArrays equal?
2800 bool IsEqualTo(DescriptorArray* other);
2803 // Returns the fixed array length required to hold number_of_descriptors
2805 static int LengthFor(int number_of_descriptors) {
2806 return ToKeyIndex(number_of_descriptors);
2810 // WhitenessWitness is used to prove that a descriptor array is white
2811 // (unmarked), so incremental write barriers can be skipped because the
2812 // marking invariant cannot be broken and slots pointing into evacuation
2813 // candidates will be discovered when the object is scanned. A witness is
2814 // always stack-allocated right after creating an array. By allocating a
2815 // witness, incremental marking is globally disabled. The witness is then
2816 // passed along wherever needed to statically prove that the array is known to
2818 class WhitenessWitness {
2820 inline explicit WhitenessWitness(DescriptorArray* array);
2821 inline ~WhitenessWitness();
2824 IncrementalMarking* marking_;
2827 // An entry in a DescriptorArray, represented as an (array, index) pair.
2830 inline explicit Entry(DescriptorArray* descs, int index) :
2831 descs_(descs), index_(index) { }
2833 inline PropertyType type() { return descs_->GetType(index_); }
2834 inline Object* GetCallbackObject() { return descs_->GetValue(index_); }
2837 DescriptorArray* descs_;
2841 // Conversion from descriptor number to array indices.
2842 static int ToKeyIndex(int descriptor_number) {
2843 return kFirstIndex +
2844 (descriptor_number * kDescriptorSize) +
2848 static int ToDetailsIndex(int descriptor_number) {
2849 return kFirstIndex +
2850 (descriptor_number * kDescriptorSize) +
2854 static int ToValueIndex(int descriptor_number) {
2855 return kFirstIndex +
2856 (descriptor_number * kDescriptorSize) +
2860 // Transfer a complete descriptor from the src descriptor array to this
2861 // descriptor array.
2862 void CopyFrom(int index, DescriptorArray* src, const WhitenessWitness&);
2864 inline void Set(int descriptor_number,
2866 const WhitenessWitness&);
2868 // Swap first and second descriptor.
2869 inline void SwapSortedKeys(int first, int second);
2871 DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
2875 enum SearchMode { ALL_ENTRIES, VALID_ENTRIES };
2877 template <SearchMode search_mode, typename T>
2878 inline int Search(T* array, Name* name, int valid_entries = 0,
2879 int* out_insertion_index = NULL);
2882 // HashTable is a subclass of FixedArray that implements a hash table
2883 // that uses open addressing and quadratic probing.
2885 // In order for the quadratic probing to work, elements that have not
2886 // yet been used and elements that have been deleted are
2887 // distinguished. Probing continues when deleted elements are
2888 // encountered and stops when unused elements are encountered.
2890 // - Elements with key == undefined have not been used yet.
2891 // - Elements with key == the_hole have been deleted.
2893 // The hash table class is parameterized with a Shape and a Key.
2894 // Shape must be a class with the following interface:
2895 // class ExampleShape {
2897 // // Tells whether key matches other.
2898 // static bool IsMatch(Key key, Object* other);
2899 // // Returns the hash value for key.
2900 // static uint32_t Hash(Key key);
2901 // // Returns the hash value for object.
2902 // static uint32_t HashForObject(Key key, Object* object);
2903 // // Convert key to an object.
2904 // static inline Handle<Object> AsHandle(Isolate* isolate, Key key);
2905 // // The prefix size indicates number of elements in the beginning
2906 // // of the backing storage.
2907 // static const int kPrefixSize = ..;
2908 // // The Element size indicates number of elements per entry.
2909 // static const int kEntrySize = ..;
2911 // The prefix size indicates an amount of memory in the
2912 // beginning of the backing storage that can be used for non-element
2913 // information by subclasses.
2915 template<typename Key>
2918 static const bool UsesSeed = false;
2919 static uint32_t Hash(Key key) { return 0; }
2920 static uint32_t SeededHash(Key key, uint32_t seed) {
2924 static uint32_t HashForObject(Key key, Object* object) { return 0; }
2925 static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
2927 return HashForObject(key, object);
2932 class HashTableBase : public FixedArray {
2934 // Returns the number of elements in the hash table.
2935 int NumberOfElements() {
2936 return Smi::cast(get(kNumberOfElementsIndex))->value();
2939 // Returns the number of deleted elements in the hash table.
2940 int NumberOfDeletedElements() {
2941 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
2944 // Returns the capacity of the hash table.
2946 return Smi::cast(get(kCapacityIndex))->value();
2949 // ElementAdded should be called whenever an element is added to a
2951 void ElementAdded() { SetNumberOfElements(NumberOfElements() + 1); }
2953 // ElementRemoved should be called whenever an element is removed from
2955 void ElementRemoved() {
2956 SetNumberOfElements(NumberOfElements() - 1);
2957 SetNumberOfDeletedElements(NumberOfDeletedElements() + 1);
2959 void ElementsRemoved(int n) {
2960 SetNumberOfElements(NumberOfElements() - n);
2961 SetNumberOfDeletedElements(NumberOfDeletedElements() + n);
2964 // Computes the required capacity for a table holding the given
2965 // number of elements. May be more than HashTable::kMaxCapacity.
2966 static inline int ComputeCapacity(int at_least_space_for);
2968 // Use a different heuristic to compute capacity when serializing.
2969 static inline int ComputeCapacityForSerialization(int at_least_space_for);
2971 // Tells whether k is a real key. The hole and undefined are not allowed
2972 // as keys and can be used to indicate missing or deleted elements.
2973 bool IsKey(Object* k) {
2974 return !k->IsTheHole() && !k->IsUndefined();
2977 // Compute the probe offset (quadratic probing).
2978 INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
2979 return (n + n * n) >> 1;
2982 static const int kNumberOfElementsIndex = 0;
2983 static const int kNumberOfDeletedElementsIndex = 1;
2984 static const int kCapacityIndex = 2;
2985 static const int kPrefixStartIndex = 3;
2987 // Constant used for denoting a absent entry.
2988 static const int kNotFound = -1;
2991 // Update the number of elements in the hash table.
2992 void SetNumberOfElements(int nof) {
2993 set(kNumberOfElementsIndex, Smi::FromInt(nof));
2996 // Update the number of deleted elements in the hash table.
2997 void SetNumberOfDeletedElements(int nod) {
2998 set(kNumberOfDeletedElementsIndex, Smi::FromInt(nod));
3001 // Returns probe entry.
3002 static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
3003 DCHECK(base::bits::IsPowerOfTwo32(size));
3004 return (hash + GetProbeOffset(number)) & (size - 1);
3007 inline static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
3008 return hash & (size - 1);
3011 inline static uint32_t NextProbe(
3012 uint32_t last, uint32_t number, uint32_t size) {
3013 return (last + number) & (size - 1);
3018 template <typename Derived, typename Shape, typename Key>
3019 class HashTable : public HashTableBase {
3022 inline uint32_t Hash(Key key) {
3023 if (Shape::UsesSeed) {
3024 return Shape::SeededHash(key, GetHeap()->HashSeed());
3026 return Shape::Hash(key);
3030 inline uint32_t HashForObject(Key key, Object* object) {
3031 if (Shape::UsesSeed) {
3032 return Shape::SeededHashForObject(key, GetHeap()->HashSeed(), object);
3034 return Shape::HashForObject(key, object);
3038 // Returns a new HashTable object.
3039 MUST_USE_RESULT static Handle<Derived> New(
3040 Isolate* isolate, int at_least_space_for,
3041 MinimumCapacity capacity_option = USE_DEFAULT_MINIMUM_CAPACITY,
3042 PretenureFlag pretenure = NOT_TENURED);
3044 DECLARE_CAST(HashTable)
3046 // Garbage collection support.
3047 void IteratePrefix(ObjectVisitor* visitor);
3048 void IterateElements(ObjectVisitor* visitor);
3050 // Find entry for key otherwise return kNotFound.
3051 inline int FindEntry(Key key);
3052 inline int FindEntry(Isolate* isolate, Key key, int32_t hash);
3053 int FindEntry(Isolate* isolate, Key key);
3055 // Rehashes the table in-place.
3056 void Rehash(Key key);
3058 // Returns the key at entry.
3059 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3061 static const int kElementsStartIndex = kPrefixStartIndex + Shape::kPrefixSize;
3062 static const int kEntrySize = Shape::kEntrySize;
3063 static const int kElementsStartOffset =
3064 kHeaderSize + kElementsStartIndex * kPointerSize;
3065 static const int kCapacityOffset =
3066 kHeaderSize + kCapacityIndex * kPointerSize;
3068 // Returns the index for an entry (of the key)
3069 static inline int EntryToIndex(int entry) {
3070 return (entry * kEntrySize) + kElementsStartIndex;
3074 friend class ObjectHashTable;
3076 // Find the entry at which to insert element with the given key that
3077 // has the given hash value.
3078 uint32_t FindInsertionEntry(uint32_t hash);
3080 // Attempt to shrink hash table after removal of key.
3081 MUST_USE_RESULT static Handle<Derived> Shrink(Handle<Derived> table, Key key);
3083 // Ensure enough space for n additional elements.
3084 MUST_USE_RESULT static Handle<Derived> EnsureCapacity(
3085 Handle<Derived> table,
3088 PretenureFlag pretenure = NOT_TENURED);
3090 // Sets the capacity of the hash table.
3091 void SetCapacity(int capacity) {
3092 // To scale a computed hash code to fit within the hash table, we
3093 // use bit-wise AND with a mask, so the capacity must be positive
3095 DCHECK(capacity > 0);
3096 DCHECK(capacity <= kMaxCapacity);
3097 set(kCapacityIndex, Smi::FromInt(capacity));
3100 // Maximal capacity of HashTable. Based on maximal length of underlying
3101 // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
3103 static const int kMaxCapacity =
3104 (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
3107 // Returns _expected_ if one of entries given by the first _probe_ probes is
3108 // equal to _expected_. Otherwise, returns the entry given by the probe
3110 uint32_t EntryForProbe(Key key, Object* k, int probe, uint32_t expected);
3112 void Swap(uint32_t entry1, uint32_t entry2, WriteBarrierMode mode);
3114 // Rehashes this hash-table into the new table.
3115 void Rehash(Handle<Derived> new_table, Key key);
3119 // HashTableKey is an abstract superclass for virtual key behavior.
3120 class HashTableKey {
3122 // Returns whether the other object matches this key.
3123 virtual bool IsMatch(Object* other) = 0;
3124 // Returns the hash value for this key.
3125 virtual uint32_t Hash() = 0;
3126 // Returns the hash value for object.
3127 virtual uint32_t HashForObject(Object* key) = 0;
3128 // Returns the key object for storing into the hash table.
3129 MUST_USE_RESULT virtual Handle<Object> AsHandle(Isolate* isolate) = 0;
3131 virtual ~HashTableKey() {}
3135 class StringTableShape : public BaseShape<HashTableKey*> {
3137 static inline bool IsMatch(HashTableKey* key, Object* value) {
3138 return key->IsMatch(value);
3141 static inline uint32_t Hash(HashTableKey* key) {
3145 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3146 return key->HashForObject(object);
3149 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3151 static const int kPrefixSize = 0;
3152 static const int kEntrySize = 1;
3155 class SeqOneByteString;
3159 // No special elements in the prefix and the element size is 1
3160 // because only the string itself (the key) needs to be stored.
3161 class StringTable: public HashTable<StringTable,
3165 // Find string in the string table. If it is not there yet, it is
3166 // added. The return value is the string found.
3167 static Handle<String> LookupString(Isolate* isolate, Handle<String> key);
3168 static Handle<String> LookupKey(Isolate* isolate, HashTableKey* key);
3169 static String* LookupKeyIfExists(Isolate* isolate, HashTableKey* key);
3171 // Tries to internalize given string and returns string handle on success
3172 // or an empty handle otherwise.
3173 MUST_USE_RESULT static MaybeHandle<String> InternalizeStringIfExists(
3175 Handle<String> string);
3177 // Looks up a string that is equal to the given string and returns
3178 // string handle if it is found, or an empty handle otherwise.
3179 MUST_USE_RESULT static MaybeHandle<String> LookupStringIfExists(
3181 Handle<String> str);
3182 MUST_USE_RESULT static MaybeHandle<String> LookupTwoCharsStringIfExists(
3187 static void EnsureCapacityForDeserialization(Isolate* isolate, int expected);
3189 DECLARE_CAST(StringTable)
3192 template <bool seq_one_byte>
3193 friend class JsonParser;
3195 DISALLOW_IMPLICIT_CONSTRUCTORS(StringTable);
3199 template <typename Derived, typename Shape, typename Key>
3200 class Dictionary: public HashTable<Derived, Shape, Key> {
3201 typedef HashTable<Derived, Shape, Key> DerivedHashTable;
3204 // Returns the value at entry.
3205 Object* ValueAt(int entry) {
3206 return this->get(Derived::EntryToIndex(entry) + 1);
3209 // Set the value for entry.
3210 void ValueAtPut(int entry, Object* value) {
3211 this->set(Derived::EntryToIndex(entry) + 1, value);
3214 // Returns the property details for the property at entry.
3215 PropertyDetails DetailsAt(int entry) {
3216 return Shape::DetailsAt(static_cast<Derived*>(this), entry);
3219 // Set the details for entry.
3220 void DetailsAtPut(int entry, PropertyDetails value) {
3221 Shape::DetailsAtPut(static_cast<Derived*>(this), entry, value);
3224 // Returns true if property at given entry is deleted.
3225 bool IsDeleted(int entry) {
3226 return Shape::IsDeleted(static_cast<Derived*>(this), entry);
3229 // Delete a property from the dictionary.
3230 static Handle<Object> DeleteProperty(Handle<Derived> dictionary, int entry);
3232 // Attempt to shrink the dictionary after deletion of key.
3233 MUST_USE_RESULT static inline Handle<Derived> Shrink(
3234 Handle<Derived> dictionary,
3236 return DerivedHashTable::Shrink(dictionary, key);
3240 // TODO(dcarney): templatize or move to SeededNumberDictionary
3241 void CopyValuesTo(FixedArray* elements);
3243 // Returns the number of elements in the dictionary filtering out properties
3244 // with the specified attributes.
3245 int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3247 // Returns the number of enumerable elements in the dictionary.
3248 int NumberOfEnumElements() {
3249 return NumberOfElementsFilterAttributes(
3250 static_cast<PropertyAttributes>(DONT_ENUM | SYMBOLIC));
3253 // Returns true if the dictionary contains any elements that are non-writable,
3254 // non-configurable, non-enumerable, or have getters/setters.
3255 bool HasComplexElements();
3257 enum SortMode { UNSORTED, SORTED };
3259 // Fill in details for properties into storage.
3260 // Returns the number of properties added.
3261 int CopyKeysTo(FixedArray* storage, int index, PropertyAttributes filter,
3262 SortMode sort_mode);
3264 // Copies enumerable keys to preallocated fixed array.
3265 void CopyEnumKeysTo(FixedArray* storage);
3267 // Accessors for next enumeration index.
3268 void SetNextEnumerationIndex(int index) {
3270 this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
3273 int NextEnumerationIndex() {
3274 return Smi::cast(this->get(kNextEnumerationIndexIndex))->value();
3277 // Creates a new dictionary.
3278 MUST_USE_RESULT static Handle<Derived> New(
3280 int at_least_space_for,
3281 PretenureFlag pretenure = NOT_TENURED);
3283 // Ensure enough space for n additional elements.
3284 static Handle<Derived> EnsureCapacity(Handle<Derived> obj, int n, Key key);
3287 void Print(std::ostream& os); // NOLINT
3289 // Returns the key (slow).
3290 Object* SlowReverseLookup(Object* value);
3292 // Sets the entry to (key, value) pair.
3293 inline void SetEntry(int entry,
3295 Handle<Object> value);
3296 inline void SetEntry(int entry,
3298 Handle<Object> value,
3299 PropertyDetails details);
3301 MUST_USE_RESULT static Handle<Derived> Add(
3302 Handle<Derived> dictionary,
3304 Handle<Object> value,
3305 PropertyDetails details);
3307 // Returns iteration indices array for the |dictionary|.
3308 // Values are direct indices in the |HashTable| array.
3309 static Handle<FixedArray> BuildIterationIndicesArray(
3310 Handle<Derived> dictionary);
3313 // Generic at put operation.
3314 MUST_USE_RESULT static Handle<Derived> AtPut(
3315 Handle<Derived> dictionary,
3317 Handle<Object> value);
3319 // Add entry to dictionary.
3320 static void AddEntry(
3321 Handle<Derived> dictionary,
3323 Handle<Object> value,
3324 PropertyDetails details,
3327 // Generate new enumeration indices to avoid enumeration index overflow.
3328 // Returns iteration indices array for the |dictionary|.
3329 static Handle<FixedArray> GenerateNewEnumerationIndices(
3330 Handle<Derived> dictionary);
3331 static const int kMaxNumberKeyIndex = DerivedHashTable::kPrefixStartIndex;
3332 static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
3336 template <typename Derived, typename Shape>
3337 class NameDictionaryBase : public Dictionary<Derived, Shape, Handle<Name> > {
3338 typedef Dictionary<Derived, Shape, Handle<Name> > DerivedDictionary;
3341 // Find entry for key, otherwise return kNotFound. Optimized version of
3342 // HashTable::FindEntry.
3343 int FindEntry(Handle<Name> key);
3347 template <typename Key>
3348 class BaseDictionaryShape : public BaseShape<Key> {
3350 template <typename Dictionary>
3351 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry) {
3352 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3353 DCHECK(entry >= 0); // Not found is -1, which is not caught by get().
3354 return PropertyDetails(
3355 Smi::cast(dict->get(Dictionary::EntryToIndex(entry) + 2)));
3358 template <typename Dictionary>
3359 static inline void DetailsAtPut(Dictionary* dict, int entry,
3360 PropertyDetails value) {
3361 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3362 dict->set(Dictionary::EntryToIndex(entry) + 2, value.AsSmi());
3365 template <typename Dictionary>
3366 static bool IsDeleted(Dictionary* dict, int entry) {
3370 template <typename Dictionary>
3371 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3372 Handle<Object> value, PropertyDetails details);
3376 class NameDictionaryShape : public BaseDictionaryShape<Handle<Name> > {
3378 static inline bool IsMatch(Handle<Name> key, Object* other);
3379 static inline uint32_t Hash(Handle<Name> key);
3380 static inline uint32_t HashForObject(Handle<Name> key, Object* object);
3381 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Name> key);
3382 static const int kPrefixSize = 2;
3383 static const int kEntrySize = 3;
3384 static const bool kIsEnumerable = true;
3388 class NameDictionary
3389 : public NameDictionaryBase<NameDictionary, NameDictionaryShape> {
3390 typedef NameDictionaryBase<NameDictionary, NameDictionaryShape>
3394 DECLARE_CAST(NameDictionary)
3396 inline static Handle<FixedArray> DoGenerateNewEnumerationIndices(
3397 Handle<NameDictionary> dictionary);
3401 class GlobalDictionaryShape : public NameDictionaryShape {
3403 static const int kEntrySize = 2; // Overrides NameDictionaryShape::kEntrySize
3405 template <typename Dictionary>
3406 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry);
3408 template <typename Dictionary>
3409 static inline void DetailsAtPut(Dictionary* dict, int entry,
3410 PropertyDetails value);
3412 template <typename Dictionary>
3413 static bool IsDeleted(Dictionary* dict, int entry);
3415 template <typename Dictionary>
3416 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3417 Handle<Object> value, PropertyDetails details);
3421 class GlobalDictionary
3422 : public NameDictionaryBase<GlobalDictionary, GlobalDictionaryShape> {
3424 DECLARE_CAST(GlobalDictionary)
3428 class NumberDictionaryShape : public BaseDictionaryShape<uint32_t> {
3430 static inline bool IsMatch(uint32_t key, Object* other);
3431 static inline Handle<Object> AsHandle(Isolate* isolate, uint32_t key);
3432 static const int kEntrySize = 3;
3433 static const bool kIsEnumerable = false;
3437 class SeededNumberDictionaryShape : public NumberDictionaryShape {
3439 static const bool UsesSeed = true;
3440 static const int kPrefixSize = 2;
3442 static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
3443 static inline uint32_t SeededHashForObject(uint32_t key,
3449 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
3451 static const int kPrefixSize = 0;
3453 static inline uint32_t Hash(uint32_t key);
3454 static inline uint32_t HashForObject(uint32_t key, Object* object);
3458 class SeededNumberDictionary
3459 : public Dictionary<SeededNumberDictionary,
3460 SeededNumberDictionaryShape,
3463 DECLARE_CAST(SeededNumberDictionary)
3465 // Type specific at put (default NONE attributes is used when adding).
3466 MUST_USE_RESULT static Handle<SeededNumberDictionary> AtNumberPut(
3467 Handle<SeededNumberDictionary> dictionary,
3469 Handle<Object> value);
3470 MUST_USE_RESULT static Handle<SeededNumberDictionary> AddNumberEntry(
3471 Handle<SeededNumberDictionary> dictionary,
3473 Handle<Object> value,
3474 PropertyDetails details);
3476 // Set an existing entry or add a new one if needed.
3477 // Return the updated dictionary.
3478 MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
3479 Handle<SeededNumberDictionary> dictionary,
3481 Handle<Object> value,
3482 PropertyDetails details);
3484 void UpdateMaxNumberKey(uint32_t key);
3486 // If slow elements are required we will never go back to fast-case
3487 // for the elements kept in this dictionary. We require slow
3488 // elements if an element has been added at an index larger than
3489 // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
3490 // when defining a getter or setter with a number key.
3491 inline bool requires_slow_elements();
3492 inline void set_requires_slow_elements();
3494 // Get the value of the max number key that has been added to this
3495 // dictionary. max_number_key can only be called if
3496 // requires_slow_elements returns false.
3497 inline uint32_t max_number_key();
3500 static const int kRequiresSlowElementsMask = 1;
3501 static const int kRequiresSlowElementsTagSize = 1;
3502 static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
3506 class UnseededNumberDictionary
3507 : public Dictionary<UnseededNumberDictionary,
3508 UnseededNumberDictionaryShape,
3511 DECLARE_CAST(UnseededNumberDictionary)
3513 // Type specific at put (default NONE attributes is used when adding).
3514 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AtNumberPut(
3515 Handle<UnseededNumberDictionary> dictionary,
3517 Handle<Object> value);
3518 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AddNumberEntry(
3519 Handle<UnseededNumberDictionary> dictionary,
3521 Handle<Object> value);
3523 // Set an existing entry or add a new one if needed.
3524 // Return the updated dictionary.
3525 MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
3526 Handle<UnseededNumberDictionary> dictionary,
3528 Handle<Object> value);
3532 class ObjectHashTableShape : public BaseShape<Handle<Object> > {
3534 static inline bool IsMatch(Handle<Object> key, Object* other);
3535 static inline uint32_t Hash(Handle<Object> key);
3536 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3537 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3538 static const int kPrefixSize = 0;
3539 static const int kEntrySize = 2;
3543 // ObjectHashTable maps keys that are arbitrary objects to object values by
3544 // using the identity hash of the key for hashing purposes.
3545 class ObjectHashTable: public HashTable<ObjectHashTable,
3546 ObjectHashTableShape,
3549 ObjectHashTable, ObjectHashTableShape, Handle<Object> > DerivedHashTable;
3551 DECLARE_CAST(ObjectHashTable)
3553 // Attempt to shrink hash table after removal of key.
3554 MUST_USE_RESULT static inline Handle<ObjectHashTable> Shrink(
3555 Handle<ObjectHashTable> table,
3556 Handle<Object> key);
3558 // Looks up the value associated with the given key. The hole value is
3559 // returned in case the key is not present.
3560 Object* Lookup(Handle<Object> key);
3561 Object* Lookup(Handle<Object> key, int32_t hash);
3562 Object* Lookup(Isolate* isolate, Handle<Object> key, int32_t hash);
3564 // Adds (or overwrites) the value associated with the given key.
3565 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3567 Handle<Object> value);
3568 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3569 Handle<Object> key, Handle<Object> value,
3572 // Returns an ObjectHashTable (possibly |table|) where |key| has been removed.
3573 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3576 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3577 Handle<Object> key, bool* was_present,
3581 friend class MarkCompactCollector;
3583 void AddEntry(int entry, Object* key, Object* value);
3584 void RemoveEntry(int entry);
3586 // Returns the index to the value of an entry.
3587 static inline int EntryToValueIndex(int entry) {
3588 return EntryToIndex(entry) + 1;
3593 // OrderedHashTable is a HashTable with Object keys that preserves
3594 // insertion order. There are Map and Set interfaces (OrderedHashMap
3595 // and OrderedHashTable, below). It is meant to be used by JSMap/JSSet.
3597 // Only Object* keys are supported, with Object::SameValueZero() used as the
3598 // equality operator and Object::GetHash() for the hash function.
3600 // Based on the "Deterministic Hash Table" as described by Jason Orendorff at
3601 // https://wiki.mozilla.org/User:Jorend/Deterministic_hash_tables
3602 // Originally attributed to Tyler Close.
3605 // [0]: bucket count
3606 // [1]: element count
3607 // [2]: deleted element count
3608 // [3..(3 + NumberOfBuckets() - 1)]: "hash table", where each item is an
3609 // offset into the data table (see below) where the
3610 // first item in this bucket is stored.
3611 // [3 + NumberOfBuckets()..length]: "data table", an array of length
3612 // Capacity() * kEntrySize, where the first entrysize
3613 // items are handled by the derived class and the
3614 // item at kChainOffset is another entry into the
3615 // data table indicating the next entry in this hash
3618 // When we transition the table to a new version we obsolete it and reuse parts
3619 // of the memory to store information how to transition an iterator to the new
3622 // Memory layout for obsolete table:
3623 // [0]: bucket count
3624 // [1]: Next newer table
3625 // [2]: Number of removed holes or -1 when the table was cleared.
3626 // [3..(3 + NumberOfRemovedHoles() - 1)]: The indexes of the removed holes.
3627 // [3 + NumberOfRemovedHoles()..length]: Not used
3629 template<class Derived, class Iterator, int entrysize>
3630 class OrderedHashTable: public FixedArray {
3632 // Returns an OrderedHashTable with a capacity of at least |capacity|.
3633 static Handle<Derived> Allocate(
3634 Isolate* isolate, int capacity, PretenureFlag pretenure = NOT_TENURED);
3636 // Returns an OrderedHashTable (possibly |table|) with enough space
3637 // to add at least one new element.
3638 static Handle<Derived> EnsureGrowable(Handle<Derived> table);
3640 // Returns an OrderedHashTable (possibly |table|) that's shrunken
3642 static Handle<Derived> Shrink(Handle<Derived> table);
3644 // Returns a new empty OrderedHashTable and records the clearing so that
3645 // exisiting iterators can be updated.
3646 static Handle<Derived> Clear(Handle<Derived> table);
3648 int NumberOfElements() {
3649 return Smi::cast(get(kNumberOfElementsIndex))->value();
3652 int NumberOfDeletedElements() {
3653 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3656 int UsedCapacity() { return NumberOfElements() + NumberOfDeletedElements(); }
3658 int NumberOfBuckets() {
3659 return Smi::cast(get(kNumberOfBucketsIndex))->value();
3662 // Returns an index into |this| for the given entry.
3663 int EntryToIndex(int entry) {
3664 return kHashTableStartIndex + NumberOfBuckets() + (entry * kEntrySize);
3667 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3670 return !get(kNextTableIndex)->IsSmi();
3673 // The next newer table. This is only valid if the table is obsolete.
3674 Derived* NextTable() {
3675 return Derived::cast(get(kNextTableIndex));
3678 // When the table is obsolete we store the indexes of the removed holes.
3679 int RemovedIndexAt(int index) {
3680 return Smi::cast(get(kRemovedHolesIndex + index))->value();
3683 static const int kNotFound = -1;
3684 static const int kMinCapacity = 4;
3686 static const int kNumberOfBucketsIndex = 0;
3687 static const int kNumberOfElementsIndex = kNumberOfBucketsIndex + 1;
3688 static const int kNumberOfDeletedElementsIndex = kNumberOfElementsIndex + 1;
3689 static const int kHashTableStartIndex = kNumberOfDeletedElementsIndex + 1;
3690 static const int kNextTableIndex = kNumberOfElementsIndex;
3692 static const int kNumberOfBucketsOffset =
3693 kHeaderSize + kNumberOfBucketsIndex * kPointerSize;
3694 static const int kNumberOfElementsOffset =
3695 kHeaderSize + kNumberOfElementsIndex * kPointerSize;
3696 static const int kNumberOfDeletedElementsOffset =
3697 kHeaderSize + kNumberOfDeletedElementsIndex * kPointerSize;
3698 static const int kHashTableStartOffset =
3699 kHeaderSize + kHashTableStartIndex * kPointerSize;
3700 static const int kNextTableOffset =
3701 kHeaderSize + kNextTableIndex * kPointerSize;
3703 static const int kEntrySize = entrysize + 1;
3704 static const int kChainOffset = entrysize;
3706 static const int kLoadFactor = 2;
3708 // NumberOfDeletedElements is set to kClearedTableSentinel when
3709 // the table is cleared, which allows iterator transitions to
3710 // optimize that case.
3711 static const int kClearedTableSentinel = -1;
3714 static Handle<Derived> Rehash(Handle<Derived> table, int new_capacity);
3716 void SetNumberOfBuckets(int num) {
3717 set(kNumberOfBucketsIndex, Smi::FromInt(num));
3720 void SetNumberOfElements(int num) {
3721 set(kNumberOfElementsIndex, Smi::FromInt(num));
3724 void SetNumberOfDeletedElements(int num) {
3725 set(kNumberOfDeletedElementsIndex, Smi::FromInt(num));
3729 return NumberOfBuckets() * kLoadFactor;
3732 void SetNextTable(Derived* next_table) {
3733 set(kNextTableIndex, next_table);
3736 void SetRemovedIndexAt(int index, int removed_index) {
3737 return set(kRemovedHolesIndex + index, Smi::FromInt(removed_index));
3740 static const int kRemovedHolesIndex = kHashTableStartIndex;
3742 static const int kMaxCapacity =
3743 (FixedArray::kMaxLength - kHashTableStartIndex)
3744 / (1 + (kEntrySize * kLoadFactor));
3748 class JSSetIterator;
3751 class OrderedHashSet: public OrderedHashTable<
3752 OrderedHashSet, JSSetIterator, 1> {
3754 DECLARE_CAST(OrderedHashSet)
3758 class JSMapIterator;
3761 class OrderedHashMap
3762 : public OrderedHashTable<OrderedHashMap, JSMapIterator, 2> {
3764 DECLARE_CAST(OrderedHashMap)
3766 Object* ValueAt(int entry) {
3767 return get(EntryToIndex(entry) + kValueOffset);
3770 static const int kValueOffset = 1;
3774 template <int entrysize>
3775 class WeakHashTableShape : public BaseShape<Handle<Object> > {
3777 static inline bool IsMatch(Handle<Object> key, Object* other);
3778 static inline uint32_t Hash(Handle<Object> key);
3779 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3780 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3781 static const int kPrefixSize = 0;
3782 static const int kEntrySize = entrysize;
3786 // WeakHashTable maps keys that are arbitrary heap objects to heap object
3787 // values. The table wraps the keys in weak cells and store values directly.
3788 // Thus it references keys weakly and values strongly.
3789 class WeakHashTable: public HashTable<WeakHashTable,
3790 WeakHashTableShape<2>,
3793 WeakHashTable, WeakHashTableShape<2>, Handle<Object> > DerivedHashTable;
3795 DECLARE_CAST(WeakHashTable)
3797 // Looks up the value associated with the given key. The hole value is
3798 // returned in case the key is not present.
3799 Object* Lookup(Handle<HeapObject> key);
3801 // Adds (or overwrites) the value associated with the given key. Mapping a
3802 // key to the hole value causes removal of the whole entry.
3803 MUST_USE_RESULT static Handle<WeakHashTable> Put(Handle<WeakHashTable> table,
3804 Handle<HeapObject> key,
3805 Handle<HeapObject> value);
3807 static Handle<FixedArray> GetValues(Handle<WeakHashTable> table);
3810 friend class MarkCompactCollector;
3812 void AddEntry(int entry, Handle<WeakCell> key, Handle<HeapObject> value);
3814 // Returns the index to the value of an entry.
3815 static inline int EntryToValueIndex(int entry) {
3816 return EntryToIndex(entry) + 1;
3821 class WeakValueHashTable : public ObjectHashTable {
3823 DECLARE_CAST(WeakValueHashTable)
3826 // Looks up the value associated with the given key. The hole value is
3827 // returned in case the key is not present.
3828 Object* LookupWeak(Handle<Object> key);
3831 // Adds (or overwrites) the value associated with the given key. Mapping a
3832 // key to the hole value causes removal of the whole entry.
3833 MUST_USE_RESULT static Handle<WeakValueHashTable> PutWeak(
3834 Handle<WeakValueHashTable> table, Handle<Object> key,
3835 Handle<HeapObject> value);
3837 static Handle<FixedArray> GetWeakValues(Handle<WeakValueHashTable> table);
3841 // JSFunctionResultCache caches results of some JSFunction invocation.
3842 // It is a fixed array with fixed structure:
3843 // [0]: factory function
3844 // [1]: finger index
3845 // [2]: current cache size
3846 // [3]: dummy field.
3847 // The rest of array are key/value pairs.
3848 class JSFunctionResultCache : public FixedArray {
3850 static const int kFactoryIndex = 0;
3851 static const int kFingerIndex = kFactoryIndex + 1;
3852 static const int kCacheSizeIndex = kFingerIndex + 1;
3853 static const int kDummyIndex = kCacheSizeIndex + 1;
3854 static const int kEntriesIndex = kDummyIndex + 1;
3856 static const int kEntrySize = 2; // key + value
3858 static const int kFactoryOffset = kHeaderSize;
3859 static const int kFingerOffset = kFactoryOffset + kPointerSize;
3860 static const int kCacheSizeOffset = kFingerOffset + kPointerSize;
3862 inline void MakeZeroSize();
3863 inline void Clear();
3866 inline void set_size(int size);
3867 inline int finger_index();
3868 inline void set_finger_index(int finger_index);
3870 DECLARE_CAST(JSFunctionResultCache)
3872 DECLARE_VERIFIER(JSFunctionResultCache)
3876 // ScopeInfo represents information about different scopes of a source
3877 // program and the allocation of the scope's variables. Scope information
3878 // is stored in a compressed form in ScopeInfo objects and is used
3879 // at runtime (stack dumps, deoptimization, etc.).
3881 // This object provides quick access to scope info details for runtime
3883 class ScopeInfo : public FixedArray {
3885 DECLARE_CAST(ScopeInfo)
3887 // Return the type of this scope.
3888 ScopeType scope_type();
3890 // Does this scope call eval?
3893 // Return the language mode of this scope.
3894 LanguageMode language_mode();
3896 // Does this scope make a sloppy eval call?
3897 bool CallsSloppyEval() { return CallsEval() && is_sloppy(language_mode()); }
3899 // Return the total number of locals allocated on the stack and in the
3900 // context. This includes the parameters that are allocated in the context.
3903 // Return the number of stack slots for code. This number consists of two
3905 // 1. One stack slot per stack allocated local.
3906 // 2. One stack slot for the function name if it is stack allocated.
3907 int StackSlotCount();
3909 // Return the number of context slots for code if a context is allocated. This
3910 // number consists of three parts:
3911 // 1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
3912 // 2. One context slot per context allocated local.
3913 // 3. One context slot for the function name if it is context allocated.
3914 // Parameters allocated in the context count as context allocated locals. If
3915 // no contexts are allocated for this scope ContextLength returns 0.
3916 int ContextLength();
3918 // Does this scope declare a "this" binding?
3921 // Does this scope declare a "this" binding, and the "this" binding is stack-
3922 // or context-allocated?
3923 bool HasAllocatedReceiver();
3925 // Is this scope the scope of a named function expression?
3926 bool HasFunctionName();
3928 // Return if this has context allocated locals.
3929 bool HasHeapAllocatedLocals();
3931 // Return if contexts are allocated for this scope.
3934 // Return if this is a function scope with "use asm".
3935 bool IsAsmModule() { return AsmModuleField::decode(Flags()); }
3937 // Return if this is a nested function within an asm module scope.
3938 bool IsAsmFunction() { return AsmFunctionField::decode(Flags()); }
3940 bool IsSimpleParameterList() {
3941 return IsSimpleParameterListField::decode(Flags());
3944 // Return the function_name if present.
3945 String* FunctionName();
3947 // Return the name of the given parameter.
3948 String* ParameterName(int var);
3950 // Return the name of the given local.
3951 String* LocalName(int var);
3953 // Return the name of the given stack local.
3954 String* StackLocalName(int var);
3956 // Return the name of the given stack local.
3957 int StackLocalIndex(int var);
3959 // Return the name of the given context local.
3960 String* ContextLocalName(int var);
3962 // Return the mode of the given context local.
3963 VariableMode ContextLocalMode(int var);
3965 // Return the initialization flag of the given context local.
3966 InitializationFlag ContextLocalInitFlag(int var);
3968 // Return the initialization flag of the given context local.
3969 MaybeAssignedFlag ContextLocalMaybeAssignedFlag(int var);
3971 // Return true if this local was introduced by the compiler, and should not be
3972 // exposed to the user in a debugger.
3973 bool LocalIsSynthetic(int var);
3975 String* StrongModeFreeVariableName(int var);
3976 int StrongModeFreeVariableStartPosition(int var);
3977 int StrongModeFreeVariableEndPosition(int var);
3979 // Lookup support for serialized scope info. Returns the
3980 // the stack slot index for a given slot name if the slot is
3981 // present; otherwise returns a value < 0. The name must be an internalized
3983 int StackSlotIndex(String* name);
3985 // Lookup support for serialized scope info. Returns the
3986 // context slot index for a given slot name if the slot is present; otherwise
3987 // returns a value < 0. The name must be an internalized string.
3988 // If the slot is present and mode != NULL, sets *mode to the corresponding
3989 // mode for that variable.
3990 static int ContextSlotIndex(Handle<ScopeInfo> scope_info, Handle<String> name,
3991 VariableMode* mode, VariableLocation* location,
3992 InitializationFlag* init_flag,
3993 MaybeAssignedFlag* maybe_assigned_flag);
3995 // Lookup support for serialized scope info. Returns the
3996 // parameter index for a given parameter name if the parameter is present;
3997 // otherwise returns a value < 0. The name must be an internalized string.
3998 int ParameterIndex(String* name);
4000 // Lookup support for serialized scope info. Returns the function context
4001 // slot index if the function name is present and context-allocated (named
4002 // function expressions, only), otherwise returns a value < 0. The name
4003 // must be an internalized string.
4004 int FunctionContextSlotIndex(String* name, VariableMode* mode);
4006 // Lookup support for serialized scope info. Returns the receiver context
4007 // slot index if scope has a "this" binding, and the binding is
4008 // context-allocated. Otherwise returns a value < 0.
4009 int ReceiverContextSlotIndex();
4011 FunctionKind function_kind();
4013 // Copies all the context locals into an object used to materialize a scope.
4014 static void CopyContextLocalsToScopeObject(Handle<ScopeInfo> scope_info,
4015 Handle<Context> context,
4016 Handle<JSObject> scope_object);
4019 static Handle<ScopeInfo> Create(Isolate* isolate, Zone* zone, Scope* scope);
4020 static Handle<ScopeInfo> CreateGlobalThisBinding(Isolate* isolate);
4022 // Serializes empty scope info.
4023 static ScopeInfo* Empty(Isolate* isolate);
4029 // The layout of the static part of a ScopeInfo is as follows. Each entry is
4030 // numeric and occupies one array slot.
4031 // 1. A set of properties of the scope
4032 // 2. The number of parameters. This only applies to function scopes. For
4033 // non-function scopes this is 0.
4034 // 3. The number of non-parameter variables allocated on the stack.
4035 // 4. The number of non-parameter and parameter variables allocated in the
4037 #define FOR_EACH_NUMERIC_FIELD(V) \
4040 V(StackLocalCount) \
4041 V(ContextLocalCount) \
4042 V(ContextGlobalCount) \
4043 V(StrongModeFreeVariableCount)
4045 #define FIELD_ACCESSORS(name) \
4046 void Set##name(int value) { \
4047 set(k##name, Smi::FromInt(value)); \
4050 if (length() > 0) { \
4051 return Smi::cast(get(k##name))->value(); \
4056 FOR_EACH_NUMERIC_FIELD(FIELD_ACCESSORS)
4057 #undef FIELD_ACCESSORS
4061 #define DECL_INDEX(name) k##name,
4062 FOR_EACH_NUMERIC_FIELD(DECL_INDEX)
4064 #undef FOR_EACH_NUMERIC_FIELD
4068 // The layout of the variable part of a ScopeInfo is as follows:
4069 // 1. ParameterEntries:
4070 // This part stores the names of the parameters for function scopes. One
4071 // slot is used per parameter, so in total this part occupies
4072 // ParameterCount() slots in the array. For other scopes than function
4073 // scopes ParameterCount() is 0.
4074 // 2. StackLocalFirstSlot:
4075 // Index of a first stack slot for stack local. Stack locals belonging to
4076 // this scope are located on a stack at slots starting from this index.
4077 // 3. StackLocalEntries:
4078 // Contains the names of local variables that are allocated on the stack,
4079 // in increasing order of the stack slot index. First local variable has
4080 // a stack slot index defined in StackLocalFirstSlot (point 2 above).
4081 // One slot is used per stack local, so in total this part occupies
4082 // StackLocalCount() slots in the array.
4083 // 4. ContextLocalNameEntries:
4084 // Contains the names of local variables and parameters that are allocated
4085 // in the context. They are stored in increasing order of the context slot
4086 // index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
4087 // context local, so in total this part occupies ContextLocalCount() slots
4089 // 5. ContextLocalInfoEntries:
4090 // Contains the variable modes and initialization flags corresponding to
4091 // the context locals in ContextLocalNameEntries. One slot is used per
4092 // context local, so in total this part occupies ContextLocalCount()
4093 // slots in the array.
4094 // 6. StrongModeFreeVariableNameEntries:
4095 // Stores the names of strong mode free variables.
4096 // 7. StrongModeFreeVariablePositionEntries:
4097 // Stores the locations (start and end position) of strong mode free
4099 // 8. RecieverEntryIndex:
4100 // If the scope binds a "this" value, one slot is reserved to hold the
4101 // context or stack slot index for the variable.
4102 // 9. FunctionNameEntryIndex:
4103 // If the scope belongs to a named function expression this part contains
4104 // information about the function variable. It always occupies two array
4105 // slots: a. The name of the function variable.
4106 // b. The context or stack slot index for the variable.
4107 int ParameterEntriesIndex();
4108 int StackLocalFirstSlotIndex();
4109 int StackLocalEntriesIndex();
4110 int ContextLocalNameEntriesIndex();
4111 int ContextGlobalNameEntriesIndex();
4112 int ContextLocalInfoEntriesIndex();
4113 int ContextGlobalInfoEntriesIndex();
4114 int StrongModeFreeVariableNameEntriesIndex();
4115 int StrongModeFreeVariablePositionEntriesIndex();
4116 int ReceiverEntryIndex();
4117 int FunctionNameEntryIndex();
4119 int Lookup(Handle<String> name, int start, int end, VariableMode* mode,
4120 VariableLocation* location, InitializationFlag* init_flag,
4121 MaybeAssignedFlag* maybe_assigned_flag);
4123 // Used for the function name variable for named function expressions, and for
4125 enum VariableAllocationInfo { NONE, STACK, CONTEXT, UNUSED };
4127 // Properties of scopes.
4128 class ScopeTypeField : public BitField<ScopeType, 0, 4> {};
4129 class CallsEvalField : public BitField<bool, ScopeTypeField::kNext, 1> {};
4130 STATIC_ASSERT(LANGUAGE_END == 3);
4131 class LanguageModeField
4132 : public BitField<LanguageMode, CallsEvalField::kNext, 2> {};
4133 class ReceiverVariableField
4134 : public BitField<VariableAllocationInfo, LanguageModeField::kNext, 2> {};
4135 class FunctionVariableField
4136 : public BitField<VariableAllocationInfo, ReceiverVariableField::kNext,
4138 class FunctionVariableMode
4139 : public BitField<VariableMode, FunctionVariableField::kNext, 3> {};
4140 class AsmModuleField : public BitField<bool, FunctionVariableMode::kNext, 1> {
4142 class AsmFunctionField : public BitField<bool, AsmModuleField::kNext, 1> {};
4143 class IsSimpleParameterListField
4144 : public BitField<bool, AsmFunctionField::kNext, 1> {};
4145 class FunctionKindField
4146 : public BitField<FunctionKind, IsSimpleParameterListField::kNext, 8> {};
4148 // BitFields representing the encoded information for context locals in the
4149 // ContextLocalInfoEntries part.
4150 class ContextLocalMode: public BitField<VariableMode, 0, 3> {};
4151 class ContextLocalInitFlag: public BitField<InitializationFlag, 3, 1> {};
4152 class ContextLocalMaybeAssignedFlag
4153 : public BitField<MaybeAssignedFlag, 4, 1> {};
4157 // The cache for maps used by normalized (dictionary mode) objects.
4158 // Such maps do not have property descriptors, so a typical program
4159 // needs very limited number of distinct normalized maps.
4160 class NormalizedMapCache: public FixedArray {
4162 static Handle<NormalizedMapCache> New(Isolate* isolate);
4164 MUST_USE_RESULT MaybeHandle<Map> Get(Handle<Map> fast_map,
4165 PropertyNormalizationMode mode);
4166 void Set(Handle<Map> fast_map, Handle<Map> normalized_map);
4170 DECLARE_CAST(NormalizedMapCache)
4172 static inline bool IsNormalizedMapCache(const Object* obj);
4174 DECLARE_VERIFIER(NormalizedMapCache)
4176 static const int kEntries = 64;
4178 static inline int GetIndex(Handle<Map> map);
4180 // The following declarations hide base class methods.
4181 Object* get(int index);
4182 void set(int index, Object* value);
4186 // ByteArray represents fixed sized byte arrays. Used for the relocation info
4187 // that is attached to code objects.
4188 class ByteArray: public FixedArrayBase {
4190 inline int Size() { return RoundUp(length() + kHeaderSize, kPointerSize); }
4192 // Setter and getter.
4193 inline byte get(int index);
4194 inline void set(int index, byte value);
4196 // Treat contents as an int array.
4197 inline int get_int(int index);
4199 static int SizeFor(int length) {
4200 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4202 // We use byte arrays for free blocks in the heap. Given a desired size in
4203 // bytes that is a multiple of the word size and big enough to hold a byte
4204 // array, this function returns the number of elements a byte array should
4206 static int LengthFor(int size_in_bytes) {
4207 DCHECK(IsAligned(size_in_bytes, kPointerSize));
4208 DCHECK(size_in_bytes >= kHeaderSize);
4209 return size_in_bytes - kHeaderSize;
4212 // Returns data start address.
4213 inline Address GetDataStartAddress();
4215 // Returns a pointer to the ByteArray object for a given data start address.
4216 static inline ByteArray* FromDataStartAddress(Address address);
4218 DECLARE_CAST(ByteArray)
4220 // Dispatched behavior.
4221 inline int ByteArraySize() {
4222 return SizeFor(this->length());
4224 DECLARE_PRINTER(ByteArray)
4225 DECLARE_VERIFIER(ByteArray)
4227 // Layout description.
4228 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4230 // Maximal memory consumption for a single ByteArray.
4231 static const int kMaxSize = 512 * MB;
4232 // Maximal length of a single ByteArray.
4233 static const int kMaxLength = kMaxSize - kHeaderSize;
4236 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4240 // BytecodeArray represents a sequence of interpreter bytecodes.
4241 class BytecodeArray : public FixedArrayBase {
4243 static int SizeFor(int length) {
4244 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4247 // Setter and getter
4248 inline byte get(int index);
4249 inline void set(int index, byte value);
4251 // Returns data start address.
4252 inline Address GetFirstBytecodeAddress();
4254 // Accessors for frame size and the number of locals
4255 inline int frame_size() const;
4256 inline void set_frame_size(int value);
4258 DECLARE_CAST(BytecodeArray)
4260 // Dispatched behavior.
4261 inline int BytecodeArraySize() { return SizeFor(this->length()); }
4263 DECLARE_PRINTER(BytecodeArray)
4264 DECLARE_VERIFIER(BytecodeArray)
4266 void Disassemble(std::ostream& os);
4268 // Layout description.
4269 static const int kFrameSizeOffset = FixedArrayBase::kHeaderSize;
4270 static const int kHeaderSize = kFrameSizeOffset + kIntSize;
4272 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4274 // Maximal memory consumption for a single BytecodeArray.
4275 static const int kMaxSize = 512 * MB;
4276 // Maximal length of a single BytecodeArray.
4277 static const int kMaxLength = kMaxSize - kHeaderSize;
4280 DISALLOW_IMPLICIT_CONSTRUCTORS(BytecodeArray);
4284 // FreeSpace are fixed-size free memory blocks used by the heap and GC.
4285 // They look like heap objects (are heap object tagged and have a map) so that
4286 // the heap remains iterable. They have a size and a next pointer.
4287 // The next pointer is the raw address of the next FreeSpace object (or NULL)
4288 // in the free list.
4289 class FreeSpace: public HeapObject {
4291 // [size]: size of the free space including the header.
4292 inline int size() const;
4293 inline void set_size(int value);
4295 inline int nobarrier_size() const;
4296 inline void nobarrier_set_size(int value);
4298 inline int Size() { return size(); }
4300 // Accessors for the next field.
4301 inline FreeSpace* next();
4302 inline FreeSpace** next_address();
4303 inline void set_next(FreeSpace* next);
4305 inline static FreeSpace* cast(HeapObject* obj);
4307 // Dispatched behavior.
4308 DECLARE_PRINTER(FreeSpace)
4309 DECLARE_VERIFIER(FreeSpace)
4311 // Layout description.
4312 // Size is smi tagged when it is stored.
4313 static const int kSizeOffset = HeapObject::kHeaderSize;
4314 static const int kNextOffset = POINTER_SIZE_ALIGN(kSizeOffset + kPointerSize);
4317 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
4321 // V has parameters (Type, type, TYPE, C type, element_size)
4322 #define TYPED_ARRAYS(V) \
4323 V(Uint8, uint8, UINT8, uint8_t, 1) \
4324 V(Int8, int8, INT8, int8_t, 1) \
4325 V(Uint16, uint16, UINT16, uint16_t, 2) \
4326 V(Int16, int16, INT16, int16_t, 2) \
4327 V(Uint32, uint32, UINT32, uint32_t, 4) \
4328 V(Int32, int32, INT32, int32_t, 4) \
4329 V(Float32, float32, FLOAT32, float, 4) \
4330 V(Float64, float64, FLOAT64, double, 8) \
4331 V(Uint8Clamped, uint8_clamped, UINT8_CLAMPED, uint8_t, 1)
4335 // An ExternalArray represents a fixed-size array of primitive values
4336 // which live outside the JavaScript heap. Its subclasses are used to
4337 // implement the CanvasArray types being defined in the WebGL
4338 // specification. As of this writing the first public draft is not yet
4339 // available, but Khronos members can access the draft at:
4340 // https://cvs.khronos.org/svn/repos/3dweb/trunk/doc/spec/WebGL-spec.html
4342 // The semantics of these arrays differ from CanvasPixelArray.
4343 // Out-of-range values passed to the setter are converted via a C
4344 // cast, not clamping. Out-of-range indices cause exceptions to be
4345 // raised rather than being silently ignored.
4346 class ExternalArray: public FixedArrayBase {
4348 inline bool is_the_hole(int index) { return false; }
4350 // [external_pointer]: The pointer to the external memory area backing this
4352 DECL_ACCESSORS(external_pointer, void) // Pointer to the data store.
4354 DECLARE_CAST(ExternalArray)
4356 // Maximal acceptable length for an external array.
4357 static const int kMaxLength = 0x3fffffff;
4359 // ExternalArray headers are not quadword aligned.
4360 static const int kExternalPointerOffset =
4361 POINTER_SIZE_ALIGN(FixedArrayBase::kLengthOffset + kPointerSize);
4362 static const int kSize = kExternalPointerOffset + kPointerSize;
4365 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalArray);
4369 // A ExternalUint8ClampedArray represents a fixed-size byte array with special
4370 // semantics used for implementing the CanvasPixelArray object. Please see the
4371 // specification at:
4373 // http://www.whatwg.org/specs/web-apps/current-work/
4374 // multipage/the-canvas-element.html#canvaspixelarray
4375 // In particular, write access clamps the value written to 0 or 255 if the
4376 // value written is outside this range.
4377 class ExternalUint8ClampedArray: public ExternalArray {
4379 inline uint8_t* external_uint8_clamped_pointer();
4381 // Setter and getter.
4382 inline uint8_t get_scalar(int index);
4383 static inline Handle<Object> get(Handle<ExternalUint8ClampedArray> array,
4385 inline void set(int index, uint8_t value);
4387 // This accessor applies the correct conversion from Smi, HeapNumber
4388 // and undefined and clamps the converted value between 0 and 255.
4389 void SetValue(uint32_t index, Object* value);
4391 DECLARE_CAST(ExternalUint8ClampedArray)
4393 // Dispatched behavior.
4394 DECLARE_PRINTER(ExternalUint8ClampedArray)
4395 DECLARE_VERIFIER(ExternalUint8ClampedArray)
4398 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint8ClampedArray);
4402 class ExternalInt8Array: public ExternalArray {
4404 // Setter and getter.
4405 inline int8_t get_scalar(int index);
4406 static inline Handle<Object> get(Handle<ExternalInt8Array> array, int index);
4407 inline void set(int index, int8_t value);
4409 // This accessor applies the correct conversion from Smi, HeapNumber
4411 void SetValue(uint32_t index, Object* value);
4413 DECLARE_CAST(ExternalInt8Array)
4415 // Dispatched behavior.
4416 DECLARE_PRINTER(ExternalInt8Array)
4417 DECLARE_VERIFIER(ExternalInt8Array)
4420 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt8Array);
4424 class ExternalUint8Array: public ExternalArray {
4426 // Setter and getter.
4427 inline uint8_t get_scalar(int index);
4428 static inline Handle<Object> get(Handle<ExternalUint8Array> array, int index);
4429 inline void set(int index, uint8_t value);
4431 // This accessor applies the correct conversion from Smi, HeapNumber
4433 void SetValue(uint32_t index, Object* value);
4435 DECLARE_CAST(ExternalUint8Array)
4437 // Dispatched behavior.
4438 DECLARE_PRINTER(ExternalUint8Array)
4439 DECLARE_VERIFIER(ExternalUint8Array)
4442 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint8Array);
4446 class ExternalInt16Array: public ExternalArray {
4448 // Setter and getter.
4449 inline int16_t get_scalar(int index);
4450 static inline Handle<Object> get(Handle<ExternalInt16Array> array, int index);
4451 inline void set(int index, int16_t value);
4453 // This accessor applies the correct conversion from Smi, HeapNumber
4455 void SetValue(uint32_t index, Object* value);
4457 DECLARE_CAST(ExternalInt16Array)
4459 // Dispatched behavior.
4460 DECLARE_PRINTER(ExternalInt16Array)
4461 DECLARE_VERIFIER(ExternalInt16Array)
4464 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt16Array);
4468 class ExternalUint16Array: public ExternalArray {
4470 // Setter and getter.
4471 inline uint16_t get_scalar(int index);
4472 static inline Handle<Object> get(Handle<ExternalUint16Array> array,
4474 inline void set(int index, uint16_t value);
4476 // This accessor applies the correct conversion from Smi, HeapNumber
4478 void SetValue(uint32_t index, Object* value);
4480 DECLARE_CAST(ExternalUint16Array)
4482 // Dispatched behavior.
4483 DECLARE_PRINTER(ExternalUint16Array)
4484 DECLARE_VERIFIER(ExternalUint16Array)
4487 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint16Array);
4491 class ExternalInt32Array: public ExternalArray {
4493 // Setter and getter.
4494 inline int32_t get_scalar(int index);
4495 static inline Handle<Object> get(Handle<ExternalInt32Array> array, int index);
4496 inline void set(int index, int32_t value);
4498 // This accessor applies the correct conversion from Smi, HeapNumber
4500 void SetValue(uint32_t index, Object* value);
4502 DECLARE_CAST(ExternalInt32Array)
4504 // Dispatched behavior.
4505 DECLARE_PRINTER(ExternalInt32Array)
4506 DECLARE_VERIFIER(ExternalInt32Array)
4509 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt32Array);
4513 class ExternalUint32Array: public ExternalArray {
4515 // Setter and getter.
4516 inline uint32_t get_scalar(int index);
4517 static inline Handle<Object> get(Handle<ExternalUint32Array> array,
4519 inline void set(int index, uint32_t value);
4521 // This accessor applies the correct conversion from Smi, HeapNumber
4523 void SetValue(uint32_t index, Object* value);
4525 DECLARE_CAST(ExternalUint32Array)
4527 // Dispatched behavior.
4528 DECLARE_PRINTER(ExternalUint32Array)
4529 DECLARE_VERIFIER(ExternalUint32Array)
4532 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint32Array);
4536 class ExternalFloat32Array: public ExternalArray {
4538 // Setter and getter.
4539 inline float get_scalar(int index);
4540 static inline Handle<Object> get(Handle<ExternalFloat32Array> array,
4542 inline void set(int index, float value);
4544 // This accessor applies the correct conversion from Smi, HeapNumber
4546 void SetValue(uint32_t index, Object* value);
4548 DECLARE_CAST(ExternalFloat32Array)
4550 // Dispatched behavior.
4551 DECLARE_PRINTER(ExternalFloat32Array)
4552 DECLARE_VERIFIER(ExternalFloat32Array)
4555 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalFloat32Array);
4559 class ExternalFloat64Array: public ExternalArray {
4561 // Setter and getter.
4562 inline double get_scalar(int index);
4563 static inline Handle<Object> get(Handle<ExternalFloat64Array> array,
4565 inline void set(int index, double value);
4567 // This accessor applies the correct conversion from Smi, HeapNumber
4569 void SetValue(uint32_t index, Object* value);
4571 DECLARE_CAST(ExternalFloat64Array)
4573 // Dispatched behavior.
4574 DECLARE_PRINTER(ExternalFloat64Array)
4575 DECLARE_VERIFIER(ExternalFloat64Array)
4578 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalFloat64Array);
4582 class FixedTypedArrayBase: public FixedArrayBase {
4584 // [base_pointer]: For now, points to the FixedTypedArrayBase itself.
4585 DECL_ACCESSORS(base_pointer, Object)
4587 // [external_pointer]: For now, contains the offset between base_pointer and
4588 // the start of the data.
4589 DECL_ACCESSORS(external_pointer, void)
4591 // Dispatched behavior.
4592 inline void FixedTypedArrayBaseIterateBody(ObjectVisitor* v);
4594 template <typename StaticVisitor>
4595 inline void FixedTypedArrayBaseIterateBody();
4597 DECLARE_CAST(FixedTypedArrayBase)
4599 static const int kBasePointerOffset = FixedArrayBase::kHeaderSize;
4600 static const int kExternalPointerOffset = kBasePointerOffset + kPointerSize;
4601 static const int kHeaderSize =
4602 DOUBLE_POINTER_ALIGN(kExternalPointerOffset + kPointerSize);
4604 static const int kDataOffset = kHeaderSize;
4608 static inline int TypedArraySize(InstanceType type, int length);
4609 inline int TypedArraySize(InstanceType type);
4611 // Use with care: returns raw pointer into heap.
4612 inline void* DataPtr();
4614 inline int DataSize();
4617 static inline int ElementSize(InstanceType type);
4619 inline int DataSize(InstanceType type);
4621 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
4625 template <class Traits>
4626 class FixedTypedArray: public FixedTypedArrayBase {
4628 typedef typename Traits::ElementType ElementType;
4629 static const InstanceType kInstanceType = Traits::kInstanceType;
4631 DECLARE_CAST(FixedTypedArray<Traits>)
4633 inline ElementType get_scalar(int index);
4634 static inline Handle<Object> get(Handle<FixedTypedArray> array, int index);
4635 inline void set(int index, ElementType value);
4637 static inline ElementType from_int(int value);
4638 static inline ElementType from_double(double value);
4640 // This accessor applies the correct conversion from Smi, HeapNumber
4642 void SetValue(uint32_t index, Object* value);
4644 DECLARE_PRINTER(FixedTypedArray)
4645 DECLARE_VERIFIER(FixedTypedArray)
4648 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
4651 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size) \
4652 class Type##ArrayTraits { \
4653 public: /* NOLINT */ \
4654 typedef elementType ElementType; \
4655 static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE; \
4656 static const char* Designator() { return #type " array"; } \
4657 static inline Handle<Object> ToHandle(Isolate* isolate, \
4658 elementType scalar); \
4659 static inline elementType defaultValue(); \
4662 typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
4664 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
4666 #undef FIXED_TYPED_ARRAY_TRAITS
4669 // DeoptimizationInputData is a fixed array used to hold the deoptimization
4670 // data for code generated by the Hydrogen/Lithium compiler. It also
4671 // contains information about functions that were inlined. If N different
4672 // functions were inlined then first N elements of the literal array will
4673 // contain these functions.
4676 class DeoptimizationInputData: public FixedArray {
4678 // Layout description. Indices in the array.
4679 static const int kTranslationByteArrayIndex = 0;
4680 static const int kInlinedFunctionCountIndex = 1;
4681 static const int kLiteralArrayIndex = 2;
4682 static const int kOsrAstIdIndex = 3;
4683 static const int kOsrPcOffsetIndex = 4;
4684 static const int kOptimizationIdIndex = 5;
4685 static const int kSharedFunctionInfoIndex = 6;
4686 static const int kWeakCellCacheIndex = 7;
4687 static const int kFirstDeoptEntryIndex = 8;
4689 // Offsets of deopt entry elements relative to the start of the entry.
4690 static const int kAstIdRawOffset = 0;
4691 static const int kTranslationIndexOffset = 1;
4692 static const int kArgumentsStackHeightOffset = 2;
4693 static const int kPcOffset = 3;
4694 static const int kDeoptEntrySize = 4;
4696 // Simple element accessors.
4697 #define DEFINE_ELEMENT_ACCESSORS(name, type) \
4699 return type::cast(get(k##name##Index)); \
4701 void Set##name(type* value) { \
4702 set(k##name##Index, value); \
4705 DEFINE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
4706 DEFINE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
4707 DEFINE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
4708 DEFINE_ELEMENT_ACCESSORS(OsrAstId, Smi)
4709 DEFINE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
4710 DEFINE_ELEMENT_ACCESSORS(OptimizationId, Smi)
4711 DEFINE_ELEMENT_ACCESSORS(SharedFunctionInfo, Object)
4712 DEFINE_ELEMENT_ACCESSORS(WeakCellCache, Object)
4714 #undef DEFINE_ELEMENT_ACCESSORS
4716 // Accessors for elements of the ith deoptimization entry.
4717 #define DEFINE_ENTRY_ACCESSORS(name, type) \
4718 type* name(int i) { \
4719 return type::cast(get(IndexForEntry(i) + k##name##Offset)); \
4721 void Set##name(int i, type* value) { \
4722 set(IndexForEntry(i) + k##name##Offset, value); \
4725 DEFINE_ENTRY_ACCESSORS(AstIdRaw, Smi)
4726 DEFINE_ENTRY_ACCESSORS(TranslationIndex, Smi)
4727 DEFINE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
4728 DEFINE_ENTRY_ACCESSORS(Pc, Smi)
4730 #undef DEFINE_DEOPT_ENTRY_ACCESSORS
4732 BailoutId AstId(int i) {
4733 return BailoutId(AstIdRaw(i)->value());
4736 void SetAstId(int i, BailoutId value) {
4737 SetAstIdRaw(i, Smi::FromInt(value.ToInt()));
4741 return (length() - kFirstDeoptEntryIndex) / kDeoptEntrySize;
4744 // Allocates a DeoptimizationInputData.
4745 static Handle<DeoptimizationInputData> New(Isolate* isolate,
4746 int deopt_entry_count,
4747 PretenureFlag pretenure);
4749 DECLARE_CAST(DeoptimizationInputData)
4751 #ifdef ENABLE_DISASSEMBLER
4752 void DeoptimizationInputDataPrint(std::ostream& os); // NOLINT
4756 static int IndexForEntry(int i) {
4757 return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
4761 static int LengthFor(int entry_count) { return IndexForEntry(entry_count); }
4765 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
4766 // data for code generated by the full compiler.
4767 // The format of the these objects is
4768 // [i * 2]: Ast ID for ith deoptimization.
4769 // [i * 2 + 1]: PC and state of ith deoptimization
4770 class DeoptimizationOutputData: public FixedArray {
4772 int DeoptPoints() { return length() / 2; }
4774 BailoutId AstId(int index) {
4775 return BailoutId(Smi::cast(get(index * 2))->value());
4778 void SetAstId(int index, BailoutId id) {
4779 set(index * 2, Smi::FromInt(id.ToInt()));
4782 Smi* PcAndState(int index) { return Smi::cast(get(1 + index * 2)); }
4783 void SetPcAndState(int index, Smi* offset) { set(1 + index * 2, offset); }
4785 static int LengthOfFixedArray(int deopt_points) {
4786 return deopt_points * 2;
4789 // Allocates a DeoptimizationOutputData.
4790 static Handle<DeoptimizationOutputData> New(Isolate* isolate,
4791 int number_of_deopt_points,
4792 PretenureFlag pretenure);
4794 DECLARE_CAST(DeoptimizationOutputData)
4796 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4797 void DeoptimizationOutputDataPrint(std::ostream& os); // NOLINT
4802 // HandlerTable is a fixed array containing entries for exception handlers in
4803 // the code object it is associated with. The tables comes in two flavors:
4804 // 1) Based on ranges: Used for unoptimized code. Contains one entry per
4805 // exception handler and a range representing the try-block covered by that
4806 // handler. Layout looks as follows:
4807 // [ range-start , range-end , handler-offset , stack-depth ]
4808 // 2) Based on return addresses: Used for turbofanned code. Contains one entry
4809 // per call-site that could throw an exception. Layout looks as follows:
4810 // [ return-address-offset , handler-offset ]
4811 class HandlerTable : public FixedArray {
4813 // Conservative prediction whether a given handler will locally catch an
4814 // exception or cause a re-throw to outside the code boundary. Since this is
4815 // undecidable it is merely an approximation (e.g. useful for debugger).
4816 enum CatchPrediction { UNCAUGHT, CAUGHT };
4818 // Accessors for handler table based on ranges.
4819 void SetRangeStart(int index, int value) {
4820 set(index * kRangeEntrySize + kRangeStartIndex, Smi::FromInt(value));
4822 void SetRangeEnd(int index, int value) {
4823 set(index * kRangeEntrySize + kRangeEndIndex, Smi::FromInt(value));
4825 void SetRangeHandler(int index, int offset, CatchPrediction prediction) {
4826 int value = HandlerOffsetField::encode(offset) |
4827 HandlerPredictionField::encode(prediction);
4828 set(index * kRangeEntrySize + kRangeHandlerIndex, Smi::FromInt(value));
4830 void SetRangeDepth(int index, int value) {
4831 set(index * kRangeEntrySize + kRangeDepthIndex, Smi::FromInt(value));
4834 // Accessors for handler table based on return addresses.
4835 void SetReturnOffset(int index, int value) {
4836 set(index * kReturnEntrySize + kReturnOffsetIndex, Smi::FromInt(value));
4838 void SetReturnHandler(int index, int offset, CatchPrediction prediction) {
4839 int value = HandlerOffsetField::encode(offset) |
4840 HandlerPredictionField::encode(prediction);
4841 set(index * kReturnEntrySize + kReturnHandlerIndex, Smi::FromInt(value));
4844 // Lookup handler in a table based on ranges.
4845 int LookupRange(int pc_offset, int* stack_depth, CatchPrediction* prediction);
4847 // Lookup handler in a table based on return addresses.
4848 int LookupReturn(int pc_offset, CatchPrediction* prediction);
4850 // Returns the required length of the underlying fixed array.
4851 static int LengthForRange(int entries) { return entries * kRangeEntrySize; }
4852 static int LengthForReturn(int entries) { return entries * kReturnEntrySize; }
4854 DECLARE_CAST(HandlerTable)
4856 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4857 void HandlerTableRangePrint(std::ostream& os); // NOLINT
4858 void HandlerTableReturnPrint(std::ostream& os); // NOLINT
4862 // Layout description for handler table based on ranges.
4863 static const int kRangeStartIndex = 0;
4864 static const int kRangeEndIndex = 1;
4865 static const int kRangeHandlerIndex = 2;
4866 static const int kRangeDepthIndex = 3;
4867 static const int kRangeEntrySize = 4;
4869 // Layout description for handler table based on return addresses.
4870 static const int kReturnOffsetIndex = 0;
4871 static const int kReturnHandlerIndex = 1;
4872 static const int kReturnEntrySize = 2;
4874 // Encoding of the {handler} field.
4875 class HandlerPredictionField : public BitField<CatchPrediction, 0, 1> {};
4876 class HandlerOffsetField : public BitField<int, 1, 30> {};
4880 // Code describes objects with on-the-fly generated machine code.
4881 class Code: public HeapObject {
4883 // Opaque data type for encapsulating code flags like kind, inline
4884 // cache state, and arguments count.
4885 typedef uint32_t Flags;
4887 #define NON_IC_KIND_LIST(V) \
4889 V(OPTIMIZED_FUNCTION) \
4895 #define IC_KIND_LIST(V) \
4906 #define CODE_KIND_LIST(V) \
4907 NON_IC_KIND_LIST(V) \
4911 #define DEFINE_CODE_KIND_ENUM(name) name,
4912 CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
4913 #undef DEFINE_CODE_KIND_ENUM
4917 // No more than 16 kinds. The value is currently encoded in four bits in
4919 STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
4921 static const char* Kind2String(Kind kind);
4929 static const int kPrologueOffsetNotSet = -1;
4931 #ifdef ENABLE_DISASSEMBLER
4933 static const char* ICState2String(InlineCacheState state);
4934 static const char* StubType2String(StubType type);
4935 static void PrintExtraICState(std::ostream& os, // NOLINT
4936 Kind kind, ExtraICState extra);
4937 void Disassemble(const char* name, std::ostream& os); // NOLINT
4938 #endif // ENABLE_DISASSEMBLER
4940 // [instruction_size]: Size of the native instructions
4941 inline int instruction_size() const;
4942 inline void set_instruction_size(int value);
4944 // [relocation_info]: Code relocation information
4945 DECL_ACCESSORS(relocation_info, ByteArray)
4946 void InvalidateRelocation();
4947 void InvalidateEmbeddedObjects();
4949 // [handler_table]: Fixed array containing offsets of exception handlers.
4950 DECL_ACCESSORS(handler_table, FixedArray)
4952 // [deoptimization_data]: Array containing data for deopt.
4953 DECL_ACCESSORS(deoptimization_data, FixedArray)
4955 // [raw_type_feedback_info]: This field stores various things, depending on
4956 // the kind of the code object.
4957 // FUNCTION => type feedback information.
4958 // STUB and ICs => major/minor key as Smi.
4959 DECL_ACCESSORS(raw_type_feedback_info, Object)
4960 inline Object* type_feedback_info();
4961 inline void set_type_feedback_info(
4962 Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
4963 inline uint32_t stub_key();
4964 inline void set_stub_key(uint32_t key);
4966 // [next_code_link]: Link for lists of optimized or deoptimized code.
4967 // Note that storage for this field is overlapped with typefeedback_info.
4968 DECL_ACCESSORS(next_code_link, Object)
4970 // [gc_metadata]: Field used to hold GC related metadata. The contents of this
4971 // field does not have to be traced during garbage collection since
4972 // it is only used by the garbage collector itself.
4973 DECL_ACCESSORS(gc_metadata, Object)
4975 // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
4976 // at the moment when this object was created.
4977 inline void set_ic_age(int count);
4978 inline int ic_age() const;
4980 // [prologue_offset]: Offset of the function prologue, used for aging
4981 // FUNCTIONs and OPTIMIZED_FUNCTIONs.
4982 inline int prologue_offset() const;
4983 inline void set_prologue_offset(int offset);
4985 // [constant_pool offset]: Offset of the constant pool.
4986 // Valid for FLAG_enable_embedded_constant_pool only
4987 inline int constant_pool_offset() const;
4988 inline void set_constant_pool_offset(int offset);
4990 // Unchecked accessors to be used during GC.
4991 inline ByteArray* unchecked_relocation_info();
4993 inline int relocation_size();
4995 // [flags]: Various code flags.
4996 inline Flags flags();
4997 inline void set_flags(Flags flags);
4999 // [flags]: Access to specific code flags.
5001 inline InlineCacheState ic_state(); // Only valid for IC stubs.
5002 inline ExtraICState extra_ic_state(); // Only valid for IC stubs.
5004 inline StubType type(); // Only valid for monomorphic IC stubs.
5006 // Testers for IC stub kinds.
5007 inline bool is_inline_cache_stub();
5008 inline bool is_debug_stub();
5009 inline bool is_handler() { return kind() == HANDLER; }
5010 inline bool is_load_stub() { return kind() == LOAD_IC; }
5011 inline bool is_keyed_load_stub() { return kind() == KEYED_LOAD_IC; }
5012 inline bool is_store_stub() { return kind() == STORE_IC; }
5013 inline bool is_keyed_store_stub() { return kind() == KEYED_STORE_IC; }
5014 inline bool is_call_stub() { return kind() == CALL_IC; }
5015 inline bool is_binary_op_stub() { return kind() == BINARY_OP_IC; }
5016 inline bool is_compare_ic_stub() { return kind() == COMPARE_IC; }
5017 inline bool is_compare_nil_ic_stub() { return kind() == COMPARE_NIL_IC; }
5018 inline bool is_to_boolean_ic_stub() { return kind() == TO_BOOLEAN_IC; }
5019 inline bool is_keyed_stub();
5020 inline bool is_optimized_code() { return kind() == OPTIMIZED_FUNCTION; }
5021 inline bool embeds_maps_weakly() {
5023 return (k == LOAD_IC || k == STORE_IC || k == KEYED_LOAD_IC ||
5024 k == KEYED_STORE_IC || k == COMPARE_NIL_IC) &&
5025 ic_state() == MONOMORPHIC;
5028 inline bool IsCodeStubOrIC();
5030 inline void set_raw_kind_specific_flags1(int value);
5031 inline void set_raw_kind_specific_flags2(int value);
5033 // [is_crankshafted]: For kind STUB or ICs, tells whether or not a code
5034 // object was generated by either the hydrogen or the TurboFan optimizing
5035 // compiler (but it may not be an optimized function).
5036 inline bool is_crankshafted();
5037 inline bool is_hydrogen_stub(); // Crankshafted, but not a function.
5038 inline void set_is_crankshafted(bool value);
5040 // [is_turbofanned]: For kind STUB or OPTIMIZED_FUNCTION, tells whether the
5041 // code object was generated by the TurboFan optimizing compiler.
5042 inline bool is_turbofanned();
5043 inline void set_is_turbofanned(bool value);
5045 // [can_have_weak_objects]: For kind OPTIMIZED_FUNCTION, tells whether the
5046 // embedded objects in code should be treated weakly.
5047 inline bool can_have_weak_objects();
5048 inline void set_can_have_weak_objects(bool value);
5050 // [has_deoptimization_support]: For FUNCTION kind, tells if it has
5051 // deoptimization support.
5052 inline bool has_deoptimization_support();
5053 inline void set_has_deoptimization_support(bool value);
5055 // [has_debug_break_slots]: For FUNCTION kind, tells if it has
5056 // been compiled with debug break slots.
5057 inline bool has_debug_break_slots();
5058 inline void set_has_debug_break_slots(bool value);
5060 // [has_reloc_info_for_serialization]: For FUNCTION kind, tells if its
5061 // reloc info includes runtime and external references to support
5062 // serialization/deserialization.
5063 inline bool has_reloc_info_for_serialization();
5064 inline void set_has_reloc_info_for_serialization(bool value);
5066 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
5067 // how long the function has been marked for OSR and therefore which
5068 // level of loop nesting we are willing to do on-stack replacement
5070 inline void set_allow_osr_at_loop_nesting_level(int level);
5071 inline int allow_osr_at_loop_nesting_level();
5073 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
5074 // the code object was seen on the stack with no IC patching going on.
5075 inline int profiler_ticks();
5076 inline void set_profiler_ticks(int ticks);
5078 // [builtin_index]: For BUILTIN kind, tells which builtin index it has.
5079 // For builtins, tells which builtin index it has.
5080 // Note that builtins can have a code kind other than BUILTIN, which means
5081 // that for arbitrary code objects, this index value may be random garbage.
5082 // To verify in that case, compare the code object to the indexed builtin.
5083 inline int builtin_index();
5084 inline void set_builtin_index(int id);
5086 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
5087 // reserved in the code prologue.
5088 inline unsigned stack_slots();
5089 inline void set_stack_slots(unsigned slots);
5091 // [safepoint_table_start]: For kind OPTIMIZED_FUNCTION, the offset in
5092 // the instruction stream where the safepoint table starts.
5093 inline unsigned safepoint_table_offset();
5094 inline void set_safepoint_table_offset(unsigned offset);
5096 // [back_edge_table_start]: For kind FUNCTION, the offset in the
5097 // instruction stream where the back edge table starts.
5098 inline unsigned back_edge_table_offset();
5099 inline void set_back_edge_table_offset(unsigned offset);
5101 inline bool back_edges_patched_for_osr();
5103 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
5104 inline uint16_t to_boolean_state();
5106 // [has_function_cache]: For kind STUB tells whether there is a function
5107 // cache is passed to the stub.
5108 inline bool has_function_cache();
5109 inline void set_has_function_cache(bool flag);
5112 // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
5113 // the code is going to be deoptimized because of dead embedded maps.
5114 inline bool marked_for_deoptimization();
5115 inline void set_marked_for_deoptimization(bool flag);
5117 // [constant_pool]: The constant pool for this function.
5118 inline Address constant_pool();
5120 // Get the safepoint entry for the given pc.
5121 SafepointEntry GetSafepointEntry(Address pc);
5123 // Find an object in a stub with a specified map
5124 Object* FindNthObject(int n, Map* match_map);
5126 // Find the first allocation site in an IC stub.
5127 AllocationSite* FindFirstAllocationSite();
5129 // Find the first map in an IC stub.
5130 Map* FindFirstMap();
5131 void FindAllMaps(MapHandleList* maps);
5133 // Find the first handler in an IC stub.
5134 Code* FindFirstHandler();
5136 // Find |length| handlers and put them into |code_list|. Returns false if not
5137 // enough handlers can be found.
5138 bool FindHandlers(CodeHandleList* code_list, int length = -1);
5140 // Find the handler for |map|.
5141 MaybeHandle<Code> FindHandlerForMap(Map* map);
5143 // Find the first name in an IC stub.
5144 Name* FindFirstName();
5146 class FindAndReplacePattern;
5147 // For each (map-to-find, object-to-replace) pair in the pattern, this
5148 // function replaces the corresponding placeholder in the code with the
5149 // object-to-replace. The function assumes that pairs in the pattern come in
5150 // the same order as the placeholders in the code.
5151 // If the placeholder is a weak cell, then the value of weak cell is matched
5152 // against the map-to-find.
5153 void FindAndReplace(const FindAndReplacePattern& pattern);
5155 // The entire code object including its header is copied verbatim to the
5156 // snapshot so that it can be written in one, fast, memcpy during
5157 // deserialization. The deserializer will overwrite some pointers, rather
5158 // like a runtime linker, but the random allocation addresses used in the
5159 // mksnapshot process would still be present in the unlinked snapshot data,
5160 // which would make snapshot production non-reproducible. This method wipes
5161 // out the to-be-overwritten header data for reproducible snapshots.
5162 inline void WipeOutHeader();
5164 // Flags operations.
5165 static inline Flags ComputeFlags(
5166 Kind kind, InlineCacheState ic_state = UNINITIALIZED,
5167 ExtraICState extra_ic_state = kNoExtraICState, StubType type = NORMAL,
5168 CacheHolderFlag holder = kCacheOnReceiver);
5170 static inline Flags ComputeMonomorphicFlags(
5171 Kind kind, ExtraICState extra_ic_state = kNoExtraICState,
5172 CacheHolderFlag holder = kCacheOnReceiver, StubType type = NORMAL);
5174 static inline Flags ComputeHandlerFlags(
5175 Kind handler_kind, StubType type = NORMAL,
5176 CacheHolderFlag holder = kCacheOnReceiver);
5178 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
5179 static inline StubType ExtractTypeFromFlags(Flags flags);
5180 static inline CacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
5181 static inline Kind ExtractKindFromFlags(Flags flags);
5182 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
5184 static inline Flags RemoveTypeFromFlags(Flags flags);
5185 static inline Flags RemoveTypeAndHolderFromFlags(Flags flags);
5187 // Convert a target address into a code object.
5188 static inline Code* GetCodeFromTargetAddress(Address address);
5190 // Convert an entry address into an object.
5191 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
5193 // Returns the address of the first instruction.
5194 inline byte* instruction_start();
5196 // Returns the address right after the last instruction.
5197 inline byte* instruction_end();
5199 // Returns the size of the instructions, padding, and relocation information.
5200 inline int body_size();
5202 // Returns the address of the first relocation info (read backwards!).
5203 inline byte* relocation_start();
5205 // Code entry point.
5206 inline byte* entry();
5208 // Returns true if pc is inside this object's instructions.
5209 inline bool contains(byte* pc);
5211 // Relocate the code by delta bytes. Called to signal that this code
5212 // object has been moved by delta bytes.
5213 void Relocate(intptr_t delta);
5215 // Migrate code described by desc.
5216 void CopyFrom(const CodeDesc& desc);
5218 // Returns the object size for a given body (used for allocation).
5219 static int SizeFor(int body_size) {
5220 DCHECK_SIZE_TAG_ALIGNED(body_size);
5221 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
5224 // Calculate the size of the code object to report for log events. This takes
5225 // the layout of the code object into account.
5226 int ExecutableSize() {
5227 // Check that the assumptions about the layout of the code object holds.
5228 DCHECK_EQ(static_cast<int>(instruction_start() - address()),
5230 return instruction_size() + Code::kHeaderSize;
5233 // Locating source position.
5234 int SourcePosition(Address pc);
5235 int SourceStatementPosition(Address pc);
5239 // Dispatched behavior.
5240 int CodeSize() { return SizeFor(body_size()); }
5241 inline void CodeIterateBody(ObjectVisitor* v);
5243 template<typename StaticVisitor>
5244 inline void CodeIterateBody(Heap* heap);
5246 DECLARE_PRINTER(Code)
5247 DECLARE_VERIFIER(Code)
5249 void ClearInlineCaches();
5250 void ClearInlineCaches(Kind kind);
5252 BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
5253 uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
5255 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
5257 kToBeExecutedOnceCodeAge = -3,
5258 kNotExecutedCodeAge = -2,
5259 kExecutedOnceCodeAge = -1,
5261 CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
5263 kFirstCodeAge = kToBeExecutedOnceCodeAge,
5264 kLastCodeAge = kAfterLastCodeAge - 1,
5265 kCodeAgeCount = kAfterLastCodeAge - kFirstCodeAge - 1,
5266 kIsOldCodeAge = kSexagenarianCodeAge,
5267 kPreAgedCodeAge = kIsOldCodeAge - 1
5269 #undef DECLARE_CODE_AGE_ENUM
5271 // Code aging. Indicates how many full GCs this code has survived without
5272 // being entered through the prologue. Used to determine when it is
5273 // relatively safe to flush this code object and replace it with the lazy
5274 // compilation stub.
5275 static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
5276 static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
5277 void MakeYoung(Isolate* isolate);
5278 void MarkToBeExecutedOnce(Isolate* isolate);
5279 void MakeOlder(MarkingParity);
5280 static bool IsYoungSequence(Isolate* isolate, byte* sequence);
5283 static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
5284 return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
5287 void PrintDeoptLocation(FILE* out, Address pc);
5288 bool CanDeoptAt(Address pc);
5291 void VerifyEmbeddedObjectsDependency();
5295 enum VerifyMode { kNoContextSpecificPointers, kNoContextRetainingPointers };
5296 void VerifyEmbeddedObjects(VerifyMode mode = kNoContextRetainingPointers);
5299 inline bool CanContainWeakObjects() {
5300 // is_turbofanned() implies !can_have_weak_objects().
5301 DCHECK(!is_optimized_code() || !is_turbofanned() ||
5302 !can_have_weak_objects());
5303 return is_optimized_code() && can_have_weak_objects();
5306 inline bool IsWeakObject(Object* object) {
5307 return (CanContainWeakObjects() && IsWeakObjectInOptimizedCode(object));
5310 static inline bool IsWeakObjectInOptimizedCode(Object* object);
5312 static Handle<WeakCell> WeakCellFor(Handle<Code> code);
5313 WeakCell* CachedWeakCell();
5315 // Max loop nesting marker used to postpose OSR. We don't take loop
5316 // nesting that is deeper than 5 levels into account.
5317 static const int kMaxLoopNestingMarker = 6;
5319 static const int kConstantPoolSize =
5320 FLAG_enable_embedded_constant_pool ? kIntSize : 0;
5322 // Layout description.
5323 static const int kRelocationInfoOffset = HeapObject::kHeaderSize;
5324 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
5325 static const int kDeoptimizationDataOffset =
5326 kHandlerTableOffset + kPointerSize;
5327 // For FUNCTION kind, we store the type feedback info here.
5328 static const int kTypeFeedbackInfoOffset =
5329 kDeoptimizationDataOffset + kPointerSize;
5330 static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
5331 static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
5332 static const int kInstructionSizeOffset = kGCMetadataOffset + kPointerSize;
5333 static const int kICAgeOffset = kInstructionSizeOffset + kIntSize;
5334 static const int kFlagsOffset = kICAgeOffset + kIntSize;
5335 static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
5336 static const int kKindSpecificFlags2Offset =
5337 kKindSpecificFlags1Offset + kIntSize;
5338 // Note: We might be able to squeeze this into the flags above.
5339 static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
5340 static const int kConstantPoolOffset = kPrologueOffset + kIntSize;
5341 static const int kHeaderPaddingStart =
5342 kConstantPoolOffset + kConstantPoolSize;
5344 // Add padding to align the instruction start following right after
5345 // the Code object header.
5346 static const int kHeaderSize =
5347 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
5349 // Byte offsets within kKindSpecificFlags1Offset.
5350 static const int kFullCodeFlags = kKindSpecificFlags1Offset;
5351 class FullCodeFlagsHasDeoptimizationSupportField:
5352 public BitField<bool, 0, 1> {}; // NOLINT
5353 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
5354 class FullCodeFlagsHasRelocInfoForSerialization
5355 : public BitField<bool, 2, 1> {};
5356 // Bit 3 in this bitfield is unused.
5357 class ProfilerTicksField : public BitField<int, 4, 28> {};
5359 // Flags layout. BitField<type, shift, size>.
5360 class ICStateField : public BitField<InlineCacheState, 0, 4> {};
5361 class TypeField : public BitField<StubType, 4, 1> {};
5362 class CacheHolderField : public BitField<CacheHolderFlag, 5, 2> {};
5363 class KindField : public BitField<Kind, 7, 4> {};
5364 class ExtraICStateField: public BitField<ExtraICState, 11,
5365 PlatformSmiTagging::kSmiValueSize - 11 + 1> {}; // NOLINT
5367 // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
5368 static const int kStackSlotsFirstBit = 0;
5369 static const int kStackSlotsBitCount = 24;
5370 static const int kHasFunctionCacheBit =
5371 kStackSlotsFirstBit + kStackSlotsBitCount;
5372 static const int kMarkedForDeoptimizationBit = kHasFunctionCacheBit + 1;
5373 static const int kIsTurbofannedBit = kMarkedForDeoptimizationBit + 1;
5374 static const int kCanHaveWeakObjects = kIsTurbofannedBit + 1;
5376 STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
5377 STATIC_ASSERT(kCanHaveWeakObjects + 1 <= 32);
5379 class StackSlotsField: public BitField<int,
5380 kStackSlotsFirstBit, kStackSlotsBitCount> {}; // NOLINT
5381 class HasFunctionCacheField : public BitField<bool, kHasFunctionCacheBit, 1> {
5383 class MarkedForDeoptimizationField
5384 : public BitField<bool, kMarkedForDeoptimizationBit, 1> {}; // NOLINT
5385 class IsTurbofannedField : public BitField<bool, kIsTurbofannedBit, 1> {
5387 class CanHaveWeakObjectsField
5388 : public BitField<bool, kCanHaveWeakObjects, 1> {}; // NOLINT
5390 // KindSpecificFlags2 layout (ALL)
5391 static const int kIsCrankshaftedBit = 0;
5392 class IsCrankshaftedField: public BitField<bool,
5393 kIsCrankshaftedBit, 1> {}; // NOLINT
5395 // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
5396 static const int kSafepointTableOffsetFirstBit = kIsCrankshaftedBit + 1;
5397 static const int kSafepointTableOffsetBitCount = 24;
5399 STATIC_ASSERT(kSafepointTableOffsetFirstBit +
5400 kSafepointTableOffsetBitCount <= 32);
5401 STATIC_ASSERT(1 + kSafepointTableOffsetBitCount <= 32);
5403 class SafepointTableOffsetField: public BitField<int,
5404 kSafepointTableOffsetFirstBit,
5405 kSafepointTableOffsetBitCount> {}; // NOLINT
5407 // KindSpecificFlags2 layout (FUNCTION)
5408 class BackEdgeTableOffsetField: public BitField<int,
5409 kIsCrankshaftedBit + 1, 27> {}; // NOLINT
5410 class AllowOSRAtLoopNestingLevelField: public BitField<int,
5411 kIsCrankshaftedBit + 1 + 27, 4> {}; // NOLINT
5412 STATIC_ASSERT(AllowOSRAtLoopNestingLevelField::kMax >= kMaxLoopNestingMarker);
5414 static const int kArgumentsBits = 16;
5415 static const int kMaxArguments = (1 << kArgumentsBits) - 1;
5417 // This constant should be encodable in an ARM instruction.
5418 static const int kFlagsNotUsedInLookup =
5419 TypeField::kMask | CacheHolderField::kMask;
5422 friend class RelocIterator;
5423 friend class Deoptimizer; // For FindCodeAgeSequence.
5425 void ClearInlineCaches(Kind* kind);
5428 byte* FindCodeAgeSequence();
5429 static void GetCodeAgeAndParity(Code* code, Age* age,
5430 MarkingParity* parity);
5431 static void GetCodeAgeAndParity(Isolate* isolate, byte* sequence, Age* age,
5432 MarkingParity* parity);
5433 static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
5435 // Code aging -- platform-specific
5436 static void PatchPlatformCodeAge(Isolate* isolate,
5437 byte* sequence, Age age,
5438 MarkingParity parity);
5440 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5444 // This class describes the layout of dependent codes array of a map. The
5445 // array is partitioned into several groups of dependent codes. Each group
5446 // contains codes with the same dependency on the map. The array has the
5447 // following layout for n dependency groups:
5449 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5450 // | C1 | C2 | ... | Cn | group 1 | group 2 | ... | group n | undefined |
5451 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5453 // The first n elements are Smis, each of them specifies the number of codes
5454 // in the corresponding group. The subsequent elements contain grouped code
5455 // objects in weak cells. The suffix of the array can be filled with the
5456 // undefined value if the number of codes is less than the length of the
5457 // array. The order of the code objects within a group is not preserved.
5459 // All code indexes used in the class are counted starting from the first
5460 // code object of the first group. In other words, code index 0 corresponds
5461 // to array index n = kCodesStartIndex.
5463 class DependentCode: public FixedArray {
5465 enum DependencyGroup {
5466 // Group of code that weakly embed this map and depend on being
5467 // deoptimized when the map is garbage collected.
5469 // Group of code that embed a transition to this map, and depend on being
5470 // deoptimized when the transition is replaced by a new version.
5472 // Group of code that omit run-time prototype checks for prototypes
5473 // described by this map. The group is deoptimized whenever an object
5474 // described by this map changes shape (and transitions to a new map),
5475 // possibly invalidating the assumptions embedded in the code.
5476 kPrototypeCheckGroup,
5477 // Group of code that depends on global property values in property cells
5478 // not being changed.
5479 kPropertyCellChangedGroup,
5480 // Group of code that omit run-time type checks for the field(s) introduced
5483 // Group of code that omit run-time type checks for initial maps of
5485 kInitialMapChangedGroup,
5486 // Group of code that depends on tenuring information in AllocationSites
5487 // not being changed.
5488 kAllocationSiteTenuringChangedGroup,
5489 // Group of code that depends on element transition information in
5490 // AllocationSites not being changed.
5491 kAllocationSiteTransitionChangedGroup
5494 static const int kGroupCount = kAllocationSiteTransitionChangedGroup + 1;
5496 // Array for holding the index of the first code object of each group.
5497 // The last element stores the total number of code objects.
5498 class GroupStartIndexes {
5500 explicit GroupStartIndexes(DependentCode* entries);
5501 void Recompute(DependentCode* entries);
5502 int at(int i) { return start_indexes_[i]; }
5503 int number_of_entries() { return start_indexes_[kGroupCount]; }
5505 int start_indexes_[kGroupCount + 1];
5508 bool Contains(DependencyGroup group, WeakCell* code_cell);
5510 static Handle<DependentCode> InsertCompilationDependencies(
5511 Handle<DependentCode> entries, DependencyGroup group,
5512 Handle<Foreign> info);
5514 static Handle<DependentCode> InsertWeakCode(Handle<DependentCode> entries,
5515 DependencyGroup group,
5516 Handle<WeakCell> code_cell);
5518 void UpdateToFinishedCode(DependencyGroup group, Foreign* info,
5519 WeakCell* code_cell);
5521 void RemoveCompilationDependencies(DependentCode::DependencyGroup group,
5524 void DeoptimizeDependentCodeGroup(Isolate* isolate,
5525 DependentCode::DependencyGroup group);
5527 bool MarkCodeForDeoptimization(Isolate* isolate,
5528 DependentCode::DependencyGroup group);
5530 // The following low-level accessors should only be used by this class
5531 // and the mark compact collector.
5532 inline int number_of_entries(DependencyGroup group);
5533 inline void set_number_of_entries(DependencyGroup group, int value);
5534 inline Object* object_at(int i);
5535 inline void set_object_at(int i, Object* object);
5536 inline void clear_at(int i);
5537 inline void copy(int from, int to);
5538 DECLARE_CAST(DependentCode)
5540 static const char* DependencyGroupName(DependencyGroup group);
5541 static void SetMarkedForDeoptimization(Code* code, DependencyGroup group);
5544 static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5545 DependencyGroup group,
5546 Handle<Object> object);
5547 static Handle<DependentCode> EnsureSpace(Handle<DependentCode> entries);
5548 // Make a room at the end of the given group by moving out the first
5549 // code objects of the subsequent groups.
5550 inline void ExtendGroup(DependencyGroup group);
5551 // Compact by removing cleared weak cells and return true if there was
5552 // any cleared weak cell.
5554 static int Grow(int number_of_entries) {
5555 if (number_of_entries < 5) return number_of_entries + 1;
5556 return number_of_entries * 5 / 4;
5558 static const int kCodesStartIndex = kGroupCount;
5562 class PrototypeInfo;
5565 // All heap objects have a Map that describes their structure.
5566 // A Map contains information about:
5567 // - Size information about the object
5568 // - How to iterate over an object (for garbage collection)
5569 class Map: public HeapObject {
5572 // Size in bytes or kVariableSizeSentinel if instances do not have
5574 inline int instance_size();
5575 inline void set_instance_size(int value);
5577 // Only to clear an unused byte, remove once byte is used.
5578 inline void clear_unused();
5580 // Count of properties allocated in the object.
5581 inline int inobject_properties();
5582 inline void set_inobject_properties(int value);
5585 inline InstanceType instance_type();
5586 inline void set_instance_type(InstanceType value);
5588 // Tells how many unused property fields are available in the
5589 // instance (only used for JSObject in fast mode).
5590 inline int unused_property_fields();
5591 inline void set_unused_property_fields(int value);
5594 inline byte bit_field() const;
5595 inline void set_bit_field(byte value);
5598 inline byte bit_field2() const;
5599 inline void set_bit_field2(byte value);
5602 inline uint32_t bit_field3() const;
5603 inline void set_bit_field3(uint32_t bits);
5605 class EnumLengthBits: public BitField<int,
5606 0, kDescriptorIndexBitCount> {}; // NOLINT
5607 class NumberOfOwnDescriptorsBits: public BitField<int,
5608 kDescriptorIndexBitCount, kDescriptorIndexBitCount> {}; // NOLINT
5609 STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
5610 class DictionaryMap : public BitField<bool, 20, 1> {};
5611 class OwnsDescriptors : public BitField<bool, 21, 1> {};
5612 class HasInstanceCallHandler : public BitField<bool, 22, 1> {};
5613 class Deprecated : public BitField<bool, 23, 1> {};
5614 class IsUnstable : public BitField<bool, 24, 1> {};
5615 class IsMigrationTarget : public BitField<bool, 25, 1> {};
5616 class IsStrong : public BitField<bool, 26, 1> {};
5619 // Keep this bit field at the very end for better code in
5620 // Builtins::kJSConstructStubGeneric stub.
5621 // This counter is used for in-object slack tracking and for map aging.
5622 // The in-object slack tracking is considered enabled when the counter is
5623 // in the range [kSlackTrackingCounterStart, kSlackTrackingCounterEnd].
5624 class Counter : public BitField<int, 28, 4> {};
5625 static const int kSlackTrackingCounterStart = 14;
5626 static const int kSlackTrackingCounterEnd = 8;
5627 static const int kRetainingCounterStart = kSlackTrackingCounterEnd - 1;
5628 static const int kRetainingCounterEnd = 0;
5630 // Tells whether the object in the prototype property will be used
5631 // for instances created from this function. If the prototype
5632 // property is set to a value that is not a JSObject, the prototype
5633 // property will not be used to create instances of the function.
5634 // See ECMA-262, 13.2.2.
5635 inline void set_non_instance_prototype(bool value);
5636 inline bool has_non_instance_prototype();
5638 // Tells whether function has special prototype property. If not, prototype
5639 // property will not be created when accessed (will return undefined),
5640 // and construction from this function will not be allowed.
5641 inline void set_function_with_prototype(bool value);
5642 inline bool function_with_prototype();
5644 // Tells whether the instance with this map should be ignored by the
5645 // Object.getPrototypeOf() function and the __proto__ accessor.
5646 inline void set_is_hidden_prototype() {
5647 set_bit_field(bit_field() | (1 << kIsHiddenPrototype));
5650 inline bool is_hidden_prototype() {
5651 return ((1 << kIsHiddenPrototype) & bit_field()) != 0;
5654 // Records and queries whether the instance has a named interceptor.
5655 inline void set_has_named_interceptor() {
5656 set_bit_field(bit_field() | (1 << kHasNamedInterceptor));
5659 inline bool has_named_interceptor() {
5660 return ((1 << kHasNamedInterceptor) & bit_field()) != 0;
5663 // Records and queries whether the instance has an indexed interceptor.
5664 inline void set_has_indexed_interceptor() {
5665 set_bit_field(bit_field() | (1 << kHasIndexedInterceptor));
5668 inline bool has_indexed_interceptor() {
5669 return ((1 << kHasIndexedInterceptor) & bit_field()) != 0;
5672 // Tells whether the instance is undetectable.
5673 // An undetectable object is a special class of JSObject: 'typeof' operator
5674 // returns undefined, ToBoolean returns false. Otherwise it behaves like
5675 // a normal JS object. It is useful for implementing undetectable
5676 // document.all in Firefox & Safari.
5677 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
5678 inline void set_is_undetectable() {
5679 set_bit_field(bit_field() | (1 << kIsUndetectable));
5682 inline bool is_undetectable() {
5683 return ((1 << kIsUndetectable) & bit_field()) != 0;
5686 // Tells whether the instance has a call-as-function handler.
5687 inline void set_is_observed() {
5688 set_bit_field(bit_field() | (1 << kIsObserved));
5691 inline bool is_observed() {
5692 return ((1 << kIsObserved) & bit_field()) != 0;
5695 inline void set_is_strong();
5696 inline bool is_strong();
5697 inline void set_is_extensible(bool value);
5698 inline bool is_extensible();
5699 inline void set_is_prototype_map(bool value);
5700 inline bool is_prototype_map() const;
5702 inline void set_elements_kind(ElementsKind elements_kind) {
5703 DCHECK(static_cast<int>(elements_kind) < kElementsKindCount);
5704 DCHECK(kElementsKindCount <= (1 << Map::ElementsKindBits::kSize));
5705 set_bit_field2(Map::ElementsKindBits::update(bit_field2(), elements_kind));
5706 DCHECK(this->elements_kind() == elements_kind);
5709 inline ElementsKind elements_kind() {
5710 return Map::ElementsKindBits::decode(bit_field2());
5713 // Tells whether the instance has fast elements that are only Smis.
5714 inline bool has_fast_smi_elements() {
5715 return IsFastSmiElementsKind(elements_kind());
5718 // Tells whether the instance has fast elements.
5719 inline bool has_fast_object_elements() {
5720 return IsFastObjectElementsKind(elements_kind());
5723 inline bool has_fast_smi_or_object_elements() {
5724 return IsFastSmiOrObjectElementsKind(elements_kind());
5727 inline bool has_fast_double_elements() {
5728 return IsFastDoubleElementsKind(elements_kind());
5731 inline bool has_fast_elements() {
5732 return IsFastElementsKind(elements_kind());
5735 inline bool has_sloppy_arguments_elements() {
5736 return IsSloppyArgumentsElements(elements_kind());
5739 inline bool has_external_array_elements() {
5740 return IsExternalArrayElementsKind(elements_kind());
5743 inline bool has_fixed_typed_array_elements() {
5744 return IsFixedTypedArrayElementsKind(elements_kind());
5747 inline bool has_dictionary_elements() {
5748 return IsDictionaryElementsKind(elements_kind());
5751 static bool IsValidElementsTransition(ElementsKind from_kind,
5752 ElementsKind to_kind);
5754 // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
5755 // map with DICTIONARY_ELEMENTS was found in the prototype chain.
5756 bool DictionaryElementsInPrototypeChainOnly();
5758 inline Map* ElementsTransitionMap();
5760 inline FixedArrayBase* GetInitialElements();
5762 // [raw_transitions]: Provides access to the transitions storage field.
5763 // Don't call set_raw_transitions() directly to overwrite transitions, use
5764 // the TransitionArray::ReplaceTransitions() wrapper instead!
5765 DECL_ACCESSORS(raw_transitions, Object)
5766 // [prototype_info]: Per-prototype metadata. Aliased with transitions
5767 // (which prototype maps don't have).
5768 DECL_ACCESSORS(prototype_info, Object)
5769 // PrototypeInfo is created lazily using this helper (which installs it on
5770 // the given prototype's map).
5771 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5772 Handle<JSObject> prototype, Isolate* isolate);
5774 // [prototype chain validity cell]: Associated with a prototype object,
5775 // stored in that object's map's PrototypeInfo, indicates that prototype
5776 // chains through this object are currently valid. The cell will be
5777 // invalidated and replaced when the prototype chain changes.
5778 static Handle<Cell> GetOrCreatePrototypeChainValidityCell(Handle<Map> map,
5780 static const int kPrototypeChainValid = 0;
5781 static const int kPrototypeChainInvalid = 1;
5784 Map* FindFieldOwner(int descriptor);
5786 inline int GetInObjectPropertyOffset(int index);
5788 int NumberOfFields();
5790 // TODO(ishell): candidate with JSObject::MigrateToMap().
5791 bool InstancesNeedRewriting(Map* target, int target_number_of_fields,
5792 int target_inobject, int target_unused,
5793 int* old_number_of_fields);
5794 // TODO(ishell): moveit!
5795 static Handle<Map> GeneralizeAllFieldRepresentations(Handle<Map> map);
5796 MUST_USE_RESULT static Handle<HeapType> GeneralizeFieldType(
5797 Handle<HeapType> type1,
5798 Handle<HeapType> type2,
5800 static void GeneralizeFieldType(Handle<Map> map, int modify_index,
5801 Representation new_representation,
5802 Handle<HeapType> new_field_type);
5803 static Handle<Map> ReconfigureProperty(Handle<Map> map, int modify_index,
5804 PropertyKind new_kind,
5805 PropertyAttributes new_attributes,
5806 Representation new_representation,
5807 Handle<HeapType> new_field_type,
5808 StoreMode store_mode);
5809 static Handle<Map> CopyGeneralizeAllRepresentations(
5810 Handle<Map> map, int modify_index, StoreMode store_mode,
5811 PropertyKind kind, PropertyAttributes attributes, const char* reason);
5813 static Handle<Map> PrepareForDataProperty(Handle<Map> old_map,
5814 int descriptor_number,
5815 Handle<Object> value);
5817 static Handle<Map> Normalize(Handle<Map> map, PropertyNormalizationMode mode,
5818 const char* reason);
5820 // Returns the constructor name (the name (possibly, inferred name) of the
5821 // function that was used to instantiate the object).
5822 String* constructor_name();
5824 // Tells whether the map is used for JSObjects in dictionary mode (ie
5825 // normalized objects, ie objects for which HasFastProperties returns false).
5826 // A map can never be used for both dictionary mode and fast mode JSObjects.
5827 // False by default and for HeapObjects that are not JSObjects.
5828 inline void set_dictionary_map(bool value);
5829 inline bool is_dictionary_map();
5831 // Tells whether the instance needs security checks when accessing its
5833 inline void set_is_access_check_needed(bool access_check_needed);
5834 inline bool is_access_check_needed();
5836 // Returns true if map has a non-empty stub code cache.
5837 inline bool has_code_cache();
5839 // [prototype]: implicit prototype object.
5840 DECL_ACCESSORS(prototype, Object)
5841 // TODO(jkummerow): make set_prototype private.
5842 static void SetPrototype(
5843 Handle<Map> map, Handle<Object> prototype,
5844 PrototypeOptimizationMode proto_mode = FAST_PROTOTYPE);
5846 // [constructor]: points back to the function responsible for this map.
5847 // The field overlaps with the back pointer. All maps in a transition tree
5848 // have the same constructor, so maps with back pointers can walk the
5849 // back pointer chain until they find the map holding their constructor.
5850 DECL_ACCESSORS(constructor_or_backpointer, Object)
5851 inline Object* GetConstructor() const;
5852 inline void SetConstructor(Object* constructor,
5853 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5854 // [back pointer]: points back to the parent map from which a transition
5855 // leads to this map. The field overlaps with the constructor (see above).
5856 inline Object* GetBackPointer();
5857 inline void SetBackPointer(Object* value,
5858 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5860 // [instance descriptors]: describes the object.
5861 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
5863 // [layout descriptor]: describes the object layout.
5864 DECL_ACCESSORS(layout_descriptor, LayoutDescriptor)
5865 // |layout descriptor| accessor which can be used from GC.
5866 inline LayoutDescriptor* layout_descriptor_gc_safe();
5867 inline bool HasFastPointerLayout() const;
5869 // |layout descriptor| accessor that is safe to call even when
5870 // FLAG_unbox_double_fields is disabled (in this case Map does not contain
5871 // |layout_descriptor| field at all).
5872 inline LayoutDescriptor* GetLayoutDescriptor();
5874 inline void UpdateDescriptors(DescriptorArray* descriptors,
5875 LayoutDescriptor* layout_descriptor);
5876 inline void InitializeDescriptors(DescriptorArray* descriptors,
5877 LayoutDescriptor* layout_descriptor);
5879 // [stub cache]: contains stubs compiled for this map.
5880 DECL_ACCESSORS(code_cache, Object)
5882 // [dependent code]: list of optimized codes that weakly embed this map.
5883 DECL_ACCESSORS(dependent_code, DependentCode)
5885 // [weak cell cache]: cache that stores a weak cell pointing to this map.
5886 DECL_ACCESSORS(weak_cell_cache, Object)
5888 inline PropertyDetails GetLastDescriptorDetails();
5891 int number_of_own_descriptors = NumberOfOwnDescriptors();
5892 DCHECK(number_of_own_descriptors > 0);
5893 return number_of_own_descriptors - 1;
5896 int NumberOfOwnDescriptors() {
5897 return NumberOfOwnDescriptorsBits::decode(bit_field3());
5900 void SetNumberOfOwnDescriptors(int number) {
5901 DCHECK(number <= instance_descriptors()->number_of_descriptors());
5902 set_bit_field3(NumberOfOwnDescriptorsBits::update(bit_field3(), number));
5905 inline Cell* RetrieveDescriptorsPointer();
5908 return EnumLengthBits::decode(bit_field3());
5911 void SetEnumLength(int length) {
5912 if (length != kInvalidEnumCacheSentinel) {
5913 DCHECK(length >= 0);
5914 DCHECK(length == 0 || instance_descriptors()->HasEnumCache());
5915 DCHECK(length <= NumberOfOwnDescriptors());
5917 set_bit_field3(EnumLengthBits::update(bit_field3(), length));
5920 inline bool owns_descriptors();
5921 inline void set_owns_descriptors(bool owns_descriptors);
5922 inline bool has_instance_call_handler();
5923 inline void set_has_instance_call_handler();
5924 inline void mark_unstable();
5925 inline bool is_stable();
5926 inline void set_migration_target(bool value);
5927 inline bool is_migration_target();
5928 inline void set_counter(int value);
5929 inline int counter();
5930 inline void deprecate();
5931 inline bool is_deprecated();
5932 inline bool CanBeDeprecated();
5933 // Returns a non-deprecated version of the input. If the input was not
5934 // deprecated, it is directly returned. Otherwise, the non-deprecated version
5935 // is found by re-transitioning from the root of the transition tree using the
5936 // descriptor array of the map. Returns MaybeHandle<Map>() if no updated map
5938 static MaybeHandle<Map> TryUpdate(Handle<Map> map) WARN_UNUSED_RESULT;
5940 // Returns a non-deprecated version of the input. This method may deprecate
5941 // existing maps along the way if encodings conflict. Not for use while
5942 // gathering type feedback. Use TryUpdate in those cases instead.
5943 static Handle<Map> Update(Handle<Map> map);
5945 static Handle<Map> CopyDropDescriptors(Handle<Map> map);
5946 static Handle<Map> CopyInsertDescriptor(Handle<Map> map,
5947 Descriptor* descriptor,
5948 TransitionFlag flag);
5950 MUST_USE_RESULT static MaybeHandle<Map> CopyWithField(
5953 Handle<HeapType> type,
5954 PropertyAttributes attributes,
5955 Representation representation,
5956 TransitionFlag flag);
5958 MUST_USE_RESULT static MaybeHandle<Map> CopyWithConstant(
5961 Handle<Object> constant,
5962 PropertyAttributes attributes,
5963 TransitionFlag flag);
5965 // Returns a new map with all transitions dropped from the given map and
5966 // the ElementsKind set.
5967 static Handle<Map> TransitionElementsTo(Handle<Map> map,
5968 ElementsKind to_kind);
5970 static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
5972 static Handle<Map> CopyAsElementsKind(Handle<Map> map,
5974 TransitionFlag flag);
5976 static Handle<Map> CopyForObserved(Handle<Map> map);
5978 static Handle<Map> CopyForPreventExtensions(Handle<Map> map,
5979 PropertyAttributes attrs_to_add,
5980 Handle<Symbol> transition_marker,
5981 const char* reason);
5983 static Handle<Map> FixProxy(Handle<Map> map, InstanceType type, int size);
5986 // Maximal number of fast properties. Used to restrict the number of map
5987 // transitions to avoid an explosion in the number of maps for objects used as
5989 inline bool TooManyFastProperties(StoreFromKeyed store_mode);
5990 static Handle<Map> TransitionToDataProperty(Handle<Map> map,
5992 Handle<Object> value,
5993 PropertyAttributes attributes,
5994 StoreFromKeyed store_mode);
5995 static Handle<Map> TransitionToAccessorProperty(
5996 Handle<Map> map, Handle<Name> name, AccessorComponent component,
5997 Handle<Object> accessor, PropertyAttributes attributes);
5998 static Handle<Map> ReconfigureExistingProperty(Handle<Map> map,
6001 PropertyAttributes attributes);
6003 inline void AppendDescriptor(Descriptor* desc);
6005 // Returns a copy of the map, prepared for inserting into the transition
6006 // tree (if the |map| owns descriptors then the new one will share
6007 // descriptors with |map|).
6008 static Handle<Map> CopyForTransition(Handle<Map> map, const char* reason);
6010 // Returns a copy of the map, with all transitions dropped from the
6011 // instance descriptors.
6012 static Handle<Map> Copy(Handle<Map> map, const char* reason);
6013 static Handle<Map> Create(Isolate* isolate, int inobject_properties);
6015 // Returns the next free property index (only valid for FAST MODE).
6016 int NextFreePropertyIndex();
6018 // Returns the number of properties described in instance_descriptors
6019 // filtering out properties with the specified attributes.
6020 int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
6021 PropertyAttributes filter = NONE);
6025 // Code cache operations.
6027 // Clears the code cache.
6028 inline void ClearCodeCache(Heap* heap);
6030 // Update code cache.
6031 static void UpdateCodeCache(Handle<Map> map,
6035 // Extend the descriptor array of the map with the list of descriptors.
6036 // In case of duplicates, the latest descriptor is used.
6037 static void AppendCallbackDescriptors(Handle<Map> map,
6038 Handle<Object> descriptors);
6040 static inline int SlackForArraySize(int old_size, int size_limit);
6042 static void EnsureDescriptorSlack(Handle<Map> map, int slack);
6044 // Returns the found code or undefined if absent.
6045 Object* FindInCodeCache(Name* name, Code::Flags flags);
6047 // Returns the non-negative index of the code object if it is in the
6048 // cache and -1 otherwise.
6049 int IndexInCodeCache(Object* name, Code* code);
6051 // Removes a code object from the code cache at the given index.
6052 void RemoveFromCodeCache(Name* name, Code* code, int index);
6054 // Computes a hash value for this map, to be used in HashTables and such.
6057 // Returns the map that this map transitions to if its elements_kind
6058 // is changed to |elements_kind|, or NULL if no such map is cached yet.
6059 // |safe_to_add_transitions| is set to false if adding transitions is not
6061 Map* LookupElementsTransitionMap(ElementsKind elements_kind);
6063 // Returns the transitioned map for this map with the most generic
6064 // elements_kind that's found in |candidates|, or null handle if no match is
6066 static Handle<Map> FindTransitionedMap(Handle<Map> map,
6067 MapHandleList* candidates);
6069 bool CanTransition() {
6070 // Only JSObject and subtypes have map transitions and back pointers.
6071 STATIC_ASSERT(LAST_TYPE == LAST_JS_OBJECT_TYPE);
6072 return instance_type() >= FIRST_JS_OBJECT_TYPE;
6075 bool IsJSObjectMap() {
6076 return instance_type() >= FIRST_JS_OBJECT_TYPE;
6078 bool IsJSArrayMap() { return instance_type() == JS_ARRAY_TYPE; }
6079 bool IsStringMap() { return instance_type() < FIRST_NONSTRING_TYPE; }
6080 bool IsJSProxyMap() {
6081 InstanceType type = instance_type();
6082 return FIRST_JS_PROXY_TYPE <= type && type <= LAST_JS_PROXY_TYPE;
6084 bool IsJSGlobalProxyMap() {
6085 return instance_type() == JS_GLOBAL_PROXY_TYPE;
6087 bool IsJSGlobalObjectMap() {
6088 return instance_type() == JS_GLOBAL_OBJECT_TYPE;
6090 bool IsGlobalObjectMap() {
6091 const InstanceType type = instance_type();
6092 return type == JS_GLOBAL_OBJECT_TYPE || type == JS_BUILTINS_OBJECT_TYPE;
6095 inline bool CanOmitMapChecks();
6097 static void AddDependentCode(Handle<Map> map,
6098 DependentCode::DependencyGroup group,
6101 bool IsMapInArrayPrototypeChain();
6103 static Handle<WeakCell> WeakCellForMap(Handle<Map> map);
6105 // Dispatched behavior.
6106 DECLARE_PRINTER(Map)
6107 DECLARE_VERIFIER(Map)
6110 void DictionaryMapVerify();
6111 void VerifyOmittedMapChecks();
6114 inline int visitor_id();
6115 inline void set_visitor_id(int visitor_id);
6117 static Handle<Map> TransitionToPrototype(Handle<Map> map,
6118 Handle<Object> prototype,
6119 PrototypeOptimizationMode mode);
6121 static const int kMaxPreAllocatedPropertyFields = 255;
6123 // Layout description.
6124 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
6125 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
6126 static const int kBitField3Offset = kInstanceAttributesOffset + kIntSize;
6127 static const int kPrototypeOffset = kBitField3Offset + kPointerSize;
6128 static const int kConstructorOrBackPointerOffset =
6129 kPrototypeOffset + kPointerSize;
6130 // When there is only one transition, it is stored directly in this field;
6131 // otherwise a transition array is used.
6132 // For prototype maps, this slot is used to store this map's PrototypeInfo
6134 static const int kTransitionsOrPrototypeInfoOffset =
6135 kConstructorOrBackPointerOffset + kPointerSize;
6136 static const int kDescriptorsOffset =
6137 kTransitionsOrPrototypeInfoOffset + kPointerSize;
6138 #if V8_DOUBLE_FIELDS_UNBOXING
6139 static const int kLayoutDecriptorOffset = kDescriptorsOffset + kPointerSize;
6140 static const int kCodeCacheOffset = kLayoutDecriptorOffset + kPointerSize;
6142 static const int kLayoutDecriptorOffset = 1; // Must not be ever accessed.
6143 static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
6145 static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
6146 static const int kWeakCellCacheOffset = kDependentCodeOffset + kPointerSize;
6147 static const int kSize = kWeakCellCacheOffset + kPointerSize;
6149 // Layout of pointer fields. Heap iteration code relies on them
6150 // being continuously allocated.
6151 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
6152 static const int kPointerFieldsEndOffset = kSize;
6154 // Byte offsets within kInstanceSizesOffset.
6155 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
6156 static const int kInObjectPropertiesByte = 1;
6157 static const int kInObjectPropertiesOffset =
6158 kInstanceSizesOffset + kInObjectPropertiesByte;
6159 // Note there is one byte available for use here.
6160 static const int kUnusedByte = 2;
6161 static const int kUnusedOffset = kInstanceSizesOffset + kUnusedByte;
6162 static const int kVisitorIdByte = 3;
6163 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
6165 // Byte offsets within kInstanceAttributesOffset attributes.
6166 #if V8_TARGET_LITTLE_ENDIAN
6167 // Order instance type and bit field together such that they can be loaded
6168 // together as a 16-bit word with instance type in the lower 8 bits regardless
6169 // of endianess. Also provide endian-independent offset to that 16-bit word.
6170 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
6171 static const int kBitFieldOffset = kInstanceAttributesOffset + 1;
6173 static const int kBitFieldOffset = kInstanceAttributesOffset + 0;
6174 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 1;
6176 static const int kInstanceTypeAndBitFieldOffset =
6177 kInstanceAttributesOffset + 0;
6178 static const int kBitField2Offset = kInstanceAttributesOffset + 2;
6179 static const int kUnusedPropertyFieldsByte = 3;
6180 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 3;
6182 STATIC_ASSERT(kInstanceTypeAndBitFieldOffset ==
6183 Internals::kMapInstanceTypeAndBitFieldOffset);
6185 // Bit positions for bit field.
6186 static const int kHasNonInstancePrototype = 0;
6187 static const int kIsHiddenPrototype = 1;
6188 static const int kHasNamedInterceptor = 2;
6189 static const int kHasIndexedInterceptor = 3;
6190 static const int kIsUndetectable = 4;
6191 static const int kIsObserved = 5;
6192 static const int kIsAccessCheckNeeded = 6;
6193 class FunctionWithPrototype: public BitField<bool, 7, 1> {};
6195 // Bit positions for bit field 2
6196 static const int kIsExtensible = 0;
6197 static const int kStringWrapperSafeForDefaultValueOf = 1;
6198 class IsPrototypeMapBits : public BitField<bool, 2, 1> {};
6199 class ElementsKindBits: public BitField<ElementsKind, 3, 5> {};
6201 // Derived values from bit field 2
6202 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
6203 (FAST_ELEMENTS + 1) << Map::ElementsKindBits::kShift) - 1;
6204 static const int8_t kMaximumBitField2FastSmiElementValue =
6205 static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
6206 Map::ElementsKindBits::kShift) - 1;
6207 static const int8_t kMaximumBitField2FastHoleyElementValue =
6208 static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
6209 Map::ElementsKindBits::kShift) - 1;
6210 static const int8_t kMaximumBitField2FastHoleySmiElementValue =
6211 static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
6212 Map::ElementsKindBits::kShift) - 1;
6214 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
6215 kPointerFieldsEndOffset,
6216 kSize> BodyDescriptor;
6218 // Compares this map to another to see if they describe equivalent objects.
6219 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
6220 // it had exactly zero inobject properties.
6221 // The "shared" flags of both this map and |other| are ignored.
6222 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
6224 // Returns true if given field is unboxed double.
6225 inline bool IsUnboxedDoubleField(FieldIndex index);
6228 static void TraceTransition(const char* what, Map* from, Map* to, Name* name);
6229 static void TraceAllTransitions(Map* map);
6232 static inline Handle<Map> CopyInstallDescriptorsForTesting(
6233 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
6234 Handle<LayoutDescriptor> layout_descriptor);
6237 static void ConnectTransition(Handle<Map> parent, Handle<Map> child,
6238 Handle<Name> name, SimpleTransitionFlag flag);
6240 bool EquivalentToForTransition(Map* other);
6241 static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
6242 static Handle<Map> ShareDescriptor(Handle<Map> map,
6243 Handle<DescriptorArray> descriptors,
6244 Descriptor* descriptor);
6245 static Handle<Map> CopyInstallDescriptors(
6246 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
6247 Handle<LayoutDescriptor> layout_descriptor);
6248 static Handle<Map> CopyAddDescriptor(Handle<Map> map,
6249 Descriptor* descriptor,
6250 TransitionFlag flag);
6251 static Handle<Map> CopyReplaceDescriptors(
6252 Handle<Map> map, Handle<DescriptorArray> descriptors,
6253 Handle<LayoutDescriptor> layout_descriptor, TransitionFlag flag,
6254 MaybeHandle<Name> maybe_name, const char* reason,
6255 SimpleTransitionFlag simple_flag);
6257 static Handle<Map> CopyReplaceDescriptor(Handle<Map> map,
6258 Handle<DescriptorArray> descriptors,
6259 Descriptor* descriptor,
6261 TransitionFlag flag);
6262 static MUST_USE_RESULT MaybeHandle<Map> TryReconfigureExistingProperty(
6263 Handle<Map> map, int descriptor, PropertyKind kind,
6264 PropertyAttributes attributes, const char** reason);
6266 static Handle<Map> CopyNormalized(Handle<Map> map,
6267 PropertyNormalizationMode mode);
6269 // Fires when the layout of an object with a leaf map changes.
6270 // This includes adding transitions to the leaf map or changing
6271 // the descriptor array.
6272 inline void NotifyLeafMapLayoutChange();
6274 void DeprecateTransitionTree();
6275 bool DeprecateTarget(PropertyKind kind, Name* key,
6276 PropertyAttributes attributes,
6277 DescriptorArray* new_descriptors,
6278 LayoutDescriptor* new_layout_descriptor);
6280 Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
6282 // Update field type of the given descriptor to new representation and new
6283 // type. The type must be prepared for storing in descriptor array:
6284 // it must be either a simple type or a map wrapped in a weak cell.
6285 void UpdateFieldType(int descriptor_number, Handle<Name> name,
6286 Representation new_representation,
6287 Handle<Object> new_wrapped_type);
6289 void PrintReconfiguration(FILE* file, int modify_index, PropertyKind kind,
6290 PropertyAttributes attributes);
6291 void PrintGeneralization(FILE* file,
6296 bool constant_to_field,
6297 Representation old_representation,
6298 Representation new_representation,
6299 HeapType* old_field_type,
6300 HeapType* new_field_type);
6302 static const int kFastPropertiesSoftLimit = 12;
6303 static const int kMaxFastProperties = 128;
6305 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
6309 // An abstract superclass, a marker class really, for simple structure classes.
6310 // It doesn't carry much functionality but allows struct classes to be
6311 // identified in the type system.
6312 class Struct: public HeapObject {
6314 inline void InitializeBody(int object_size);
6315 DECLARE_CAST(Struct)
6319 // A simple one-element struct, useful where smis need to be boxed.
6320 class Box : public Struct {
6322 // [value]: the boxed contents.
6323 DECL_ACCESSORS(value, Object)
6327 // Dispatched behavior.
6328 DECLARE_PRINTER(Box)
6329 DECLARE_VERIFIER(Box)
6331 static const int kValueOffset = HeapObject::kHeaderSize;
6332 static const int kSize = kValueOffset + kPointerSize;
6335 DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
6339 // Container for metadata stored on each prototype map.
6340 class PrototypeInfo : public Struct {
6342 // [prototype_users]: WeakFixedArray containing maps using this prototype,
6343 // or Smi(0) if uninitialized.
6344 DECL_ACCESSORS(prototype_users, Object)
6345 // [validity_cell]: Cell containing the validity bit for prototype chains
6346 // going through this object, or Smi(0) if uninitialized.
6347 DECL_ACCESSORS(validity_cell, Object)
6348 // [constructor_name]: User-friendly name of the original constructor.
6349 DECL_ACCESSORS(constructor_name, Object)
6351 DECLARE_CAST(PrototypeInfo)
6353 // Dispatched behavior.
6354 DECLARE_PRINTER(PrototypeInfo)
6355 DECLARE_VERIFIER(PrototypeInfo)
6357 static const int kPrototypeUsersOffset = HeapObject::kHeaderSize;
6358 static const int kValidityCellOffset = kPrototypeUsersOffset + kPointerSize;
6359 static const int kConstructorNameOffset = kValidityCellOffset + kPointerSize;
6360 static const int kSize = kConstructorNameOffset + kPointerSize;
6363 DISALLOW_IMPLICIT_CONSTRUCTORS(PrototypeInfo);
6367 // Script describes a script which has been added to the VM.
6368 class Script: public Struct {
6377 // Script compilation types.
6378 enum CompilationType {
6379 COMPILATION_TYPE_HOST = 0,
6380 COMPILATION_TYPE_EVAL = 1
6383 // Script compilation state.
6384 enum CompilationState {
6385 COMPILATION_STATE_INITIAL = 0,
6386 COMPILATION_STATE_COMPILED = 1
6389 // [source]: the script source.
6390 DECL_ACCESSORS(source, Object)
6392 // [name]: the script name.
6393 DECL_ACCESSORS(name, Object)
6395 // [id]: the script id.
6396 DECL_ACCESSORS(id, Smi)
6398 // [line_offset]: script line offset in resource from where it was extracted.
6399 DECL_ACCESSORS(line_offset, Smi)
6401 // [column_offset]: script column offset in resource from where it was
6403 DECL_ACCESSORS(column_offset, Smi)
6405 // [context_data]: context data for the context this script was compiled in.
6406 DECL_ACCESSORS(context_data, Object)
6408 // [wrapper]: the wrapper cache. This is either undefined or a WeakCell.
6409 DECL_ACCESSORS(wrapper, HeapObject)
6411 // [type]: the script type.
6412 DECL_ACCESSORS(type, Smi)
6414 // [line_ends]: FixedArray of line ends positions.
6415 DECL_ACCESSORS(line_ends, Object)
6417 // [eval_from_shared]: for eval scripts the shared funcion info for the
6418 // function from which eval was called.
6419 DECL_ACCESSORS(eval_from_shared, Object)
6421 // [eval_from_instructions_offset]: the instruction offset in the code for the
6422 // function from which eval was called where eval was called.
6423 DECL_ACCESSORS(eval_from_instructions_offset, Smi)
6425 // [shared_function_infos]: weak fixed array containing all shared
6426 // function infos created from this script.
6427 DECL_ACCESSORS(shared_function_infos, Object)
6429 // [flags]: Holds an exciting bitfield.
6430 DECL_ACCESSORS(flags, Smi)
6432 // [source_url]: sourceURL from magic comment
6433 DECL_ACCESSORS(source_url, Object)
6435 // [source_url]: sourceMappingURL magic comment
6436 DECL_ACCESSORS(source_mapping_url, Object)
6438 // [compilation_type]: how the the script was compiled. Encoded in the
6440 inline CompilationType compilation_type();
6441 inline void set_compilation_type(CompilationType type);
6443 // [compilation_state]: determines whether the script has already been
6444 // compiled. Encoded in the 'flags' field.
6445 inline CompilationState compilation_state();
6446 inline void set_compilation_state(CompilationState state);
6448 // [origin_options]: optional attributes set by the embedder via ScriptOrigin,
6449 // and used by the embedder to make decisions about the script. V8 just passes
6450 // this through. Encoded in the 'flags' field.
6451 inline v8::ScriptOriginOptions origin_options();
6452 inline void set_origin_options(ScriptOriginOptions origin_options);
6454 DECLARE_CAST(Script)
6456 // If script source is an external string, check that the underlying
6457 // resource is accessible. Otherwise, always return true.
6458 inline bool HasValidSource();
6460 // Convert code position into column number.
6461 static int GetColumnNumber(Handle<Script> script, int code_pos);
6463 // Convert code position into (zero-based) line number.
6464 // The non-handlified version does not allocate, but may be much slower.
6465 static int GetLineNumber(Handle<Script> script, int code_pos);
6466 int GetLineNumber(int code_pos);
6468 static Handle<Object> GetNameOrSourceURL(Handle<Script> script);
6470 // Init line_ends array with code positions of line ends inside script source.
6471 static void InitLineEnds(Handle<Script> script);
6473 // Get the JS object wrapping the given script; create it if none exists.
6474 static Handle<JSObject> GetWrapper(Handle<Script> script);
6476 // Look through the list of existing shared function infos to find one
6477 // that matches the function literal. Return empty handle if not found.
6478 MaybeHandle<SharedFunctionInfo> FindSharedFunctionInfo(FunctionLiteral* fun);
6480 // Dispatched behavior.
6481 DECLARE_PRINTER(Script)
6482 DECLARE_VERIFIER(Script)
6484 static const int kSourceOffset = HeapObject::kHeaderSize;
6485 static const int kNameOffset = kSourceOffset + kPointerSize;
6486 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
6487 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
6488 static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
6489 static const int kWrapperOffset = kContextOffset + kPointerSize;
6490 static const int kTypeOffset = kWrapperOffset + kPointerSize;
6491 static const int kLineEndsOffset = kTypeOffset + kPointerSize;
6492 static const int kIdOffset = kLineEndsOffset + kPointerSize;
6493 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
6494 static const int kEvalFrominstructionsOffsetOffset =
6495 kEvalFromSharedOffset + kPointerSize;
6496 static const int kSharedFunctionInfosOffset =
6497 kEvalFrominstructionsOffsetOffset + kPointerSize;
6498 static const int kFlagsOffset = kSharedFunctionInfosOffset + kPointerSize;
6499 static const int kSourceUrlOffset = kFlagsOffset + kPointerSize;
6500 static const int kSourceMappingUrlOffset = kSourceUrlOffset + kPointerSize;
6501 static const int kSize = kSourceMappingUrlOffset + kPointerSize;
6504 int GetLineNumberWithArray(int code_pos);
6506 // Bit positions in the flags field.
6507 static const int kCompilationTypeBit = 0;
6508 static const int kCompilationStateBit = 1;
6509 static const int kOriginOptionsShift = 2;
6510 static const int kOriginOptionsSize = 3;
6511 static const int kOriginOptionsMask = ((1 << kOriginOptionsSize) - 1)
6512 << kOriginOptionsShift;
6514 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6518 // List of builtin functions we want to identify to improve code
6521 // Each entry has a name of a global object property holding an object
6522 // optionally followed by ".prototype", a name of a builtin function
6523 // on the object (the one the id is set for), and a label.
6525 // Installation of ids for the selected builtin functions is handled
6526 // by the bootstrapper.
6527 #define FUNCTIONS_WITH_ID_LIST(V) \
6528 V(Array.prototype, indexOf, ArrayIndexOf) \
6529 V(Array.prototype, lastIndexOf, ArrayLastIndexOf) \
6530 V(Array.prototype, push, ArrayPush) \
6531 V(Array.prototype, pop, ArrayPop) \
6532 V(Array.prototype, shift, ArrayShift) \
6533 V(Function.prototype, apply, FunctionApply) \
6534 V(Function.prototype, call, FunctionCall) \
6535 V(String.prototype, charCodeAt, StringCharCodeAt) \
6536 V(String.prototype, charAt, StringCharAt) \
6537 V(String, fromCharCode, StringFromCharCode) \
6538 V(Math, random, MathRandom) \
6539 V(Math, floor, MathFloor) \
6540 V(Math, round, MathRound) \
6541 V(Math, ceil, MathCeil) \
6542 V(Math, abs, MathAbs) \
6543 V(Math, log, MathLog) \
6544 V(Math, exp, MathExp) \
6545 V(Math, sqrt, MathSqrt) \
6546 V(Math, pow, MathPow) \
6547 V(Math, max, MathMax) \
6548 V(Math, min, MathMin) \
6549 V(Math, cos, MathCos) \
6550 V(Math, sin, MathSin) \
6551 V(Math, tan, MathTan) \
6552 V(Math, acos, MathAcos) \
6553 V(Math, asin, MathAsin) \
6554 V(Math, atan, MathAtan) \
6555 V(Math, atan2, MathAtan2) \
6556 V(Math, imul, MathImul) \
6557 V(Math, clz32, MathClz32) \
6558 V(Math, fround, MathFround)
6560 #define ATOMIC_FUNCTIONS_WITH_ID_LIST(V) \
6561 V(Atomics, load, AtomicsLoad) \
6562 V(Atomics, store, AtomicsStore)
6564 enum BuiltinFunctionId {
6566 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
6568 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6569 ATOMIC_FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6570 #undef DECLARE_FUNCTION_ID
6571 // Fake id for a special case of Math.pow. Note, it continues the
6572 // list of math functions.
6577 // Result of searching in an optimized code map of a SharedFunctionInfo. Note
6578 // that both {code} and {literals} can be NULL to pass search result status.
6579 struct CodeAndLiterals {
6580 Code* code; // Cached optimized code.
6581 FixedArray* literals; // Cached literals array.
6585 // SharedFunctionInfo describes the JSFunction information that can be
6586 // shared by multiple instances of the function.
6587 class SharedFunctionInfo: public HeapObject {
6589 // [name]: Function name.
6590 DECL_ACCESSORS(name, Object)
6592 // [code]: Function code.
6593 DECL_ACCESSORS(code, Code)
6594 inline void ReplaceCode(Code* code);
6596 // [optimized_code_map]: Map from native context to optimized code
6597 // and a shared literals array or Smi(0) if none.
6598 DECL_ACCESSORS(optimized_code_map, Object)
6600 // Returns entry from optimized code map for specified context and OSR entry.
6601 // Note that {code == nullptr} indicates no matching entry has been found,
6602 // whereas {literals == nullptr} indicates the code is context-independent.
6603 CodeAndLiterals SearchOptimizedCodeMap(Context* native_context,
6604 BailoutId osr_ast_id);
6606 // Clear optimized code map.
6607 void ClearOptimizedCodeMap();
6609 // Removed a specific optimized code object from the optimized code map.
6610 void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
6612 // Trims the optimized code map after entries have been removed.
6613 void TrimOptimizedCodeMap(int shrink_by);
6615 // Add a new entry to the optimized code map for context-independent code.
6616 static void AddSharedCodeToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6619 // Add a new entry to the optimized code map for context-dependent code.
6620 static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6621 Handle<Context> native_context,
6623 Handle<FixedArray> literals,
6624 BailoutId osr_ast_id);
6626 // Set up the link between shared function info and the script. The shared
6627 // function info is added to the list on the script.
6628 static void SetScript(Handle<SharedFunctionInfo> shared,
6629 Handle<Object> script_object);
6631 // Layout description of the optimized code map.
6632 static const int kNextMapIndex = 0;
6633 static const int kSharedCodeIndex = 1;
6634 static const int kEntriesStart = 2;
6635 static const int kContextOffset = 0;
6636 static const int kCachedCodeOffset = 1;
6637 static const int kLiteralsOffset = 2;
6638 static const int kOsrAstIdOffset = 3;
6639 static const int kEntryLength = 4;
6640 static const int kInitialLength = kEntriesStart + kEntryLength;
6642 // [scope_info]: Scope info.
6643 DECL_ACCESSORS(scope_info, ScopeInfo)
6645 // [construct stub]: Code stub for constructing instances of this function.
6646 DECL_ACCESSORS(construct_stub, Code)
6648 // Returns if this function has been compiled to native code yet.
6649 inline bool is_compiled();
6651 // [length]: The function length - usually the number of declared parameters.
6652 // Use up to 2^30 parameters.
6653 inline int length() const;
6654 inline void set_length(int value);
6656 // [internal formal parameter count]: The declared number of parameters.
6657 // For subclass constructors, also includes new.target.
6658 // The size of function's frame is internal_formal_parameter_count + 1.
6659 inline int internal_formal_parameter_count() const;
6660 inline void set_internal_formal_parameter_count(int value);
6662 // Set the formal parameter count so the function code will be
6663 // called without using argument adaptor frames.
6664 inline void DontAdaptArguments();
6666 // [expected_nof_properties]: Expected number of properties for the function.
6667 inline int expected_nof_properties() const;
6668 inline void set_expected_nof_properties(int value);
6670 // [feedback_vector] - accumulates ast node feedback from full-codegen and
6671 // (increasingly) from crankshafted code where sufficient feedback isn't
6673 DECL_ACCESSORS(feedback_vector, TypeFeedbackVector)
6675 // Unconditionally clear the type feedback vector (including vector ICs).
6676 void ClearTypeFeedbackInfo();
6678 // Clear the type feedback vector with a more subtle policy at GC time.
6679 void ClearTypeFeedbackInfoAtGCTime();
6682 // [unique_id] - For --trace-maps purposes, an identifier that's persistent
6683 // even if the GC moves this SharedFunctionInfo.
6684 inline int unique_id() const;
6685 inline void set_unique_id(int value);
6688 // [instance class name]: class name for instances.
6689 DECL_ACCESSORS(instance_class_name, Object)
6691 // [function data]: This field holds some additional data for function.
6692 // Currently it has one of:
6693 // - a FunctionTemplateInfo to make benefit the API [IsApiFunction()].
6694 // - a Smi identifying a builtin function [HasBuiltinFunctionId()].
6695 // - a BytecodeArray for the interpreter [HasBytecodeArray()].
6696 // In the long run we don't want all functions to have this field but
6697 // we can fix that when we have a better model for storing hidden data
6699 DECL_ACCESSORS(function_data, Object)
6701 inline bool IsApiFunction();
6702 inline FunctionTemplateInfo* get_api_func_data();
6703 inline bool HasBuiltinFunctionId();
6704 inline BuiltinFunctionId builtin_function_id();
6705 inline bool HasBytecodeArray();
6706 inline BytecodeArray* bytecode_array();
6708 // [script info]: Script from which the function originates.
6709 DECL_ACCESSORS(script, Object)
6711 // [num_literals]: Number of literals used by this function.
6712 inline int num_literals() const;
6713 inline void set_num_literals(int value);
6715 // [start_position_and_type]: Field used to store both the source code
6716 // position, whether or not the function is a function expression,
6717 // and whether or not the function is a toplevel function. The two
6718 // least significants bit indicates whether the function is an
6719 // expression and the rest contains the source code position.
6720 inline int start_position_and_type() const;
6721 inline void set_start_position_and_type(int value);
6723 // The function is subject to debugging if a debug info is attached.
6724 inline bool HasDebugInfo();
6725 inline DebugInfo* GetDebugInfo();
6727 // A function has debug code if the compiled code has debug break slots.
6728 inline bool HasDebugCode();
6730 // [debug info]: Debug information.
6731 DECL_ACCESSORS(debug_info, Object)
6733 // [inferred name]: Name inferred from variable or property
6734 // assignment of this function. Used to facilitate debugging and
6735 // profiling of JavaScript code written in OO style, where almost
6736 // all functions are anonymous but are assigned to object
6738 DECL_ACCESSORS(inferred_name, String)
6740 // The function's name if it is non-empty, otherwise the inferred name.
6741 String* DebugName();
6743 // Position of the 'function' token in the script source.
6744 inline int function_token_position() const;
6745 inline void set_function_token_position(int function_token_position);
6747 // Position of this function in the script source.
6748 inline int start_position() const;
6749 inline void set_start_position(int start_position);
6751 // End position of this function in the script source.
6752 inline int end_position() const;
6753 inline void set_end_position(int end_position);
6755 // Is this function a function expression in the source code.
6756 DECL_BOOLEAN_ACCESSORS(is_expression)
6758 // Is this function a top-level function (scripts, evals).
6759 DECL_BOOLEAN_ACCESSORS(is_toplevel)
6761 // Bit field containing various information collected by the compiler to
6762 // drive optimization.
6763 inline int compiler_hints() const;
6764 inline void set_compiler_hints(int value);
6766 inline int ast_node_count() const;
6767 inline void set_ast_node_count(int count);
6769 inline int profiler_ticks() const;
6770 inline void set_profiler_ticks(int ticks);
6772 // Inline cache age is used to infer whether the function survived a context
6773 // disposal or not. In the former case we reset the opt_count.
6774 inline int ic_age();
6775 inline void set_ic_age(int age);
6777 // Indicates if this function can be lazy compiled.
6778 // This is used to determine if we can safely flush code from a function
6779 // when doing GC if we expect that the function will no longer be used.
6780 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
6782 // Indicates if this function can be lazy compiled without a context.
6783 // This is used to determine if we can force compilation without reaching
6784 // the function through program execution but through other means (e.g. heap
6785 // iteration by the debugger).
6786 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
6788 // Indicates whether optimizations have been disabled for this
6789 // shared function info. If a function is repeatedly optimized or if
6790 // we cannot optimize the function we disable optimization to avoid
6791 // spending time attempting to optimize it again.
6792 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
6794 // Indicates the language mode.
6795 inline LanguageMode language_mode();
6796 inline void set_language_mode(LanguageMode language_mode);
6798 // False if the function definitely does not allocate an arguments object.
6799 DECL_BOOLEAN_ACCESSORS(uses_arguments)
6801 // Indicates that this function uses a super property (or an eval that may
6802 // use a super property).
6803 // This is needed to set up the [[HomeObject]] on the function instance.
6804 DECL_BOOLEAN_ACCESSORS(needs_home_object)
6806 // True if the function has any duplicated parameter names.
6807 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
6809 // Indicates whether the function is a native function.
6810 // These needs special treatment in .call and .apply since
6811 // null passed as the receiver should not be translated to the
6813 DECL_BOOLEAN_ACCESSORS(native)
6815 // Indicate that this function should always be inlined in optimized code.
6816 DECL_BOOLEAN_ACCESSORS(force_inline)
6818 // Indicates that the function was created by the Function function.
6819 // Though it's anonymous, toString should treat it as if it had the name
6820 // "anonymous". We don't set the name itself so that the system does not
6821 // see a binding for it.
6822 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
6824 // Indicates whether the function is a bound function created using
6825 // the bind function.
6826 DECL_BOOLEAN_ACCESSORS(bound)
6828 // Indicates that the function is anonymous (the name field can be set
6829 // through the API, which does not change this flag).
6830 DECL_BOOLEAN_ACCESSORS(is_anonymous)
6832 // Is this a function or top-level/eval code.
6833 DECL_BOOLEAN_ACCESSORS(is_function)
6835 // Indicates that code for this function cannot be compiled with Crankshaft.
6836 DECL_BOOLEAN_ACCESSORS(dont_crankshaft)
6838 // Indicates that code for this function cannot be flushed.
6839 DECL_BOOLEAN_ACCESSORS(dont_flush)
6841 // Indicates that this function is a generator.
6842 DECL_BOOLEAN_ACCESSORS(is_generator)
6844 // Indicates that this function is an arrow function.
6845 DECL_BOOLEAN_ACCESSORS(is_arrow)
6847 // Indicates that this function is a concise method.
6848 DECL_BOOLEAN_ACCESSORS(is_concise_method)
6850 // Indicates that this function is an accessor (getter or setter).
6851 DECL_BOOLEAN_ACCESSORS(is_accessor_function)
6853 // Indicates that this function is a default constructor.
6854 DECL_BOOLEAN_ACCESSORS(is_default_constructor)
6856 // Indicates that this function is an asm function.
6857 DECL_BOOLEAN_ACCESSORS(asm_function)
6859 // Indicates that the the shared function info is deserialized from cache.
6860 DECL_BOOLEAN_ACCESSORS(deserialized)
6862 // Indicates that the the shared function info has never been compiled before.
6863 DECL_BOOLEAN_ACCESSORS(never_compiled)
6865 inline FunctionKind kind();
6866 inline void set_kind(FunctionKind kind);
6868 // Indicates whether or not the code in the shared function support
6870 inline bool has_deoptimization_support();
6872 // Enable deoptimization support through recompiled code.
6873 void EnableDeoptimizationSupport(Code* recompiled);
6875 // Disable (further) attempted optimization of all functions sharing this
6876 // shared function info.
6877 void DisableOptimization(BailoutReason reason);
6879 inline BailoutReason disable_optimization_reason();
6881 // Lookup the bailout ID and DCHECK that it exists in the non-optimized
6882 // code, returns whether it asserted (i.e., always true if assertions are
6884 bool VerifyBailoutId(BailoutId id);
6886 // [source code]: Source code for the function.
6887 bool HasSourceCode() const;
6888 Handle<Object> GetSourceCode();
6890 // Number of times the function was optimized.
6891 inline int opt_count();
6892 inline void set_opt_count(int opt_count);
6894 // Number of times the function was deoptimized.
6895 inline void set_deopt_count(int value);
6896 inline int deopt_count();
6897 inline void increment_deopt_count();
6899 // Number of time we tried to re-enable optimization after it
6900 // was disabled due to high number of deoptimizations.
6901 inline void set_opt_reenable_tries(int value);
6902 inline int opt_reenable_tries();
6904 inline void TryReenableOptimization();
6906 // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
6907 inline void set_counters(int value);
6908 inline int counters() const;
6910 // Stores opt_count and bailout_reason as bit-fields.
6911 inline void set_opt_count_and_bailout_reason(int value);
6912 inline int opt_count_and_bailout_reason() const;
6914 void set_disable_optimization_reason(BailoutReason reason) {
6915 set_opt_count_and_bailout_reason(
6916 DisabledOptimizationReasonBits::update(opt_count_and_bailout_reason(),
6920 // Tells whether this function should be subject to debugging.
6921 inline bool IsSubjectToDebugging();
6923 // Check whether or not this function is inlineable.
6924 bool IsInlineable();
6926 // Source size of this function.
6929 // Calculate the instance size.
6930 int CalculateInstanceSize();
6932 // Calculate the number of in-object properties.
6933 int CalculateInObjectProperties();
6935 inline bool is_simple_parameter_list();
6937 // Initialize a SharedFunctionInfo from a parsed function literal.
6938 static void InitFromFunctionLiteral(Handle<SharedFunctionInfo> shared_info,
6939 FunctionLiteral* lit);
6941 // Dispatched behavior.
6942 DECLARE_PRINTER(SharedFunctionInfo)
6943 DECLARE_VERIFIER(SharedFunctionInfo)
6945 void ResetForNewContext(int new_ic_age);
6947 DECLARE_CAST(SharedFunctionInfo)
6950 static const int kDontAdaptArgumentsSentinel = -1;
6952 // Layout description.
6954 static const int kNameOffset = HeapObject::kHeaderSize;
6955 static const int kCodeOffset = kNameOffset + kPointerSize;
6956 static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
6957 static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
6958 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
6959 static const int kInstanceClassNameOffset =
6960 kConstructStubOffset + kPointerSize;
6961 static const int kFunctionDataOffset =
6962 kInstanceClassNameOffset + kPointerSize;
6963 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
6964 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
6965 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
6966 static const int kFeedbackVectorOffset =
6967 kInferredNameOffset + kPointerSize;
6969 static const int kUniqueIdOffset = kFeedbackVectorOffset + kPointerSize;
6970 static const int kLastPointerFieldOffset = kUniqueIdOffset;
6972 // Just to not break the postmortrem support with conditional offsets
6973 static const int kUniqueIdOffset = kFeedbackVectorOffset;
6974 static const int kLastPointerFieldOffset = kFeedbackVectorOffset;
6977 #if V8_HOST_ARCH_32_BIT
6979 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6980 static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
6981 static const int kExpectedNofPropertiesOffset =
6982 kFormalParameterCountOffset + kPointerSize;
6983 static const int kNumLiteralsOffset =
6984 kExpectedNofPropertiesOffset + kPointerSize;
6985 static const int kStartPositionAndTypeOffset =
6986 kNumLiteralsOffset + kPointerSize;
6987 static const int kEndPositionOffset =
6988 kStartPositionAndTypeOffset + kPointerSize;
6989 static const int kFunctionTokenPositionOffset =
6990 kEndPositionOffset + kPointerSize;
6991 static const int kCompilerHintsOffset =
6992 kFunctionTokenPositionOffset + kPointerSize;
6993 static const int kOptCountAndBailoutReasonOffset =
6994 kCompilerHintsOffset + kPointerSize;
6995 static const int kCountersOffset =
6996 kOptCountAndBailoutReasonOffset + kPointerSize;
6997 static const int kAstNodeCountOffset =
6998 kCountersOffset + kPointerSize;
6999 static const int kProfilerTicksOffset =
7000 kAstNodeCountOffset + kPointerSize;
7003 static const int kSize = kProfilerTicksOffset + kPointerSize;
7005 // The only reason to use smi fields instead of int fields
7006 // is to allow iteration without maps decoding during
7007 // garbage collections.
7008 // To avoid wasting space on 64-bit architectures we use
7009 // the following trick: we group integer fields into pairs
7010 // The least significant integer in each pair is shifted left by 1.
7011 // By doing this we guarantee that LSB of each kPointerSize aligned
7012 // word is not set and thus this word cannot be treated as pointer
7013 // to HeapObject during old space traversal.
7014 #if V8_TARGET_LITTLE_ENDIAN
7015 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
7016 static const int kFormalParameterCountOffset =
7017 kLengthOffset + kIntSize;
7019 static const int kExpectedNofPropertiesOffset =
7020 kFormalParameterCountOffset + kIntSize;
7021 static const int kNumLiteralsOffset =
7022 kExpectedNofPropertiesOffset + kIntSize;
7024 static const int kEndPositionOffset =
7025 kNumLiteralsOffset + kIntSize;
7026 static const int kStartPositionAndTypeOffset =
7027 kEndPositionOffset + kIntSize;
7029 static const int kFunctionTokenPositionOffset =
7030 kStartPositionAndTypeOffset + kIntSize;
7031 static const int kCompilerHintsOffset =
7032 kFunctionTokenPositionOffset + kIntSize;
7034 static const int kOptCountAndBailoutReasonOffset =
7035 kCompilerHintsOffset + kIntSize;
7036 static const int kCountersOffset =
7037 kOptCountAndBailoutReasonOffset + kIntSize;
7039 static const int kAstNodeCountOffset =
7040 kCountersOffset + kIntSize;
7041 static const int kProfilerTicksOffset =
7042 kAstNodeCountOffset + kIntSize;
7045 static const int kSize = kProfilerTicksOffset + kIntSize;
7047 #elif V8_TARGET_BIG_ENDIAN
7048 static const int kFormalParameterCountOffset =
7049 kLastPointerFieldOffset + kPointerSize;
7050 static const int kLengthOffset = kFormalParameterCountOffset + kIntSize;
7052 static const int kNumLiteralsOffset = kLengthOffset + kIntSize;
7053 static const int kExpectedNofPropertiesOffset = kNumLiteralsOffset + kIntSize;
7055 static const int kStartPositionAndTypeOffset =
7056 kExpectedNofPropertiesOffset + kIntSize;
7057 static const int kEndPositionOffset = kStartPositionAndTypeOffset + kIntSize;
7059 static const int kCompilerHintsOffset = kEndPositionOffset + kIntSize;
7060 static const int kFunctionTokenPositionOffset =
7061 kCompilerHintsOffset + kIntSize;
7063 static const int kCountersOffset = kFunctionTokenPositionOffset + kIntSize;
7064 static const int kOptCountAndBailoutReasonOffset = kCountersOffset + kIntSize;
7066 static const int kProfilerTicksOffset =
7067 kOptCountAndBailoutReasonOffset + kIntSize;
7068 static const int kAstNodeCountOffset = kProfilerTicksOffset + kIntSize;
7071 static const int kSize = kAstNodeCountOffset + kIntSize;
7074 #error Unknown byte ordering
7075 #endif // Big endian
7079 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
7081 typedef FixedBodyDescriptor<kNameOffset,
7082 kLastPointerFieldOffset + kPointerSize,
7083 kSize> BodyDescriptor;
7085 // Bit positions in start_position_and_type.
7086 // The source code start position is in the 30 most significant bits of
7087 // the start_position_and_type field.
7088 static const int kIsExpressionBit = 0;
7089 static const int kIsTopLevelBit = 1;
7090 static const int kStartPositionShift = 2;
7091 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
7093 // Bit positions in compiler_hints.
7094 enum CompilerHints {
7095 kAllowLazyCompilation,
7096 kAllowLazyCompilationWithoutContext,
7097 kOptimizationDisabled,
7098 kStrictModeFunction,
7099 kStrongModeFunction,
7102 kHasDuplicateParameters,
7107 kNameShouldPrintAsAnonymous,
7114 kIsAccessorFunction,
7115 kIsDefaultConstructor,
7116 kIsSubclassConstructor,
7122 kCompilerHintsCount // Pseudo entry
7124 // Add hints for other modes when they're added.
7125 STATIC_ASSERT(LANGUAGE_END == 3);
7127 class FunctionKindBits : public BitField<FunctionKind, kIsArrow, 8> {};
7129 class DeoptCountBits : public BitField<int, 0, 4> {};
7130 class OptReenableTriesBits : public BitField<int, 4, 18> {};
7131 class ICAgeBits : public BitField<int, 22, 8> {};
7133 class OptCountBits : public BitField<int, 0, 22> {};
7134 class DisabledOptimizationReasonBits : public BitField<int, 22, 8> {};
7137 #if V8_HOST_ARCH_32_BIT
7138 // On 32 bit platforms, compiler hints is a smi.
7139 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
7140 static const int kCompilerHintsSize = kPointerSize;
7142 // On 64 bit platforms, compiler hints is not a smi, see comment above.
7143 static const int kCompilerHintsSmiTagSize = 0;
7144 static const int kCompilerHintsSize = kIntSize;
7147 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
7148 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
7151 // Constants for optimizing codegen for strict mode function and
7153 // Allows to use byte-width instructions.
7154 static const int kStrictModeBitWithinByte =
7155 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
7156 static const int kStrongModeBitWithinByte =
7157 (kStrongModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
7159 static const int kNativeBitWithinByte =
7160 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
7162 #if defined(V8_TARGET_LITTLE_ENDIAN)
7163 static const int kStrictModeByteOffset = kCompilerHintsOffset +
7164 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
7165 static const int kStrongModeByteOffset =
7166 kCompilerHintsOffset +
7167 (kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
7168 static const int kNativeByteOffset = kCompilerHintsOffset +
7169 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
7170 #elif defined(V8_TARGET_BIG_ENDIAN)
7171 static const int kStrictModeByteOffset = kCompilerHintsOffset +
7172 (kCompilerHintsSize - 1) -
7173 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
7174 static const int kStrongModeByteOffset =
7175 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
7176 ((kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
7177 static const int kNativeByteOffset = kCompilerHintsOffset +
7178 (kCompilerHintsSize - 1) -
7179 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
7181 #error Unknown byte ordering
7185 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
7189 // Printing support.
7190 struct SourceCodeOf {
7191 explicit SourceCodeOf(SharedFunctionInfo* v, int max = -1)
7192 : value(v), max_length(max) {}
7193 const SharedFunctionInfo* value;
7198 std::ostream& operator<<(std::ostream& os, const SourceCodeOf& v);
7201 class JSGeneratorObject: public JSObject {
7203 // [function]: The function corresponding to this generator object.
7204 DECL_ACCESSORS(function, JSFunction)
7206 // [context]: The context of the suspended computation.
7207 DECL_ACCESSORS(context, Context)
7209 // [receiver]: The receiver of the suspended computation.
7210 DECL_ACCESSORS(receiver, Object)
7212 // [continuation]: Offset into code of continuation.
7214 // A positive offset indicates a suspended generator. The special
7215 // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
7216 // cannot be resumed.
7217 inline int continuation() const;
7218 inline void set_continuation(int continuation);
7219 inline bool is_closed();
7220 inline bool is_executing();
7221 inline bool is_suspended();
7223 // [operand_stack]: Saved operand stack.
7224 DECL_ACCESSORS(operand_stack, FixedArray)
7226 DECLARE_CAST(JSGeneratorObject)
7228 // Dispatched behavior.
7229 DECLARE_PRINTER(JSGeneratorObject)
7230 DECLARE_VERIFIER(JSGeneratorObject)
7232 // Magic sentinel values for the continuation.
7233 static const int kGeneratorExecuting = -1;
7234 static const int kGeneratorClosed = 0;
7236 // Layout description.
7237 static const int kFunctionOffset = JSObject::kHeaderSize;
7238 static const int kContextOffset = kFunctionOffset + kPointerSize;
7239 static const int kReceiverOffset = kContextOffset + kPointerSize;
7240 static const int kContinuationOffset = kReceiverOffset + kPointerSize;
7241 static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
7242 static const int kSize = kOperandStackOffset + kPointerSize;
7244 // Resume mode, for use by runtime functions.
7245 enum ResumeMode { NEXT, THROW };
7247 // Yielding from a generator returns an object with the following inobject
7248 // properties. See Context::iterator_result_map() for the map.
7249 static const int kResultValuePropertyIndex = 0;
7250 static const int kResultDonePropertyIndex = 1;
7251 static const int kResultPropertyCount = 2;
7253 static const int kResultValuePropertyOffset = JSObject::kHeaderSize;
7254 static const int kResultDonePropertyOffset =
7255 kResultValuePropertyOffset + kPointerSize;
7256 static const int kResultSize = kResultDonePropertyOffset + kPointerSize;
7259 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
7263 // Representation for module instance objects.
7264 class JSModule: public JSObject {
7266 // [context]: the context holding the module's locals, or undefined if none.
7267 DECL_ACCESSORS(context, Object)
7269 // [scope_info]: Scope info.
7270 DECL_ACCESSORS(scope_info, ScopeInfo)
7272 DECLARE_CAST(JSModule)
7274 // Dispatched behavior.
7275 DECLARE_PRINTER(JSModule)
7276 DECLARE_VERIFIER(JSModule)
7278 // Layout description.
7279 static const int kContextOffset = JSObject::kHeaderSize;
7280 static const int kScopeInfoOffset = kContextOffset + kPointerSize;
7281 static const int kSize = kScopeInfoOffset + kPointerSize;
7284 DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
7288 // JSFunction describes JavaScript functions.
7289 class JSFunction: public JSObject {
7291 // [prototype_or_initial_map]:
7292 DECL_ACCESSORS(prototype_or_initial_map, Object)
7294 // [shared]: The information about the function that
7295 // can be shared by instances.
7296 DECL_ACCESSORS(shared, SharedFunctionInfo)
7298 // [context]: The context for this function.
7299 inline Context* context();
7300 inline void set_context(Object* context);
7301 inline JSObject* global_proxy();
7303 // [code]: The generated code object for this function. Executed
7304 // when the function is invoked, e.g. foo() or new foo(). See
7305 // [[Call]] and [[Construct]] description in ECMA-262, section
7307 inline Code* code();
7308 inline void set_code(Code* code);
7309 inline void set_code_no_write_barrier(Code* code);
7310 inline void ReplaceCode(Code* code);
7312 // Tells whether this function is builtin.
7313 inline bool IsBuiltin();
7315 // Tells whether this function inlines the given shared function info.
7316 bool Inlines(SharedFunctionInfo* candidate);
7318 // Tells whether this function should be subject to debugging.
7319 inline bool IsSubjectToDebugging();
7321 // Tells whether or not the function needs arguments adaption.
7322 inline bool NeedsArgumentsAdaption();
7324 // Tells whether or not this function has been optimized.
7325 inline bool IsOptimized();
7327 // Mark this function for lazy recompilation. The function will be
7328 // recompiled the next time it is executed.
7329 void MarkForOptimization();
7330 void AttemptConcurrentOptimization();
7332 // Tells whether or not the function is already marked for lazy
7334 inline bool IsMarkedForOptimization();
7335 inline bool IsMarkedForConcurrentOptimization();
7337 // Tells whether or not the function is on the concurrent recompilation queue.
7338 inline bool IsInOptimizationQueue();
7340 // Inobject slack tracking is the way to reclaim unused inobject space.
7342 // The instance size is initially determined by adding some slack to
7343 // expected_nof_properties (to allow for a few extra properties added
7344 // after the constructor). There is no guarantee that the extra space
7345 // will not be wasted.
7347 // Here is the algorithm to reclaim the unused inobject space:
7348 // - Detect the first constructor call for this JSFunction.
7349 // When it happens enter the "in progress" state: initialize construction
7350 // counter in the initial_map.
7351 // - While the tracking is in progress create objects filled with
7352 // one_pointer_filler_map instead of undefined_value. This way they can be
7353 // resized quickly and safely.
7354 // - Once enough objects have been created compute the 'slack'
7355 // (traverse the map transition tree starting from the
7356 // initial_map and find the lowest value of unused_property_fields).
7357 // - Traverse the transition tree again and decrease the instance size
7358 // of every map. Existing objects will resize automatically (they are
7359 // filled with one_pointer_filler_map). All further allocations will
7360 // use the adjusted instance size.
7361 // - SharedFunctionInfo's expected_nof_properties left unmodified since
7362 // allocations made using different closures could actually create different
7363 // kind of objects (see prototype inheritance pattern).
7365 // Important: inobject slack tracking is not attempted during the snapshot
7368 // True if the initial_map is set and the object constructions countdown
7369 // counter is not zero.
7370 static const int kGenerousAllocationCount =
7371 Map::kSlackTrackingCounterStart - Map::kSlackTrackingCounterEnd + 1;
7372 inline bool IsInobjectSlackTrackingInProgress();
7374 // Starts the tracking.
7375 // Initializes object constructions countdown counter in the initial map.
7376 void StartInobjectSlackTracking();
7378 // Completes the tracking.
7379 void CompleteInobjectSlackTracking();
7381 // [literals_or_bindings]: Fixed array holding either
7382 // the materialized literals or the bindings of a bound function.
7384 // If the function contains object, regexp or array literals, the
7385 // literals array prefix contains the object, regexp, and array
7386 // function to be used when creating these literals. This is
7387 // necessary so that we do not dynamically lookup the object, regexp
7388 // or array functions. Performing a dynamic lookup, we might end up
7389 // using the functions from a new context that we should not have
7392 // On bound functions, the array is a (copy-on-write) fixed-array containing
7393 // the function that was bound, bound this-value and any bound
7394 // arguments. Bound functions never contain literals.
7395 DECL_ACCESSORS(literals_or_bindings, FixedArray)
7397 inline FixedArray* literals();
7398 inline void set_literals(FixedArray* literals);
7400 inline FixedArray* function_bindings();
7401 inline void set_function_bindings(FixedArray* bindings);
7403 // The initial map for an object created by this constructor.
7404 inline Map* initial_map();
7405 static void SetInitialMap(Handle<JSFunction> function, Handle<Map> map,
7406 Handle<Object> prototype);
7407 inline bool has_initial_map();
7408 static void EnsureHasInitialMap(Handle<JSFunction> function);
7410 // Get and set the prototype property on a JSFunction. If the
7411 // function has an initial map the prototype is set on the initial
7412 // map. Otherwise, the prototype is put in the initial map field
7413 // until an initial map is needed.
7414 inline bool has_prototype();
7415 inline bool has_instance_prototype();
7416 inline Object* prototype();
7417 inline Object* instance_prototype();
7418 static void SetPrototype(Handle<JSFunction> function,
7419 Handle<Object> value);
7420 static void SetInstancePrototype(Handle<JSFunction> function,
7421 Handle<Object> value);
7423 // Creates a new closure for the fucntion with the same bindings,
7424 // bound values, and prototype. An equivalent of spec operations
7425 // ``CloneMethod`` and ``CloneBoundFunction``.
7426 static Handle<JSFunction> CloneClosure(Handle<JSFunction> function);
7428 // After prototype is removed, it will not be created when accessed, and
7429 // [[Construct]] from this function will not be allowed.
7430 bool RemovePrototype();
7431 inline bool should_have_prototype();
7433 // Accessor for this function's initial map's [[class]]
7434 // property. This is primarily used by ECMA native functions. This
7435 // method sets the class_name field of this function's initial map
7436 // to a given value. It creates an initial map if this function does
7437 // not have one. Note that this method does not copy the initial map
7438 // if it has one already, but simply replaces it with the new value.
7439 // Instances created afterwards will have a map whose [[class]] is
7440 // set to 'value', but there is no guarantees on instances created
7442 void SetInstanceClassName(String* name);
7444 // Returns if this function has been compiled to native code yet.
7445 inline bool is_compiled();
7447 // Returns `false` if formal parameters include rest parameters, optional
7448 // parameters, or destructuring parameters.
7449 // TODO(caitp): make this a flag set during parsing
7450 inline bool is_simple_parameter_list();
7452 // [next_function_link]: Links functions into various lists, e.g. the list
7453 // of optimized functions hanging off the native_context. The CodeFlusher
7454 // uses this link to chain together flushing candidates. Treated weakly
7455 // by the garbage collector.
7456 DECL_ACCESSORS(next_function_link, Object)
7458 // Prints the name of the function using PrintF.
7459 void PrintName(FILE* out = stdout);
7461 DECLARE_CAST(JSFunction)
7463 // Iterates the objects, including code objects indirectly referenced
7464 // through pointers to the first instruction in the code object.
7465 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
7467 // Dispatched behavior.
7468 DECLARE_PRINTER(JSFunction)
7469 DECLARE_VERIFIER(JSFunction)
7471 // Returns the number of allocated literals.
7472 inline int NumberOfLiterals();
7474 // Used for flags such as --hydrogen-filter.
7475 bool PassesFilter(const char* raw_filter);
7477 // The function's name if it is configured, otherwise shared function info
7479 static Handle<String> GetDebugName(Handle<JSFunction> function);
7481 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
7482 // kSize) is weak and has special handling during garbage collection.
7483 static const int kCodeEntryOffset = JSObject::kHeaderSize;
7484 static const int kPrototypeOrInitialMapOffset =
7485 kCodeEntryOffset + kPointerSize;
7486 static const int kSharedFunctionInfoOffset =
7487 kPrototypeOrInitialMapOffset + kPointerSize;
7488 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
7489 static const int kLiteralsOffset = kContextOffset + kPointerSize;
7490 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
7491 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
7492 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
7494 // Layout of the bound-function binding array.
7495 static const int kBoundFunctionIndex = 0;
7496 static const int kBoundThisIndex = 1;
7497 static const int kBoundArgumentsStartIndex = 2;
7500 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7504 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7505 // and the prototype is hidden. JSGlobalProxy always delegates
7506 // property accesses to its prototype if the prototype is not null.
7508 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7510 // Accessing a JSGlobalProxy requires security check.
7512 class JSGlobalProxy : public JSObject {
7514 // [native_context]: the owner native context of this global proxy object.
7515 // It is null value if this object is not used by any context.
7516 DECL_ACCESSORS(native_context, Object)
7518 // [hash]: The hash code property (undefined if not initialized yet).
7519 DECL_ACCESSORS(hash, Object)
7521 DECLARE_CAST(JSGlobalProxy)
7523 inline bool IsDetachedFrom(GlobalObject* global) const;
7525 // Dispatched behavior.
7526 DECLARE_PRINTER(JSGlobalProxy)
7527 DECLARE_VERIFIER(JSGlobalProxy)
7529 // Layout description.
7530 static const int kNativeContextOffset = JSObject::kHeaderSize;
7531 static const int kHashOffset = kNativeContextOffset + kPointerSize;
7532 static const int kSize = kHashOffset + kPointerSize;
7535 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7539 // Common super class for JavaScript global objects and the special
7540 // builtins global objects.
7541 class GlobalObject: public JSObject {
7543 // [builtins]: the object holding the runtime routines written in JS.
7544 DECL_ACCESSORS(builtins, JSBuiltinsObject)
7546 // [native context]: the natives corresponding to this global object.
7547 DECL_ACCESSORS(native_context, Context)
7549 // [global proxy]: the global proxy object of the context
7550 DECL_ACCESSORS(global_proxy, JSObject)
7552 DECLARE_CAST(GlobalObject)
7554 static void InvalidatePropertyCell(Handle<GlobalObject> object,
7556 // Ensure that the global object has a cell for the given property name.
7557 static Handle<PropertyCell> EnsurePropertyCell(Handle<GlobalObject> global,
7560 // Layout description.
7561 static const int kBuiltinsOffset = JSObject::kHeaderSize;
7562 static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7563 static const int kGlobalProxyOffset = kNativeContextOffset + kPointerSize;
7564 static const int kHeaderSize = kGlobalProxyOffset + kPointerSize;
7567 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7571 // JavaScript global object.
7572 class JSGlobalObject: public GlobalObject {
7574 DECLARE_CAST(JSGlobalObject)
7576 inline bool IsDetached();
7578 // Dispatched behavior.
7579 DECLARE_PRINTER(JSGlobalObject)
7580 DECLARE_VERIFIER(JSGlobalObject)
7582 // Layout description.
7583 static const int kSize = GlobalObject::kHeaderSize;
7586 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7590 // Builtins global object which holds the runtime routines written in
7592 class JSBuiltinsObject: public GlobalObject {
7594 // Accessors for the runtime routines written in JavaScript.
7595 inline Object* javascript_builtin(Builtins::JavaScript id);
7596 inline void set_javascript_builtin(Builtins::JavaScript id, Object* value);
7598 DECLARE_CAST(JSBuiltinsObject)
7600 // Dispatched behavior.
7601 DECLARE_PRINTER(JSBuiltinsObject)
7602 DECLARE_VERIFIER(JSBuiltinsObject)
7604 // Layout description. The size of the builtins object includes
7605 // room for two pointers per runtime routine written in javascript
7606 // (function and code object).
7607 static const int kJSBuiltinsCount = Builtins::id_count;
7608 static const int kJSBuiltinsOffset = GlobalObject::kHeaderSize;
7609 static const int kSize =
7610 GlobalObject::kHeaderSize + (kJSBuiltinsCount * kPointerSize);
7612 static int OffsetOfFunctionWithId(Builtins::JavaScript id) {
7613 return kJSBuiltinsOffset + id * kPointerSize;
7617 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7621 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
7622 class JSValue: public JSObject {
7624 // [value]: the object being wrapped.
7625 DECL_ACCESSORS(value, Object)
7627 DECLARE_CAST(JSValue)
7629 // Dispatched behavior.
7630 DECLARE_PRINTER(JSValue)
7631 DECLARE_VERIFIER(JSValue)
7633 // Layout description.
7634 static const int kValueOffset = JSObject::kHeaderSize;
7635 static const int kSize = kValueOffset + kPointerSize;
7638 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
7644 // Representation for JS date objects.
7645 class JSDate: public JSObject {
7647 // If one component is NaN, all of them are, indicating a NaN time value.
7648 // [value]: the time value.
7649 DECL_ACCESSORS(value, Object)
7650 // [year]: caches year. Either undefined, smi, or NaN.
7651 DECL_ACCESSORS(year, Object)
7652 // [month]: caches month. Either undefined, smi, or NaN.
7653 DECL_ACCESSORS(month, Object)
7654 // [day]: caches day. Either undefined, smi, or NaN.
7655 DECL_ACCESSORS(day, Object)
7656 // [weekday]: caches day of week. Either undefined, smi, or NaN.
7657 DECL_ACCESSORS(weekday, Object)
7658 // [hour]: caches hours. Either undefined, smi, or NaN.
7659 DECL_ACCESSORS(hour, Object)
7660 // [min]: caches minutes. Either undefined, smi, or NaN.
7661 DECL_ACCESSORS(min, Object)
7662 // [sec]: caches seconds. Either undefined, smi, or NaN.
7663 DECL_ACCESSORS(sec, Object)
7664 // [cache stamp]: sample of the date cache stamp at the
7665 // moment when chached fields were cached.
7666 DECL_ACCESSORS(cache_stamp, Object)
7668 DECLARE_CAST(JSDate)
7670 // Returns the date field with the specified index.
7671 // See FieldIndex for the list of date fields.
7672 static Object* GetField(Object* date, Smi* index);
7674 void SetValue(Object* value, bool is_value_nan);
7677 // Dispatched behavior.
7678 DECLARE_PRINTER(JSDate)
7679 DECLARE_VERIFIER(JSDate)
7681 // The order is important. It must be kept in sync with date macros
7692 kFirstUncachedField,
7693 kMillisecond = kFirstUncachedField,
7697 kYearUTC = kFirstUTCField,
7710 // Layout description.
7711 static const int kValueOffset = JSObject::kHeaderSize;
7712 static const int kYearOffset = kValueOffset + kPointerSize;
7713 static const int kMonthOffset = kYearOffset + kPointerSize;
7714 static const int kDayOffset = kMonthOffset + kPointerSize;
7715 static const int kWeekdayOffset = kDayOffset + kPointerSize;
7716 static const int kHourOffset = kWeekdayOffset + kPointerSize;
7717 static const int kMinOffset = kHourOffset + kPointerSize;
7718 static const int kSecOffset = kMinOffset + kPointerSize;
7719 static const int kCacheStampOffset = kSecOffset + kPointerSize;
7720 static const int kSize = kCacheStampOffset + kPointerSize;
7723 inline Object* DoGetField(FieldIndex index);
7725 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
7727 // Computes and caches the cacheable fields of the date.
7728 inline void SetCachedFields(int64_t local_time_ms, DateCache* date_cache);
7731 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
7735 // Representation of message objects used for error reporting through
7736 // the API. The messages are formatted in JavaScript so this object is
7737 // a real JavaScript object. The information used for formatting the
7738 // error messages are not directly accessible from JavaScript to
7739 // prevent leaking information to user code called during error
7741 class JSMessageObject: public JSObject {
7743 // [type]: the type of error message.
7744 inline int type() const;
7745 inline void set_type(int value);
7747 // [arguments]: the arguments for formatting the error message.
7748 DECL_ACCESSORS(argument, Object)
7750 // [script]: the script from which the error message originated.
7751 DECL_ACCESSORS(script, Object)
7753 // [stack_frames]: an array of stack frames for this error object.
7754 DECL_ACCESSORS(stack_frames, Object)
7756 // [start_position]: the start position in the script for the error message.
7757 inline int start_position() const;
7758 inline void set_start_position(int value);
7760 // [end_position]: the end position in the script for the error message.
7761 inline int end_position() const;
7762 inline void set_end_position(int value);
7764 DECLARE_CAST(JSMessageObject)
7766 // Dispatched behavior.
7767 DECLARE_PRINTER(JSMessageObject)
7768 DECLARE_VERIFIER(JSMessageObject)
7770 // Layout description.
7771 static const int kTypeOffset = JSObject::kHeaderSize;
7772 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
7773 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
7774 static const int kStackFramesOffset = kScriptOffset + kPointerSize;
7775 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
7776 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
7777 static const int kSize = kEndPositionOffset + kPointerSize;
7779 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
7780 kStackFramesOffset + kPointerSize,
7781 kSize> BodyDescriptor;
7785 // Regular expressions
7786 // The regular expression holds a single reference to a FixedArray in
7787 // the kDataOffset field.
7788 // The FixedArray contains the following data:
7789 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
7790 // - reference to the original source string
7791 // - reference to the original flag string
7792 // If it is an atom regexp
7793 // - a reference to a literal string to search for
7794 // If it is an irregexp regexp:
7795 // - a reference to code for Latin1 inputs (bytecode or compiled), or a smi
7796 // used for tracking the last usage (used for code flushing).
7797 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
7798 // used for tracking the last usage (used for code flushing)..
7799 // - max number of registers used by irregexp implementations.
7800 // - number of capture registers (output values) of the regexp.
7801 class JSRegExp: public JSObject {
7804 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
7805 // ATOM: A simple string to match against using an indexOf operation.
7806 // IRREGEXP: Compiled with Irregexp.
7807 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
7808 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
7815 UNICODE_ESCAPES = 16
7820 explicit Flags(uint32_t value) : value_(value) { }
7821 bool is_global() { return (value_ & GLOBAL) != 0; }
7822 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
7823 bool is_multiline() { return (value_ & MULTILINE) != 0; }
7824 bool is_sticky() { return (value_ & STICKY) != 0; }
7825 bool is_unicode() { return (value_ & UNICODE_ESCAPES) != 0; }
7826 uint32_t value() { return value_; }
7831 DECL_ACCESSORS(data, Object)
7833 inline Type TypeTag();
7834 inline int CaptureCount();
7835 inline Flags GetFlags();
7836 inline String* Pattern();
7837 inline Object* DataAt(int index);
7838 // Set implementation data after the object has been prepared.
7839 inline void SetDataAt(int index, Object* value);
7841 static int code_index(bool is_latin1) {
7843 return kIrregexpLatin1CodeIndex;
7845 return kIrregexpUC16CodeIndex;
7849 static int saved_code_index(bool is_latin1) {
7851 return kIrregexpLatin1CodeSavedIndex;
7853 return kIrregexpUC16CodeSavedIndex;
7857 DECLARE_CAST(JSRegExp)
7859 // Dispatched behavior.
7860 DECLARE_VERIFIER(JSRegExp)
7862 static const int kDataOffset = JSObject::kHeaderSize;
7863 static const int kSize = kDataOffset + kPointerSize;
7865 // Indices in the data array.
7866 static const int kTagIndex = 0;
7867 static const int kSourceIndex = kTagIndex + 1;
7868 static const int kFlagsIndex = kSourceIndex + 1;
7869 static const int kDataIndex = kFlagsIndex + 1;
7870 // The data fields are used in different ways depending on the
7871 // value of the tag.
7872 // Atom regexps (literal strings).
7873 static const int kAtomPatternIndex = kDataIndex;
7875 static const int kAtomDataSize = kAtomPatternIndex + 1;
7877 // Irregexp compiled code or bytecode for Latin1. If compilation
7878 // fails, this fields hold an exception object that should be
7879 // thrown if the regexp is used again.
7880 static const int kIrregexpLatin1CodeIndex = kDataIndex;
7881 // Irregexp compiled code or bytecode for UC16. If compilation
7882 // fails, this fields hold an exception object that should be
7883 // thrown if the regexp is used again.
7884 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
7886 // Saved instance of Irregexp compiled code or bytecode for Latin1 that
7887 // is a potential candidate for flushing.
7888 static const int kIrregexpLatin1CodeSavedIndex = kDataIndex + 2;
7889 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
7890 // a potential candidate for flushing.
7891 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
7893 // Maximal number of registers used by either Latin1 or UC16.
7894 // Only used to check that there is enough stack space
7895 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
7896 // Number of captures in the compiled regexp.
7897 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
7899 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
7901 // Offsets directly into the data fixed array.
7902 static const int kDataTagOffset =
7903 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
7904 static const int kDataOneByteCodeOffset =
7905 FixedArray::kHeaderSize + kIrregexpLatin1CodeIndex * kPointerSize;
7906 static const int kDataUC16CodeOffset =
7907 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
7908 static const int kIrregexpCaptureCountOffset =
7909 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
7911 // In-object fields.
7912 static const int kSourceFieldIndex = 0;
7913 static const int kGlobalFieldIndex = 1;
7914 static const int kIgnoreCaseFieldIndex = 2;
7915 static const int kMultilineFieldIndex = 3;
7916 static const int kLastIndexFieldIndex = 4;
7917 static const int kInObjectFieldCount = 5;
7919 // The uninitialized value for a regexp code object.
7920 static const int kUninitializedValue = -1;
7922 // The compilation error value for the regexp code object. The real error
7923 // object is in the saved code field.
7924 static const int kCompilationErrorValue = -2;
7926 // When we store the sweep generation at which we moved the code from the
7927 // code index to the saved code index we mask it of to be in the [0:255]
7929 static const int kCodeAgeMask = 0xff;
7933 class CompilationCacheShape : public BaseShape<HashTableKey*> {
7935 static inline bool IsMatch(HashTableKey* key, Object* value) {
7936 return key->IsMatch(value);
7939 static inline uint32_t Hash(HashTableKey* key) {
7943 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7944 return key->HashForObject(object);
7947 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7949 static const int kPrefixSize = 0;
7950 static const int kEntrySize = 2;
7954 // This cache is used in two different variants. For regexp caching, it simply
7955 // maps identifying info of the regexp to the cached regexp object. Scripts and
7956 // eval code only gets cached after a second probe for the code object. To do
7957 // so, on first "put" only a hash identifying the source is entered into the
7958 // cache, mapping it to a lifetime count of the hash. On each call to Age all
7959 // such lifetimes get reduced, and removed once they reach zero. If a second put
7960 // is called while such a hash is live in the cache, the hash gets replaced by
7961 // an actual cache entry. Age also removes stale live entries from the cache.
7962 // Such entries are identified by SharedFunctionInfos pointing to either the
7963 // recompilation stub, or to "old" code. This avoids memory leaks due to
7964 // premature caching of scripts and eval strings that are never needed later.
7965 class CompilationCacheTable: public HashTable<CompilationCacheTable,
7966 CompilationCacheShape,
7969 // Find cached value for a string key, otherwise return null.
7970 Handle<Object> Lookup(
7971 Handle<String> src, Handle<Context> context, LanguageMode language_mode);
7972 Handle<Object> LookupEval(
7973 Handle<String> src, Handle<SharedFunctionInfo> shared,
7974 LanguageMode language_mode, int scope_position);
7975 Handle<Object> LookupRegExp(Handle<String> source, JSRegExp::Flags flags);
7976 static Handle<CompilationCacheTable> Put(
7977 Handle<CompilationCacheTable> cache, Handle<String> src,
7978 Handle<Context> context, LanguageMode language_mode,
7979 Handle<Object> value);
7980 static Handle<CompilationCacheTable> PutEval(
7981 Handle<CompilationCacheTable> cache, Handle<String> src,
7982 Handle<SharedFunctionInfo> context, Handle<SharedFunctionInfo> value,
7983 int scope_position);
7984 static Handle<CompilationCacheTable> PutRegExp(
7985 Handle<CompilationCacheTable> cache, Handle<String> src,
7986 JSRegExp::Flags flags, Handle<FixedArray> value);
7987 void Remove(Object* value);
7989 static const int kHashGenerations = 10;
7991 DECLARE_CAST(CompilationCacheTable)
7994 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
7998 class CodeCache: public Struct {
8000 DECL_ACCESSORS(default_cache, FixedArray)
8001 DECL_ACCESSORS(normal_type_cache, Object)
8003 // Add the code object to the cache.
8005 Handle<CodeCache> cache, Handle<Name> name, Handle<Code> code);
8007 // Lookup code object in the cache. Returns code object if found and undefined
8009 Object* Lookup(Name* name, Code::Flags flags);
8011 // Get the internal index of a code object in the cache. Returns -1 if the
8012 // code object is not in that cache. This index can be used to later call
8013 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
8015 int GetIndex(Object* name, Code* code);
8017 // Remove an object from the cache with the provided internal index.
8018 void RemoveByIndex(Object* name, Code* code, int index);
8020 DECLARE_CAST(CodeCache)
8022 // Dispatched behavior.
8023 DECLARE_PRINTER(CodeCache)
8024 DECLARE_VERIFIER(CodeCache)
8026 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
8027 static const int kNormalTypeCacheOffset =
8028 kDefaultCacheOffset + kPointerSize;
8029 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
8032 static void UpdateDefaultCache(
8033 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
8034 static void UpdateNormalTypeCache(
8035 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
8036 Object* LookupDefaultCache(Name* name, Code::Flags flags);
8037 Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
8039 // Code cache layout of the default cache. Elements are alternating name and
8040 // code objects for non normal load/store/call IC's.
8041 static const int kCodeCacheEntrySize = 2;
8042 static const int kCodeCacheEntryNameOffset = 0;
8043 static const int kCodeCacheEntryCodeOffset = 1;
8045 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
8049 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
8051 static inline bool IsMatch(HashTableKey* key, Object* value) {
8052 return key->IsMatch(value);
8055 static inline uint32_t Hash(HashTableKey* key) {
8059 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
8060 return key->HashForObject(object);
8063 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
8065 static const int kPrefixSize = 0;
8066 static const int kEntrySize = 2;
8070 class CodeCacheHashTable: public HashTable<CodeCacheHashTable,
8071 CodeCacheHashTableShape,
8074 Object* Lookup(Name* name, Code::Flags flags);
8075 static Handle<CodeCacheHashTable> Put(
8076 Handle<CodeCacheHashTable> table,
8080 int GetIndex(Name* name, Code::Flags flags);
8081 void RemoveByIndex(int index);
8083 DECLARE_CAST(CodeCacheHashTable)
8085 // Initial size of the fixed array backing the hash table.
8086 static const int kInitialSize = 64;
8089 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
8093 class PolymorphicCodeCache: public Struct {
8095 DECL_ACCESSORS(cache, Object)
8097 static void Update(Handle<PolymorphicCodeCache> cache,
8098 MapHandleList* maps,
8103 // Returns an undefined value if the entry is not found.
8104 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
8106 DECLARE_CAST(PolymorphicCodeCache)
8108 // Dispatched behavior.
8109 DECLARE_PRINTER(PolymorphicCodeCache)
8110 DECLARE_VERIFIER(PolymorphicCodeCache)
8112 static const int kCacheOffset = HeapObject::kHeaderSize;
8113 static const int kSize = kCacheOffset + kPointerSize;
8116 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
8120 class PolymorphicCodeCacheHashTable
8121 : public HashTable<PolymorphicCodeCacheHashTable,
8122 CodeCacheHashTableShape,
8125 Object* Lookup(MapHandleList* maps, int code_kind);
8127 static Handle<PolymorphicCodeCacheHashTable> Put(
8128 Handle<PolymorphicCodeCacheHashTable> hash_table,
8129 MapHandleList* maps,
8133 DECLARE_CAST(PolymorphicCodeCacheHashTable)
8135 static const int kInitialSize = 64;
8137 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
8141 class TypeFeedbackInfo: public Struct {
8143 inline int ic_total_count();
8144 inline void set_ic_total_count(int count);
8146 inline int ic_with_type_info_count();
8147 inline void change_ic_with_type_info_count(int delta);
8149 inline int ic_generic_count();
8150 inline void change_ic_generic_count(int delta);
8152 inline void initialize_storage();
8154 inline void change_own_type_change_checksum();
8155 inline int own_type_change_checksum();
8157 inline void set_inlined_type_change_checksum(int checksum);
8158 inline bool matches_inlined_type_change_checksum(int checksum);
8160 DECLARE_CAST(TypeFeedbackInfo)
8162 // Dispatched behavior.
8163 DECLARE_PRINTER(TypeFeedbackInfo)
8164 DECLARE_VERIFIER(TypeFeedbackInfo)
8166 static const int kStorage1Offset = HeapObject::kHeaderSize;
8167 static const int kStorage2Offset = kStorage1Offset + kPointerSize;
8168 static const int kStorage3Offset = kStorage2Offset + kPointerSize;
8169 static const int kSize = kStorage3Offset + kPointerSize;
8172 static const int kTypeChangeChecksumBits = 7;
8174 class ICTotalCountField: public BitField<int, 0,
8175 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
8176 class OwnTypeChangeChecksum: public BitField<int,
8177 kSmiValueSize - kTypeChangeChecksumBits,
8178 kTypeChangeChecksumBits> {}; // NOLINT
8179 class ICsWithTypeInfoCountField: public BitField<int, 0,
8180 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
8181 class InlinedTypeChangeChecksum: public BitField<int,
8182 kSmiValueSize - kTypeChangeChecksumBits,
8183 kTypeChangeChecksumBits> {}; // NOLINT
8185 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
8189 enum AllocationSiteMode {
8190 DONT_TRACK_ALLOCATION_SITE,
8191 TRACK_ALLOCATION_SITE,
8192 LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
8196 class AllocationSite: public Struct {
8198 static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
8199 static const double kPretenureRatio;
8200 static const int kPretenureMinimumCreated = 100;
8202 // Values for pretenure decision field.
8203 enum PretenureDecision {
8209 kLastPretenureDecisionValue = kZombie
8212 const char* PretenureDecisionName(PretenureDecision decision);
8214 DECL_ACCESSORS(transition_info, Object)
8215 // nested_site threads a list of sites that represent nested literals
8216 // walked in a particular order. So [[1, 2], 1, 2] will have one
8217 // nested_site, but [[1, 2], 3, [4]] will have a list of two.
8218 DECL_ACCESSORS(nested_site, Object)
8219 DECL_ACCESSORS(pretenure_data, Smi)
8220 DECL_ACCESSORS(pretenure_create_count, Smi)
8221 DECL_ACCESSORS(dependent_code, DependentCode)
8222 DECL_ACCESSORS(weak_next, Object)
8224 inline void Initialize();
8226 // This method is expensive, it should only be called for reporting.
8227 bool IsNestedSite();
8229 // transition_info bitfields, for constructed array transition info.
8230 class ElementsKindBits: public BitField<ElementsKind, 0, 15> {};
8231 class UnusedBits: public BitField<int, 15, 14> {};
8232 class DoNotInlineBit: public BitField<bool, 29, 1> {};
8234 // Bitfields for pretenure_data
8235 class MementoFoundCountBits: public BitField<int, 0, 26> {};
8236 class PretenureDecisionBits: public BitField<PretenureDecision, 26, 3> {};
8237 class DeoptDependentCodeBit: public BitField<bool, 29, 1> {};
8238 STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
8240 // Increments the mementos found counter and returns true when the first
8241 // memento was found for a given allocation site.
8242 inline bool IncrementMementoFoundCount();
8244 inline void IncrementMementoCreateCount();
8246 PretenureFlag GetPretenureMode();
8248 void ResetPretenureDecision();
8250 PretenureDecision pretenure_decision() {
8251 int value = pretenure_data()->value();
8252 return PretenureDecisionBits::decode(value);
8255 void set_pretenure_decision(PretenureDecision decision) {
8256 int value = pretenure_data()->value();
8258 Smi::FromInt(PretenureDecisionBits::update(value, decision)),
8259 SKIP_WRITE_BARRIER);
8262 bool deopt_dependent_code() {
8263 int value = pretenure_data()->value();
8264 return DeoptDependentCodeBit::decode(value);
8267 void set_deopt_dependent_code(bool deopt) {
8268 int value = pretenure_data()->value();
8270 Smi::FromInt(DeoptDependentCodeBit::update(value, deopt)),
8271 SKIP_WRITE_BARRIER);
8274 int memento_found_count() {
8275 int value = pretenure_data()->value();
8276 return MementoFoundCountBits::decode(value);
8279 inline void set_memento_found_count(int count);
8281 int memento_create_count() {
8282 return pretenure_create_count()->value();
8285 void set_memento_create_count(int count) {
8286 set_pretenure_create_count(Smi::FromInt(count), SKIP_WRITE_BARRIER);
8289 // The pretenuring decision is made during gc, and the zombie state allows
8290 // us to recognize when an allocation site is just being kept alive because
8291 // a later traversal of new space may discover AllocationMementos that point
8292 // to this AllocationSite.
8294 return pretenure_decision() == kZombie;
8297 bool IsMaybeTenure() {
8298 return pretenure_decision() == kMaybeTenure;
8301 inline void MarkZombie();
8303 inline bool MakePretenureDecision(PretenureDecision current_decision,
8305 bool maximum_size_scavenge);
8307 inline bool DigestPretenuringFeedback(bool maximum_size_scavenge);
8309 ElementsKind GetElementsKind() {
8310 DCHECK(!SitePointsToLiteral());
8311 int value = Smi::cast(transition_info())->value();
8312 return ElementsKindBits::decode(value);
8315 void SetElementsKind(ElementsKind kind) {
8316 int value = Smi::cast(transition_info())->value();
8317 set_transition_info(Smi::FromInt(ElementsKindBits::update(value, kind)),
8318 SKIP_WRITE_BARRIER);
8321 bool CanInlineCall() {
8322 int value = Smi::cast(transition_info())->value();
8323 return DoNotInlineBit::decode(value) == 0;
8326 void SetDoNotInlineCall() {
8327 int value = Smi::cast(transition_info())->value();
8328 set_transition_info(Smi::FromInt(DoNotInlineBit::update(value, true)),
8329 SKIP_WRITE_BARRIER);
8332 bool SitePointsToLiteral() {
8333 // If transition_info is a smi, then it represents an ElementsKind
8334 // for a constructed array. Otherwise, it must be a boilerplate
8335 // for an object or array literal.
8336 return transition_info()->IsJSArray() || transition_info()->IsJSObject();
8339 static void DigestTransitionFeedback(Handle<AllocationSite> site,
8340 ElementsKind to_kind);
8342 DECLARE_PRINTER(AllocationSite)
8343 DECLARE_VERIFIER(AllocationSite)
8345 DECLARE_CAST(AllocationSite)
8346 static inline AllocationSiteMode GetMode(
8347 ElementsKind boilerplate_elements_kind);
8348 static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
8349 static inline bool CanTrack(InstanceType type);
8351 static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
8352 static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
8353 static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
8354 static const int kPretenureCreateCountOffset =
8355 kPretenureDataOffset + kPointerSize;
8356 static const int kDependentCodeOffset =
8357 kPretenureCreateCountOffset + kPointerSize;
8358 static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
8359 static const int kSize = kWeakNextOffset + kPointerSize;
8361 // During mark compact we need to take special care for the dependent code
8363 static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
8364 static const int kPointerFieldsEndOffset = kWeakNextOffset;
8366 // For other visitors, use the fixed body descriptor below.
8367 typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
8368 kDependentCodeOffset + kPointerSize,
8369 kSize> BodyDescriptor;
8372 bool PretenuringDecisionMade() {
8373 return pretenure_decision() != kUndecided;
8376 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
8380 class AllocationMemento: public Struct {
8382 static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
8383 static const int kSize = kAllocationSiteOffset + kPointerSize;
8385 DECL_ACCESSORS(allocation_site, Object)
8388 return allocation_site()->IsAllocationSite() &&
8389 !AllocationSite::cast(allocation_site())->IsZombie();
8391 AllocationSite* GetAllocationSite() {
8393 return AllocationSite::cast(allocation_site());
8396 DECLARE_PRINTER(AllocationMemento)
8397 DECLARE_VERIFIER(AllocationMemento)
8399 DECLARE_CAST(AllocationMemento)
8402 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
8406 // Representation of a slow alias as part of a sloppy arguments objects.
8407 // For fast aliases (if HasSloppyArgumentsElements()):
8408 // - the parameter map contains an index into the context
8409 // - all attributes of the element have default values
8410 // For slow aliases (if HasDictionaryArgumentsElements()):
8411 // - the parameter map contains no fast alias mapping (i.e. the hole)
8412 // - this struct (in the slow backing store) contains an index into the context
8413 // - all attributes are available as part if the property details
8414 class AliasedArgumentsEntry: public Struct {
8416 inline int aliased_context_slot() const;
8417 inline void set_aliased_context_slot(int count);
8419 DECLARE_CAST(AliasedArgumentsEntry)
8421 // Dispatched behavior.
8422 DECLARE_PRINTER(AliasedArgumentsEntry)
8423 DECLARE_VERIFIER(AliasedArgumentsEntry)
8425 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
8426 static const int kSize = kAliasedContextSlot + kPointerSize;
8429 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
8433 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
8434 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
8437 class StringHasher {
8439 explicit inline StringHasher(int length, uint32_t seed);
8441 template <typename schar>
8442 static inline uint32_t HashSequentialString(const schar* chars,
8446 // Reads all the data, even for long strings and computes the utf16 length.
8447 static uint32_t ComputeUtf8Hash(Vector<const char> chars,
8449 int* utf16_length_out);
8451 // Calculated hash value for a string consisting of 1 to
8452 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
8453 // value is represented decimal value.
8454 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
8456 // No string is allowed to have a hash of zero. That value is reserved
8457 // for internal properties. If the hash calculation yields zero then we
8459 static const int kZeroHash = 27;
8461 // Reusable parts of the hashing algorithm.
8462 INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
8463 INLINE(static uint32_t GetHashCore(uint32_t running_hash));
8464 INLINE(static uint32_t ComputeRunningHash(uint32_t running_hash,
8465 const uc16* chars, int length));
8466 INLINE(static uint32_t ComputeRunningHashOneByte(uint32_t running_hash,
8471 // Returns the value to store in the hash field of a string with
8472 // the given length and contents.
8473 uint32_t GetHashField();
8474 // Returns true if the hash of this string can be computed without
8475 // looking at the contents.
8476 inline bool has_trivial_hash();
8477 // Adds a block of characters to the hash.
8478 template<typename Char>
8479 inline void AddCharacters(const Char* chars, int len);
8482 // Add a character to the hash.
8483 inline void AddCharacter(uint16_t c);
8484 // Update index. Returns true if string is still an index.
8485 inline bool UpdateIndex(uint16_t c);
8488 uint32_t raw_running_hash_;
8489 uint32_t array_index_;
8490 bool is_array_index_;
8491 bool is_first_char_;
8492 DISALLOW_COPY_AND_ASSIGN(StringHasher);
8496 class IteratingStringHasher : public StringHasher {
8498 static inline uint32_t Hash(String* string, uint32_t seed);
8499 inline void VisitOneByteString(const uint8_t* chars, int length);
8500 inline void VisitTwoByteString(const uint16_t* chars, int length);
8503 inline IteratingStringHasher(int len, uint32_t seed)
8504 : StringHasher(len, seed) {}
8505 void VisitConsString(ConsString* cons_string);
8506 DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher);
8510 // The characteristics of a string are stored in its map. Retrieving these
8511 // few bits of information is moderately expensive, involving two memory
8512 // loads where the second is dependent on the first. To improve efficiency
8513 // the shape of the string is given its own class so that it can be retrieved
8514 // once and used for several string operations. A StringShape is small enough
8515 // to be passed by value and is immutable, but be aware that flattening a
8516 // string can potentially alter its shape. Also be aware that a GC caused by
8517 // something else can alter the shape of a string due to ConsString
8518 // shortcutting. Keeping these restrictions in mind has proven to be error-
8519 // prone and so we no longer put StringShapes in variables unless there is a
8520 // concrete performance benefit at that particular point in the code.
8521 class StringShape BASE_EMBEDDED {
8523 inline explicit StringShape(const String* s);
8524 inline explicit StringShape(Map* s);
8525 inline explicit StringShape(InstanceType t);
8526 inline bool IsSequential();
8527 inline bool IsExternal();
8528 inline bool IsCons();
8529 inline bool IsSliced();
8530 inline bool IsIndirect();
8531 inline bool IsExternalOneByte();
8532 inline bool IsExternalTwoByte();
8533 inline bool IsSequentialOneByte();
8534 inline bool IsSequentialTwoByte();
8535 inline bool IsInternalized();
8536 inline StringRepresentationTag representation_tag();
8537 inline uint32_t encoding_tag();
8538 inline uint32_t full_representation_tag();
8539 inline uint32_t size_tag();
8541 inline uint32_t type() { return type_; }
8542 inline void invalidate() { valid_ = false; }
8543 inline bool valid() { return valid_; }
8545 inline void invalidate() { }
8551 inline void set_valid() { valid_ = true; }
8554 inline void set_valid() { }
8559 // The Name abstract class captures anything that can be used as a property
8560 // name, i.e., strings and symbols. All names store a hash value.
8561 class Name: public HeapObject {
8563 // Get and set the hash field of the name.
8564 inline uint32_t hash_field();
8565 inline void set_hash_field(uint32_t value);
8567 // Tells whether the hash code has been computed.
8568 inline bool HasHashCode();
8570 // Returns a hash value used for the property table
8571 inline uint32_t Hash();
8573 // Equality operations.
8574 inline bool Equals(Name* other);
8575 inline static bool Equals(Handle<Name> one, Handle<Name> two);
8578 inline bool AsArrayIndex(uint32_t* index);
8580 // If the name is private, it can only name own properties.
8581 inline bool IsPrivate();
8583 // If the name is a non-flat string, this method returns a flat version of the
8584 // string. Otherwise it'll just return the input.
8585 static inline Handle<Name> Flatten(Handle<Name> name,
8586 PretenureFlag pretenure = NOT_TENURED);
8590 DECLARE_PRINTER(Name)
8592 void NameShortPrint();
8593 int NameShortPrint(Vector<char> str);
8596 // Layout description.
8597 static const int kHashFieldSlot = HeapObject::kHeaderSize;
8598 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
8599 static const int kHashFieldOffset = kHashFieldSlot;
8601 static const int kHashFieldOffset = kHashFieldSlot + kIntSize;
8603 static const int kSize = kHashFieldSlot + kPointerSize;
8605 // Mask constant for checking if a name has a computed hash code
8606 // and if it is a string that is an array index. The least significant bit
8607 // indicates whether a hash code has been computed. If the hash code has
8608 // been computed the 2nd bit tells whether the string can be used as an
8610 static const int kHashNotComputedMask = 1;
8611 static const int kIsNotArrayIndexMask = 1 << 1;
8612 static const int kNofHashBitFields = 2;
8614 // Shift constant retrieving hash code from hash field.
8615 static const int kHashShift = kNofHashBitFields;
8617 // Only these bits are relevant in the hash, since the top two are shifted
8619 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8621 // Array index strings this short can keep their index in the hash field.
8622 static const int kMaxCachedArrayIndexLength = 7;
8624 // For strings which are array indexes the hash value has the string length
8625 // mixed into the hash, mainly to avoid a hash value of zero which would be
8626 // the case for the string '0'. 24 bits are used for the array index value.
8627 static const int kArrayIndexValueBits = 24;
8628 static const int kArrayIndexLengthBits =
8629 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8631 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8633 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8634 kArrayIndexValueBits> {}; // NOLINT
8635 class ArrayIndexLengthBits : public BitField<unsigned int,
8636 kNofHashBitFields + kArrayIndexValueBits,
8637 kArrayIndexLengthBits> {}; // NOLINT
8639 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8640 // could use a mask to test if the length of string is less than or equal to
8641 // kMaxCachedArrayIndexLength.
8642 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8644 static const unsigned int kContainsCachedArrayIndexMask =
8645 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8646 << ArrayIndexLengthBits::kShift) |
8647 kIsNotArrayIndexMask;
8649 // Value of empty hash field indicating that the hash is not computed.
8650 static const int kEmptyHashField =
8651 kIsNotArrayIndexMask | kHashNotComputedMask;
8654 static inline bool IsHashFieldComputed(uint32_t field);
8657 DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8662 class Symbol: public Name {
8664 // [name]: The print name of a symbol, or undefined if none.
8665 DECL_ACCESSORS(name, Object)
8667 DECL_ACCESSORS(flags, Smi)
8669 // [is_private]: Whether this is a private symbol. Private symbols can only
8670 // be used to designate own properties of objects.
8671 DECL_BOOLEAN_ACCESSORS(is_private)
8673 DECLARE_CAST(Symbol)
8675 // Dispatched behavior.
8676 DECLARE_PRINTER(Symbol)
8677 DECLARE_VERIFIER(Symbol)
8679 // Layout description.
8680 static const int kNameOffset = Name::kSize;
8681 static const int kFlagsOffset = kNameOffset + kPointerSize;
8682 static const int kSize = kFlagsOffset + kPointerSize;
8684 typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
8686 void SymbolShortPrint(std::ostream& os);
8689 static const int kPrivateBit = 0;
8691 const char* PrivateSymbolToName() const;
8694 friend class Name; // For PrivateSymbolToName.
8697 DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
8703 // The String abstract class captures JavaScript string values:
8706 // 4.3.16 String Value
8707 // A string value is a member of the type String and is a finite
8708 // ordered sequence of zero or more 16-bit unsigned integer values.
8710 // All string values have a length field.
8711 class String: public Name {
8713 enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
8715 // Array index strings this short can keep their index in the hash field.
8716 static const int kMaxCachedArrayIndexLength = 7;
8718 // For strings which are array indexes the hash value has the string length
8719 // mixed into the hash, mainly to avoid a hash value of zero which would be
8720 // the case for the string '0'. 24 bits are used for the array index value.
8721 static const int kArrayIndexValueBits = 24;
8722 static const int kArrayIndexLengthBits =
8723 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8725 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8727 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8728 kArrayIndexValueBits> {}; // NOLINT
8729 class ArrayIndexLengthBits : public BitField<unsigned int,
8730 kNofHashBitFields + kArrayIndexValueBits,
8731 kArrayIndexLengthBits> {}; // NOLINT
8733 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8734 // could use a mask to test if the length of string is less than or equal to
8735 // kMaxCachedArrayIndexLength.
8736 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8738 static const unsigned int kContainsCachedArrayIndexMask =
8739 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8740 << ArrayIndexLengthBits::kShift) |
8741 kIsNotArrayIndexMask;
8743 class SubStringRange {
8745 explicit SubStringRange(String* string, int first = 0, int length = -1)
8748 length_(length == -1 ? string->length() : length) {}
8750 inline iterator begin();
8751 inline iterator end();
8759 // Representation of the flat content of a String.
8760 // A non-flat string doesn't have flat content.
8761 // A flat string has content that's encoded as a sequence of either
8762 // one-byte chars or two-byte UC16.
8763 // Returned by String::GetFlatContent().
8766 // Returns true if the string is flat and this structure contains content.
8767 bool IsFlat() { return state_ != NON_FLAT; }
8768 // Returns true if the structure contains one-byte content.
8769 bool IsOneByte() { return state_ == ONE_BYTE; }
8770 // Returns true if the structure contains two-byte content.
8771 bool IsTwoByte() { return state_ == TWO_BYTE; }
8773 // Return the one byte content of the string. Only use if IsOneByte()
8775 Vector<const uint8_t> ToOneByteVector() {
8776 DCHECK_EQ(ONE_BYTE, state_);
8777 return Vector<const uint8_t>(onebyte_start, length_);
8779 // Return the two-byte content of the string. Only use if IsTwoByte()
8781 Vector<const uc16> ToUC16Vector() {
8782 DCHECK_EQ(TWO_BYTE, state_);
8783 return Vector<const uc16>(twobyte_start, length_);
8787 DCHECK(i < length_);
8788 DCHECK(state_ != NON_FLAT);
8789 if (state_ == ONE_BYTE) return onebyte_start[i];
8790 return twobyte_start[i];
8793 bool UsesSameString(const FlatContent& other) const {
8794 return onebyte_start == other.onebyte_start;
8798 enum State { NON_FLAT, ONE_BYTE, TWO_BYTE };
8800 // Constructors only used by String::GetFlatContent().
8801 explicit FlatContent(const uint8_t* start, int length)
8802 : onebyte_start(start), length_(length), state_(ONE_BYTE) {}
8803 explicit FlatContent(const uc16* start, int length)
8804 : twobyte_start(start), length_(length), state_(TWO_BYTE) { }
8805 FlatContent() : onebyte_start(NULL), length_(0), state_(NON_FLAT) { }
8808 const uint8_t* onebyte_start;
8809 const uc16* twobyte_start;
8814 friend class String;
8815 friend class IterableSubString;
8818 template <typename Char>
8819 INLINE(Vector<const Char> GetCharVector());
8821 // Get and set the length of the string.
8822 inline int length() const;
8823 inline void set_length(int value);
8825 // Get and set the length of the string using acquire loads and release
8827 inline int synchronized_length() const;
8828 inline void synchronized_set_length(int value);
8830 // Returns whether this string has only one-byte chars, i.e. all of them can
8831 // be one-byte encoded. This might be the case even if the string is
8832 // two-byte. Such strings may appear when the embedder prefers
8833 // two-byte external representations even for one-byte data.
8834 inline bool IsOneByteRepresentation() const;
8835 inline bool IsTwoByteRepresentation() const;
8837 // Cons and slices have an encoding flag that may not represent the actual
8838 // encoding of the underlying string. This is taken into account here.
8839 // Requires: this->IsFlat()
8840 inline bool IsOneByteRepresentationUnderneath();
8841 inline bool IsTwoByteRepresentationUnderneath();
8843 // NOTE: this should be considered only a hint. False negatives are
8845 inline bool HasOnlyOneByteChars();
8847 // Get and set individual two byte chars in the string.
8848 inline void Set(int index, uint16_t value);
8849 // Get individual two byte char in the string. Repeated calls
8850 // to this method are not efficient unless the string is flat.
8851 INLINE(uint16_t Get(int index));
8853 // Flattens the string. Checks first inline to see if it is
8854 // necessary. Does nothing if the string is not a cons string.
8855 // Flattening allocates a sequential string with the same data as
8856 // the given string and mutates the cons string to a degenerate
8857 // form, where the first component is the new sequential string and
8858 // the second component is the empty string. If allocation fails,
8859 // this function returns a failure. If flattening succeeds, this
8860 // function returns the sequential string that is now the first
8861 // component of the cons string.
8863 // Degenerate cons strings are handled specially by the garbage
8864 // collector (see IsShortcutCandidate).
8866 static inline Handle<String> Flatten(Handle<String> string,
8867 PretenureFlag pretenure = NOT_TENURED);
8869 // Tries to return the content of a flat string as a structure holding either
8870 // a flat vector of char or of uc16.
8871 // If the string isn't flat, and therefore doesn't have flat content, the
8872 // returned structure will report so, and can't provide a vector of either
8874 FlatContent GetFlatContent();
8876 // Returns the parent of a sliced string or first part of a flat cons string.
8877 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
8878 inline String* GetUnderlying();
8880 // String equality operations.
8881 inline bool Equals(String* other);
8882 inline static bool Equals(Handle<String> one, Handle<String> two);
8883 bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
8884 bool IsOneByteEqualTo(Vector<const uint8_t> str);
8885 bool IsTwoByteEqualTo(Vector<const uc16> str);
8887 // Return a UTF8 representation of the string. The string is null
8888 // terminated but may optionally contain nulls. Length is returned
8889 // in length_output if length_output is not a null pointer The string
8890 // should be nearly flat, otherwise the performance of this method may
8891 // be very slow (quadratic in the length). Setting robustness_flag to
8892 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8893 // handles unexpected data without causing assert failures and it does not
8894 // do any heap allocations. This is useful when printing stack traces.
8895 base::SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
8896 RobustnessFlag robustness_flag,
8897 int offset, int length,
8898 int* length_output = 0);
8899 base::SmartArrayPointer<char> ToCString(
8900 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
8901 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
8902 int* length_output = 0);
8904 // Return a 16 bit Unicode representation of the string.
8905 // The string should be nearly flat, otherwise the performance of
8906 // of this method may be very bad. Setting robustness_flag to
8907 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8908 // handles unexpected data without causing assert failures and it does not
8909 // do any heap allocations. This is useful when printing stack traces.
8910 base::SmartArrayPointer<uc16> ToWideCString(
8911 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
8913 bool ComputeArrayIndex(uint32_t* index);
8916 bool MakeExternal(v8::String::ExternalStringResource* resource);
8917 bool MakeExternal(v8::String::ExternalOneByteStringResource* resource);
8920 inline bool AsArrayIndex(uint32_t* index);
8922 DECLARE_CAST(String)
8924 void PrintOn(FILE* out);
8926 // For use during stack traces. Performs rudimentary sanity check.
8929 // Dispatched behavior.
8930 void StringShortPrint(StringStream* accumulator);
8931 void PrintUC16(std::ostream& os, int start = 0, int end = -1); // NOLINT
8932 #if defined(DEBUG) || defined(OBJECT_PRINT)
8933 char* ToAsciiArray();
8935 DECLARE_PRINTER(String)
8936 DECLARE_VERIFIER(String)
8938 inline bool IsFlat();
8940 // Layout description.
8941 static const int kLengthOffset = Name::kSize;
8942 static const int kSize = kLengthOffset + kPointerSize;
8944 // Maximum number of characters to consider when trying to convert a string
8945 // value into an array index.
8946 static const int kMaxArrayIndexSize = 10;
8947 STATIC_ASSERT(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
8950 static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
8951 static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
8952 static const int kMaxUtf16CodeUnit = 0xffff;
8953 static const uint32_t kMaxUtf16CodeUnitU = kMaxUtf16CodeUnit;
8955 // Value of hash field containing computed hash equal to zero.
8956 static const int kEmptyStringHash = kIsNotArrayIndexMask;
8958 // Maximal string length.
8959 static const int kMaxLength = (1 << 28) - 16;
8961 // Max length for computing hash. For strings longer than this limit the
8962 // string length is used as the hash value.
8963 static const int kMaxHashCalcLength = 16383;
8965 // Limit for truncation in short printing.
8966 static const int kMaxShortPrintLength = 1024;
8968 // Support for regular expressions.
8969 const uc16* GetTwoByteData(unsigned start);
8971 // Helper function for flattening strings.
8972 template <typename sinkchar>
8973 static void WriteToFlat(String* source,
8978 // The return value may point to the first aligned word containing the first
8979 // non-one-byte character, rather than directly to the non-one-byte character.
8980 // If the return value is >= the passed length, the entire string was
8982 static inline int NonAsciiStart(const char* chars, int length) {
8983 const char* start = chars;
8984 const char* limit = chars + length;
8986 if (length >= kIntptrSize) {
8987 // Check unaligned bytes.
8988 while (!IsAligned(reinterpret_cast<intptr_t>(chars), sizeof(uintptr_t))) {
8989 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8990 return static_cast<int>(chars - start);
8994 // Check aligned words.
8995 DCHECK(unibrow::Utf8::kMaxOneByteChar == 0x7F);
8996 const uintptr_t non_one_byte_mask = kUintptrAllBitsSet / 0xFF * 0x80;
8997 while (chars + sizeof(uintptr_t) <= limit) {
8998 if (*reinterpret_cast<const uintptr_t*>(chars) & non_one_byte_mask) {
8999 return static_cast<int>(chars - start);
9001 chars += sizeof(uintptr_t);
9004 // Check remaining unaligned bytes.
9005 while (chars < limit) {
9006 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
9007 return static_cast<int>(chars - start);
9012 return static_cast<int>(chars - start);
9015 static inline bool IsAscii(const char* chars, int length) {
9016 return NonAsciiStart(chars, length) >= length;
9019 static inline bool IsAscii(const uint8_t* chars, int length) {
9021 NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
9024 static inline int NonOneByteStart(const uc16* chars, int length) {
9025 const uc16* limit = chars + length;
9026 const uc16* start = chars;
9027 while (chars < limit) {
9028 if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
9031 return static_cast<int>(chars - start);
9034 static inline bool IsOneByte(const uc16* chars, int length) {
9035 return NonOneByteStart(chars, length) >= length;
9038 template<class Visitor>
9039 static inline ConsString* VisitFlat(Visitor* visitor,
9043 static Handle<FixedArray> CalculateLineEnds(Handle<String> string,
9044 bool include_ending_line);
9046 // Use the hash field to forward to the canonical internalized string
9047 // when deserializing an internalized string.
9048 inline void SetForwardedInternalizedString(String* string);
9049 inline String* GetForwardedInternalizedString();
9053 friend class StringTableInsertionKey;
9055 static Handle<String> SlowFlatten(Handle<ConsString> cons,
9056 PretenureFlag tenure);
9058 // Slow case of String::Equals. This implementation works on any strings
9059 // but it is most efficient on strings that are almost flat.
9060 bool SlowEquals(String* other);
9062 static bool SlowEquals(Handle<String> one, Handle<String> two);
9064 // Slow case of AsArrayIndex.
9065 bool SlowAsArrayIndex(uint32_t* index);
9067 // Compute and set the hash code.
9068 uint32_t ComputeAndSetHash();
9070 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
9074 // The SeqString abstract class captures sequential string values.
9075 class SeqString: public String {
9077 DECLARE_CAST(SeqString)
9079 // Layout description.
9080 static const int kHeaderSize = String::kSize;
9082 // Truncate the string in-place if possible and return the result.
9083 // In case of new_length == 0, the empty string is returned without
9084 // truncating the original string.
9085 MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
9088 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
9092 // The OneByteString class captures sequential one-byte string objects.
9093 // Each character in the OneByteString is an one-byte character.
9094 class SeqOneByteString: public SeqString {
9096 static const bool kHasOneByteEncoding = true;
9098 // Dispatched behavior.
9099 inline uint16_t SeqOneByteStringGet(int index);
9100 inline void SeqOneByteStringSet(int index, uint16_t value);
9102 // Get the address of the characters in this string.
9103 inline Address GetCharsAddress();
9105 inline uint8_t* GetChars();
9107 DECLARE_CAST(SeqOneByteString)
9109 // Garbage collection support. This method is called by the
9110 // garbage collector to compute the actual size of an OneByteString
9112 inline int SeqOneByteStringSize(InstanceType instance_type);
9114 // Computes the size for an OneByteString instance of a given length.
9115 static int SizeFor(int length) {
9116 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
9119 // Maximal memory usage for a single sequential one-byte string.
9120 static const int kMaxSize = 512 * MB - 1;
9121 STATIC_ASSERT((kMaxSize - kHeaderSize) >= String::kMaxLength);
9124 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
9128 // The TwoByteString class captures sequential unicode string objects.
9129 // Each character in the TwoByteString is a two-byte uint16_t.
9130 class SeqTwoByteString: public SeqString {
9132 static const bool kHasOneByteEncoding = false;
9134 // Dispatched behavior.
9135 inline uint16_t SeqTwoByteStringGet(int index);
9136 inline void SeqTwoByteStringSet(int index, uint16_t value);
9138 // Get the address of the characters in this string.
9139 inline Address GetCharsAddress();
9141 inline uc16* GetChars();
9144 const uint16_t* SeqTwoByteStringGetData(unsigned start);
9146 DECLARE_CAST(SeqTwoByteString)
9148 // Garbage collection support. This method is called by the
9149 // garbage collector to compute the actual size of a TwoByteString
9151 inline int SeqTwoByteStringSize(InstanceType instance_type);
9153 // Computes the size for a TwoByteString instance of a given length.
9154 static int SizeFor(int length) {
9155 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
9158 // Maximal memory usage for a single sequential two-byte string.
9159 static const int kMaxSize = 512 * MB - 1;
9160 STATIC_ASSERT(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
9161 String::kMaxLength);
9164 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
9168 // The ConsString class describes string values built by using the
9169 // addition operator on strings. A ConsString is a pair where the
9170 // first and second components are pointers to other string values.
9171 // One or both components of a ConsString can be pointers to other
9172 // ConsStrings, creating a binary tree of ConsStrings where the leaves
9173 // are non-ConsString string values. The string value represented by
9174 // a ConsString can be obtained by concatenating the leaf string
9175 // values in a left-to-right depth-first traversal of the tree.
9176 class ConsString: public String {
9178 // First string of the cons cell.
9179 inline String* first();
9180 // Doesn't check that the result is a string, even in debug mode. This is
9181 // useful during GC where the mark bits confuse the checks.
9182 inline Object* unchecked_first();
9183 inline void set_first(String* first,
9184 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9186 // Second string of the cons cell.
9187 inline String* second();
9188 // Doesn't check that the result is a string, even in debug mode. This is
9189 // useful during GC where the mark bits confuse the checks.
9190 inline Object* unchecked_second();
9191 inline void set_second(String* second,
9192 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9194 // Dispatched behavior.
9195 uint16_t ConsStringGet(int index);
9197 DECLARE_CAST(ConsString)
9199 // Layout description.
9200 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
9201 static const int kSecondOffset = kFirstOffset + kPointerSize;
9202 static const int kSize = kSecondOffset + kPointerSize;
9204 // Minimum length for a cons string.
9205 static const int kMinLength = 13;
9207 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
9210 DECLARE_VERIFIER(ConsString)
9213 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
9217 // The Sliced String class describes strings that are substrings of another
9218 // sequential string. The motivation is to save time and memory when creating
9219 // a substring. A Sliced String is described as a pointer to the parent,
9220 // the offset from the start of the parent string and the length. Using
9221 // a Sliced String therefore requires unpacking of the parent string and
9222 // adding the offset to the start address. A substring of a Sliced String
9223 // are not nested since the double indirection is simplified when creating
9224 // such a substring.
9225 // Currently missing features are:
9226 // - handling externalized parent strings
9227 // - external strings as parent
9228 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
9229 class SlicedString: public String {
9231 inline String* parent();
9232 inline void set_parent(String* parent,
9233 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9234 inline int offset() const;
9235 inline void set_offset(int offset);
9237 // Dispatched behavior.
9238 uint16_t SlicedStringGet(int index);
9240 DECLARE_CAST(SlicedString)
9242 // Layout description.
9243 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
9244 static const int kOffsetOffset = kParentOffset + kPointerSize;
9245 static const int kSize = kOffsetOffset + kPointerSize;
9247 // Minimum length for a sliced string.
9248 static const int kMinLength = 13;
9250 typedef FixedBodyDescriptor<kParentOffset,
9251 kOffsetOffset + kPointerSize, kSize>
9254 DECLARE_VERIFIER(SlicedString)
9257 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
9261 // The ExternalString class describes string values that are backed by
9262 // a string resource that lies outside the V8 heap. ExternalStrings
9263 // consist of the length field common to all strings, a pointer to the
9264 // external resource. It is important to ensure (externally) that the
9265 // resource is not deallocated while the ExternalString is live in the
9268 // The API expects that all ExternalStrings are created through the
9269 // API. Therefore, ExternalStrings should not be used internally.
9270 class ExternalString: public String {
9272 DECLARE_CAST(ExternalString)
9274 // Layout description.
9275 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
9276 static const int kShortSize = kResourceOffset + kPointerSize;
9277 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
9278 static const int kSize = kResourceDataOffset + kPointerSize;
9280 static const int kMaxShortLength =
9281 (kShortSize - SeqString::kHeaderSize) / kCharSize;
9283 // Return whether external string is short (data pointer is not cached).
9284 inline bool is_short();
9286 STATIC_ASSERT(kResourceOffset == Internals::kStringResourceOffset);
9289 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
9293 // The ExternalOneByteString class is an external string backed by an
9295 class ExternalOneByteString : public ExternalString {
9297 static const bool kHasOneByteEncoding = true;
9299 typedef v8::String::ExternalOneByteStringResource Resource;
9301 // The underlying resource.
9302 inline const Resource* resource();
9303 inline void set_resource(const Resource* buffer);
9305 // Update the pointer cache to the external character array.
9306 // The cached pointer is always valid, as the external character array does =
9307 // not move during lifetime. Deserialization is the only exception, after
9308 // which the pointer cache has to be refreshed.
9309 inline void update_data_cache();
9311 inline const uint8_t* GetChars();
9313 // Dispatched behavior.
9314 inline uint16_t ExternalOneByteStringGet(int index);
9316 DECLARE_CAST(ExternalOneByteString)
9318 // Garbage collection support.
9319 inline void ExternalOneByteStringIterateBody(ObjectVisitor* v);
9321 template <typename StaticVisitor>
9322 inline void ExternalOneByteStringIterateBody();
9325 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalOneByteString);
9329 // The ExternalTwoByteString class is an external string backed by a UTF-16
9331 class ExternalTwoByteString: public ExternalString {
9333 static const bool kHasOneByteEncoding = false;
9335 typedef v8::String::ExternalStringResource Resource;
9337 // The underlying string resource.
9338 inline const Resource* resource();
9339 inline void set_resource(const Resource* buffer);
9341 // Update the pointer cache to the external character array.
9342 // The cached pointer is always valid, as the external character array does =
9343 // not move during lifetime. Deserialization is the only exception, after
9344 // which the pointer cache has to be refreshed.
9345 inline void update_data_cache();
9347 inline const uint16_t* GetChars();
9349 // Dispatched behavior.
9350 inline uint16_t ExternalTwoByteStringGet(int index);
9353 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
9355 DECLARE_CAST(ExternalTwoByteString)
9357 // Garbage collection support.
9358 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
9360 template<typename StaticVisitor>
9361 inline void ExternalTwoByteStringIterateBody();
9364 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
9368 // Utility superclass for stack-allocated objects that must be updated
9369 // on gc. It provides two ways for the gc to update instances, either
9370 // iterating or updating after gc.
9371 class Relocatable BASE_EMBEDDED {
9373 explicit inline Relocatable(Isolate* isolate);
9374 inline virtual ~Relocatable();
9375 virtual void IterateInstance(ObjectVisitor* v) { }
9376 virtual void PostGarbageCollection() { }
9378 static void PostGarbageCollectionProcessing(Isolate* isolate);
9379 static int ArchiveSpacePerThread();
9380 static char* ArchiveState(Isolate* isolate, char* to);
9381 static char* RestoreState(Isolate* isolate, char* from);
9382 static void Iterate(Isolate* isolate, ObjectVisitor* v);
9383 static void Iterate(ObjectVisitor* v, Relocatable* top);
9384 static char* Iterate(ObjectVisitor* v, char* t);
9392 // A flat string reader provides random access to the contents of a
9393 // string independent of the character width of the string. The handle
9394 // must be valid as long as the reader is being used.
9395 class FlatStringReader : public Relocatable {
9397 FlatStringReader(Isolate* isolate, Handle<String> str);
9398 FlatStringReader(Isolate* isolate, Vector<const char> input);
9399 void PostGarbageCollection();
9400 inline uc32 Get(int index);
9401 template <typename Char>
9402 inline Char Get(int index);
9403 int length() { return length_; }
9412 // This maintains an off-stack representation of the stack frames required
9413 // to traverse a ConsString, allowing an entirely iterative and restartable
9414 // traversal of the entire string
9415 class ConsStringIterator {
9417 inline ConsStringIterator() {}
9418 inline explicit ConsStringIterator(ConsString* cons_string, int offset = 0) {
9419 Reset(cons_string, offset);
9421 inline void Reset(ConsString* cons_string, int offset = 0) {
9423 // Next will always return NULL.
9424 if (cons_string == NULL) return;
9425 Initialize(cons_string, offset);
9427 // Returns NULL when complete.
9428 inline String* Next(int* offset_out) {
9430 if (depth_ == 0) return NULL;
9431 return Continue(offset_out);
9435 static const int kStackSize = 32;
9436 // Use a mask instead of doing modulo operations for stack wrapping.
9437 static const int kDepthMask = kStackSize-1;
9438 STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
9439 static inline int OffsetForDepth(int depth);
9441 inline void PushLeft(ConsString* string);
9442 inline void PushRight(ConsString* string);
9443 inline void AdjustMaximumDepth();
9445 inline bool StackBlown() { return maximum_depth_ - depth_ == kStackSize; }
9446 void Initialize(ConsString* cons_string, int offset);
9447 String* Continue(int* offset_out);
9448 String* NextLeaf(bool* blew_stack);
9449 String* Search(int* offset_out);
9451 // Stack must always contain only frames for which right traversal
9452 // has not yet been performed.
9453 ConsString* frames_[kStackSize];
9458 DISALLOW_COPY_AND_ASSIGN(ConsStringIterator);
9462 class StringCharacterStream {
9464 inline StringCharacterStream(String* string,
9466 inline uint16_t GetNext();
9467 inline bool HasMore();
9468 inline void Reset(String* string, int offset = 0);
9469 inline void VisitOneByteString(const uint8_t* chars, int length);
9470 inline void VisitTwoByteString(const uint16_t* chars, int length);
9473 ConsStringIterator iter_;
9476 const uint8_t* buffer8_;
9477 const uint16_t* buffer16_;
9479 const uint8_t* end_;
9480 DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
9484 template <typename T>
9485 class VectorIterator {
9487 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
9488 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
9489 T GetNext() { return data_[index_++]; }
9490 bool has_more() { return index_ < data_.length(); }
9492 Vector<const T> data_;
9497 // The Oddball describes objects null, undefined, true, and false.
9498 class Oddball: public HeapObject {
9500 // [to_string]: Cached to_string computed at startup.
9501 DECL_ACCESSORS(to_string, String)
9503 // [to_number]: Cached to_number computed at startup.
9504 DECL_ACCESSORS(to_number, Object)
9506 inline byte kind() const;
9507 inline void set_kind(byte kind);
9509 DECLARE_CAST(Oddball)
9511 // Dispatched behavior.
9512 DECLARE_VERIFIER(Oddball)
9514 // Initialize the fields.
9515 static void Initialize(Isolate* isolate,
9516 Handle<Oddball> oddball,
9517 const char* to_string,
9518 Handle<Object> to_number,
9521 // Layout description.
9522 static const int kToStringOffset = HeapObject::kHeaderSize;
9523 static const int kToNumberOffset = kToStringOffset + kPointerSize;
9524 static const int kKindOffset = kToNumberOffset + kPointerSize;
9525 static const int kSize = kKindOffset + kPointerSize;
9527 static const byte kFalse = 0;
9528 static const byte kTrue = 1;
9529 static const byte kNotBooleanMask = ~1;
9530 static const byte kTheHole = 2;
9531 static const byte kNull = 3;
9532 static const byte kArgumentMarker = 4;
9533 static const byte kUndefined = 5;
9534 static const byte kUninitialized = 6;
9535 static const byte kOther = 7;
9536 static const byte kException = 8;
9538 typedef FixedBodyDescriptor<kToStringOffset,
9539 kToNumberOffset + kPointerSize,
9540 kSize> BodyDescriptor;
9542 STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset);
9543 STATIC_ASSERT(kNull == Internals::kNullOddballKind);
9544 STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind);
9547 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
9551 class Cell: public HeapObject {
9553 // [value]: value of the cell.
9554 DECL_ACCESSORS(value, Object)
9558 static inline Cell* FromValueAddress(Address value) {
9559 Object* result = FromAddress(value - kValueOffset);
9560 return static_cast<Cell*>(result);
9563 inline Address ValueAddress() {
9564 return address() + kValueOffset;
9567 // Dispatched behavior.
9568 DECLARE_PRINTER(Cell)
9569 DECLARE_VERIFIER(Cell)
9571 // Layout description.
9572 static const int kValueOffset = HeapObject::kHeaderSize;
9573 static const int kSize = kValueOffset + kPointerSize;
9575 typedef FixedBodyDescriptor<kValueOffset,
9576 kValueOffset + kPointerSize,
9577 kSize> BodyDescriptor;
9580 DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9584 class PropertyCell : public HeapObject {
9586 // [property_details]: details of the global property.
9587 DECL_ACCESSORS(property_details_raw, Object)
9588 // [value]: value of the global property.
9589 DECL_ACCESSORS(value, Object)
9590 // [dependent_code]: dependent code that depends on the type of the global
9592 DECL_ACCESSORS(dependent_code, DependentCode)
9594 PropertyDetails property_details() {
9595 return PropertyDetails(Smi::cast(property_details_raw()));
9598 void set_property_details(PropertyDetails details) {
9599 set_property_details_raw(details.AsSmi());
9602 PropertyCellConstantType GetConstantType();
9604 // Computes the new type of the cell's contents for the given value, but
9605 // without actually modifying the details.
9606 static PropertyCellType UpdatedType(Handle<PropertyCell> cell,
9607 Handle<Object> value,
9608 PropertyDetails details);
9609 static void UpdateCell(Handle<GlobalDictionary> dictionary, int entry,
9610 Handle<Object> value, PropertyDetails details);
9612 static Handle<PropertyCell> InvalidateEntry(
9613 Handle<GlobalDictionary> dictionary, int entry);
9615 static void SetValueWithInvalidation(Handle<PropertyCell> cell,
9616 Handle<Object> new_value);
9618 DECLARE_CAST(PropertyCell)
9620 // Dispatched behavior.
9621 DECLARE_PRINTER(PropertyCell)
9622 DECLARE_VERIFIER(PropertyCell)
9624 // Layout description.
9625 static const int kDetailsOffset = HeapObject::kHeaderSize;
9626 static const int kValueOffset = kDetailsOffset + kPointerSize;
9627 static const int kDependentCodeOffset = kValueOffset + kPointerSize;
9628 static const int kSize = kDependentCodeOffset + kPointerSize;
9630 static const int kPointerFieldsBeginOffset = kValueOffset;
9631 static const int kPointerFieldsEndOffset = kSize;
9633 typedef FixedBodyDescriptor<kValueOffset,
9635 kSize> BodyDescriptor;
9638 DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9642 class WeakCell : public HeapObject {
9644 inline Object* value() const;
9646 // This should not be called by anyone except GC.
9647 inline void clear();
9649 // This should not be called by anyone except allocator.
9650 inline void initialize(HeapObject* value);
9652 inline bool cleared() const;
9654 DECL_ACCESSORS(next, Object)
9656 inline void clear_next(Heap* heap);
9658 inline bool next_cleared();
9660 DECLARE_CAST(WeakCell)
9662 DECLARE_PRINTER(WeakCell)
9663 DECLARE_VERIFIER(WeakCell)
9665 // Layout description.
9666 static const int kValueOffset = HeapObject::kHeaderSize;
9667 static const int kNextOffset = kValueOffset + kPointerSize;
9668 static const int kSize = kNextOffset + kPointerSize;
9670 typedef FixedBodyDescriptor<kValueOffset, kSize, kSize> BodyDescriptor;
9673 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakCell);
9677 // The JSProxy describes EcmaScript Harmony proxies
9678 class JSProxy: public JSReceiver {
9680 // [handler]: The handler property.
9681 DECL_ACCESSORS(handler, Object)
9683 // [hash]: The hash code property (undefined if not initialized yet).
9684 DECL_ACCESSORS(hash, Object)
9686 DECLARE_CAST(JSProxy)
9688 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithHandler(
9689 Handle<JSProxy> proxy,
9690 Handle<Object> receiver,
9693 // If the handler defines an accessor property with a setter, invoke it.
9694 // If it defines an accessor property without a setter, or a data property
9695 // that is read-only, throw. In all these cases set '*done' to true,
9696 // otherwise set it to false.
9698 static MaybeHandle<Object> SetPropertyViaPrototypesWithHandler(
9699 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9700 Handle<Object> value, LanguageMode language_mode, bool* done);
9702 MUST_USE_RESULT static Maybe<PropertyAttributes>
9703 GetPropertyAttributesWithHandler(Handle<JSProxy> proxy,
9704 Handle<Object> receiver,
9706 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithHandler(
9707 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9708 Handle<Object> value, LanguageMode language_mode);
9710 // Turn the proxy into an (empty) JSObject.
9711 static void Fix(Handle<JSProxy> proxy);
9713 // Initializes the body after the handler slot.
9714 inline void InitializeBody(int object_size, Object* value);
9716 // Invoke a trap by name. If the trap does not exist on this's handler,
9717 // but derived_trap is non-NULL, invoke that instead. May cause GC.
9718 MUST_USE_RESULT static MaybeHandle<Object> CallTrap(
9719 Handle<JSProxy> proxy,
9721 Handle<Object> derived_trap,
9723 Handle<Object> args[]);
9725 // Dispatched behavior.
9726 DECLARE_PRINTER(JSProxy)
9727 DECLARE_VERIFIER(JSProxy)
9729 // Layout description. We add padding so that a proxy has the same
9730 // size as a virgin JSObject. This is essential for becoming a JSObject
9732 static const int kHandlerOffset = HeapObject::kHeaderSize;
9733 static const int kHashOffset = kHandlerOffset + kPointerSize;
9734 static const int kPaddingOffset = kHashOffset + kPointerSize;
9735 static const int kSize = JSObject::kHeaderSize;
9736 static const int kHeaderSize = kPaddingOffset;
9737 static const int kPaddingSize = kSize - kPaddingOffset;
9739 STATIC_ASSERT(kPaddingSize >= 0);
9741 typedef FixedBodyDescriptor<kHandlerOffset,
9743 kSize> BodyDescriptor;
9746 friend class JSReceiver;
9748 MUST_USE_RESULT static Maybe<bool> HasPropertyWithHandler(
9749 Handle<JSProxy> proxy, Handle<Name> name);
9751 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithHandler(
9752 Handle<JSProxy> proxy, Handle<Name> name, LanguageMode language_mode);
9754 MUST_USE_RESULT Object* GetIdentityHash();
9756 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
9758 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
9762 class JSFunctionProxy: public JSProxy {
9764 // [call_trap]: The call trap.
9765 DECL_ACCESSORS(call_trap, Object)
9767 // [construct_trap]: The construct trap.
9768 DECL_ACCESSORS(construct_trap, Object)
9770 DECLARE_CAST(JSFunctionProxy)
9772 // Dispatched behavior.
9773 DECLARE_PRINTER(JSFunctionProxy)
9774 DECLARE_VERIFIER(JSFunctionProxy)
9776 // Layout description.
9777 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
9778 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
9779 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
9780 static const int kSize = JSFunction::kSize;
9781 static const int kPaddingSize = kSize - kPaddingOffset;
9783 STATIC_ASSERT(kPaddingSize >= 0);
9785 typedef FixedBodyDescriptor<kHandlerOffset,
9786 kConstructTrapOffset + kPointerSize,
9787 kSize> BodyDescriptor;
9790 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
9794 class JSCollection : public JSObject {
9796 // [table]: the backing hash table
9797 DECL_ACCESSORS(table, Object)
9799 static const int kTableOffset = JSObject::kHeaderSize;
9800 static const int kSize = kTableOffset + kPointerSize;
9803 DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollection);
9807 // The JSSet describes EcmaScript Harmony sets
9808 class JSSet : public JSCollection {
9812 // Dispatched behavior.
9813 DECLARE_PRINTER(JSSet)
9814 DECLARE_VERIFIER(JSSet)
9817 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
9821 // The JSMap describes EcmaScript Harmony maps
9822 class JSMap : public JSCollection {
9826 // Dispatched behavior.
9827 DECLARE_PRINTER(JSMap)
9828 DECLARE_VERIFIER(JSMap)
9831 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
9835 // OrderedHashTableIterator is an iterator that iterates over the keys and
9836 // values of an OrderedHashTable.
9838 // The iterator has a reference to the underlying OrderedHashTable data,
9839 // [table], as well as the current [index] the iterator is at.
9841 // When the OrderedHashTable is rehashed it adds a reference from the old table
9842 // to the new table as well as storing enough data about the changes so that the
9843 // iterator [index] can be adjusted accordingly.
9845 // When the [Next] result from the iterator is requested, the iterator checks if
9846 // there is a newer table that it needs to transition to.
9847 template<class Derived, class TableType>
9848 class OrderedHashTableIterator: public JSObject {
9850 // [table]: the backing hash table mapping keys to values.
9851 DECL_ACCESSORS(table, Object)
9853 // [index]: The index into the data table.
9854 DECL_ACCESSORS(index, Object)
9856 // [kind]: The kind of iteration this is. One of the [Kind] enum values.
9857 DECL_ACCESSORS(kind, Object)
9860 void OrderedHashTableIteratorPrint(std::ostream& os); // NOLINT
9863 static const int kTableOffset = JSObject::kHeaderSize;
9864 static const int kIndexOffset = kTableOffset + kPointerSize;
9865 static const int kKindOffset = kIndexOffset + kPointerSize;
9866 static const int kSize = kKindOffset + kPointerSize;
9874 // Whether the iterator has more elements. This needs to be called before
9875 // calling |CurrentKey| and/or |CurrentValue|.
9878 // Move the index forward one.
9880 set_index(Smi::FromInt(Smi::cast(index())->value() + 1));
9883 // Populates the array with the next key and value and then moves the iterator
9885 // This returns the |kind| or 0 if the iterator is already at the end.
9886 Smi* Next(JSArray* value_array);
9888 // Returns the current key of the iterator. This should only be called when
9889 // |HasMore| returns true.
9890 inline Object* CurrentKey();
9893 // Transitions the iterator to the non obsolete backing store. This is a NOP
9894 // if the [table] is not obsolete.
9897 DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
9901 class JSSetIterator: public OrderedHashTableIterator<JSSetIterator,
9904 // Dispatched behavior.
9905 DECLARE_PRINTER(JSSetIterator)
9906 DECLARE_VERIFIER(JSSetIterator)
9908 DECLARE_CAST(JSSetIterator)
9910 // Called by |Next| to populate the array. This allows the subclasses to
9911 // populate the array differently.
9912 inline void PopulateValueArray(FixedArray* array);
9915 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSetIterator);
9919 class JSMapIterator: public OrderedHashTableIterator<JSMapIterator,
9922 // Dispatched behavior.
9923 DECLARE_PRINTER(JSMapIterator)
9924 DECLARE_VERIFIER(JSMapIterator)
9926 DECLARE_CAST(JSMapIterator)
9928 // Called by |Next| to populate the array. This allows the subclasses to
9929 // populate the array differently.
9930 inline void PopulateValueArray(FixedArray* array);
9933 // Returns the current value of the iterator. This should only be called when
9934 // |HasMore| returns true.
9935 inline Object* CurrentValue();
9937 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMapIterator);
9941 // Base class for both JSWeakMap and JSWeakSet
9942 class JSWeakCollection: public JSObject {
9944 // [table]: the backing hash table mapping keys to values.
9945 DECL_ACCESSORS(table, Object)
9947 // [next]: linked list of encountered weak maps during GC.
9948 DECL_ACCESSORS(next, Object)
9950 static const int kTableOffset = JSObject::kHeaderSize;
9951 static const int kNextOffset = kTableOffset + kPointerSize;
9952 static const int kSize = kNextOffset + kPointerSize;
9955 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
9959 // The JSWeakMap describes EcmaScript Harmony weak maps
9960 class JSWeakMap: public JSWeakCollection {
9962 DECLARE_CAST(JSWeakMap)
9964 // Dispatched behavior.
9965 DECLARE_PRINTER(JSWeakMap)
9966 DECLARE_VERIFIER(JSWeakMap)
9969 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
9973 // The JSWeakSet describes EcmaScript Harmony weak sets
9974 class JSWeakSet: public JSWeakCollection {
9976 DECLARE_CAST(JSWeakSet)
9978 // Dispatched behavior.
9979 DECLARE_PRINTER(JSWeakSet)
9980 DECLARE_VERIFIER(JSWeakSet)
9983 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
9987 // Whether a JSArrayBuffer is a SharedArrayBuffer or not.
9988 enum class SharedFlag { kNotShared, kShared };
9991 class JSArrayBuffer: public JSObject {
9993 // [backing_store]: backing memory for this array
9994 DECL_ACCESSORS(backing_store, void)
9996 // [byte_length]: length in bytes
9997 DECL_ACCESSORS(byte_length, Object)
9999 inline uint32_t bit_field() const;
10000 inline void set_bit_field(uint32_t bits);
10002 inline bool is_external();
10003 inline void set_is_external(bool value);
10005 inline bool is_neuterable();
10006 inline void set_is_neuterable(bool value);
10008 inline bool was_neutered();
10009 inline void set_was_neutered(bool value);
10011 inline bool is_shared();
10012 inline void set_is_shared(bool value);
10014 DECLARE_CAST(JSArrayBuffer)
10018 // Dispatched behavior.
10019 DECLARE_PRINTER(JSArrayBuffer)
10020 DECLARE_VERIFIER(JSArrayBuffer)
10022 static const int kBackingStoreOffset = JSObject::kHeaderSize;
10023 static const int kByteLengthOffset = kBackingStoreOffset + kPointerSize;
10024 static const int kBitFieldSlot = kByteLengthOffset + kPointerSize;
10025 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
10026 static const int kBitFieldOffset = kBitFieldSlot;
10028 static const int kBitFieldOffset = kBitFieldSlot + kIntSize;
10030 static const int kSize = kBitFieldSlot + kPointerSize;
10032 static const int kSizeWithInternalFields =
10033 kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
10035 class IsExternal : public BitField<bool, 1, 1> {};
10036 class IsNeuterable : public BitField<bool, 2, 1> {};
10037 class WasNeutered : public BitField<bool, 3, 1> {};
10038 class IsShared : public BitField<bool, 4, 1> {};
10041 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
10045 class JSArrayBufferView: public JSObject {
10047 // [buffer]: ArrayBuffer that this typed array views.
10048 DECL_ACCESSORS(buffer, Object)
10050 // [byte_offset]: offset of typed array in bytes.
10051 DECL_ACCESSORS(byte_offset, Object)
10053 // [byte_length]: length of typed array in bytes.
10054 DECL_ACCESSORS(byte_length, Object)
10056 DECLARE_CAST(JSArrayBufferView)
10058 DECLARE_VERIFIER(JSArrayBufferView)
10060 inline bool WasNeutered() const;
10062 static const int kBufferOffset = JSObject::kHeaderSize;
10063 static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
10064 static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
10065 static const int kViewSize = kByteLengthOffset + kPointerSize;
10069 DECL_ACCESSORS(raw_byte_offset, Object)
10070 DECL_ACCESSORS(raw_byte_length, Object)
10073 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
10077 class JSTypedArray: public JSArrayBufferView {
10079 // [length]: length of typed array in elements.
10080 DECL_ACCESSORS(length, Object)
10081 inline uint32_t length_value() const;
10083 DECLARE_CAST(JSTypedArray)
10085 ExternalArrayType type();
10086 size_t element_size();
10088 Handle<JSArrayBuffer> GetBuffer();
10090 // Dispatched behavior.
10091 DECLARE_PRINTER(JSTypedArray)
10092 DECLARE_VERIFIER(JSTypedArray)
10094 static const int kLengthOffset = kViewSize + kPointerSize;
10095 static const int kSize = kLengthOffset + kPointerSize;
10097 static const int kSizeWithInternalFields =
10098 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
10101 static Handle<JSArrayBuffer> MaterializeArrayBuffer(
10102 Handle<JSTypedArray> typed_array);
10104 DECL_ACCESSORS(raw_length, Object)
10107 DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
10111 class JSDataView: public JSArrayBufferView {
10113 DECLARE_CAST(JSDataView)
10115 // Dispatched behavior.
10116 DECLARE_PRINTER(JSDataView)
10117 DECLARE_VERIFIER(JSDataView)
10119 static const int kSize = kViewSize;
10121 static const int kSizeWithInternalFields =
10122 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
10125 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
10129 // Foreign describes objects pointing from JavaScript to C structures.
10130 class Foreign: public HeapObject {
10132 // [address]: field containing the address.
10133 inline Address foreign_address();
10134 inline void set_foreign_address(Address value);
10136 DECLARE_CAST(Foreign)
10138 // Dispatched behavior.
10139 inline void ForeignIterateBody(ObjectVisitor* v);
10141 template<typename StaticVisitor>
10142 inline void ForeignIterateBody();
10144 // Dispatched behavior.
10145 DECLARE_PRINTER(Foreign)
10146 DECLARE_VERIFIER(Foreign)
10148 // Layout description.
10150 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
10151 static const int kSize = kForeignAddressOffset + kPointerSize;
10153 STATIC_ASSERT(kForeignAddressOffset == Internals::kForeignAddressOffset);
10156 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
10160 // The JSArray describes JavaScript Arrays
10161 // Such an array can be in one of two modes:
10162 // - fast, backing storage is a FixedArray and length <= elements.length();
10163 // Please note: push and pop can be used to grow and shrink the array.
10164 // - slow, backing storage is a HashTable with numbers as keys.
10165 class JSArray: public JSObject {
10167 // [length]: The length property.
10168 DECL_ACCESSORS(length, Object)
10170 // Overload the length setter to skip write barrier when the length
10171 // is set to a smi. This matches the set function on FixedArray.
10172 inline void set_length(Smi* length);
10174 static bool HasReadOnlyLength(Handle<JSArray> array);
10175 static bool WouldChangeReadOnlyLength(Handle<JSArray> array, uint32_t index);
10176 static MaybeHandle<Object> ReadOnlyLengthError(Handle<JSArray> array);
10178 // Initialize the array with the given capacity. The function may
10179 // fail due to out-of-memory situations, but only if the requested
10180 // capacity is non-zero.
10181 static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
10183 // If the JSArray has fast elements, and new_length would result in
10184 // normalization, returns true.
10185 bool SetLengthWouldNormalize(uint32_t new_length);
10186 static inline bool SetLengthWouldNormalize(Heap* heap, uint32_t new_length);
10188 // Initializes the array to a certain length.
10189 inline bool AllowsSetLength();
10191 static void SetLength(Handle<JSArray> array, uint32_t length);
10192 // Same as above but will also queue splice records if |array| is observed.
10193 static MaybeHandle<Object> ObservableSetLength(Handle<JSArray> array,
10196 // Set the content of the array to the content of storage.
10197 static inline void SetContent(Handle<JSArray> array,
10198 Handle<FixedArrayBase> storage);
10200 DECLARE_CAST(JSArray)
10202 // Dispatched behavior.
10203 DECLARE_PRINTER(JSArray)
10204 DECLARE_VERIFIER(JSArray)
10206 // Number of element slots to pre-allocate for an empty array.
10207 static const int kPreallocatedArrayElements = 4;
10209 // Layout description.
10210 static const int kLengthOffset = JSObject::kHeaderSize;
10211 static const int kSize = kLengthOffset + kPointerSize;
10214 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
10218 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
10219 Handle<Map> initial_map);
10222 // JSRegExpResult is just a JSArray with a specific initial map.
10223 // This initial map adds in-object properties for "index" and "input"
10224 // properties, as assigned by RegExp.prototype.exec, which allows
10225 // faster creation of RegExp exec results.
10226 // This class just holds constants used when creating the result.
10227 // After creation the result must be treated as a JSArray in all regards.
10228 class JSRegExpResult: public JSArray {
10230 // Offsets of object fields.
10231 static const int kIndexOffset = JSArray::kSize;
10232 static const int kInputOffset = kIndexOffset + kPointerSize;
10233 static const int kSize = kInputOffset + kPointerSize;
10234 // Indices of in-object properties.
10235 static const int kIndexIndex = 0;
10236 static const int kInputIndex = 1;
10238 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
10242 class AccessorInfo: public Struct {
10244 DECL_ACCESSORS(name, Object)
10245 DECL_ACCESSORS(flag, Smi)
10246 DECL_ACCESSORS(expected_receiver_type, Object)
10248 inline bool all_can_read();
10249 inline void set_all_can_read(bool value);
10251 inline bool all_can_write();
10252 inline void set_all_can_write(bool value);
10254 inline bool is_special_data_property();
10255 inline void set_is_special_data_property(bool value);
10257 inline PropertyAttributes property_attributes();
10258 inline void set_property_attributes(PropertyAttributes attributes);
10260 // Checks whether the given receiver is compatible with this accessor.
10261 static bool IsCompatibleReceiverMap(Isolate* isolate,
10262 Handle<AccessorInfo> info,
10264 inline bool IsCompatibleReceiver(Object* receiver);
10266 DECLARE_CAST(AccessorInfo)
10268 // Dispatched behavior.
10269 DECLARE_VERIFIER(AccessorInfo)
10271 // Append all descriptors to the array that are not already there.
10272 // Return number added.
10273 static int AppendUnique(Handle<Object> descriptors,
10274 Handle<FixedArray> array,
10275 int valid_descriptors);
10277 static const int kNameOffset = HeapObject::kHeaderSize;
10278 static const int kFlagOffset = kNameOffset + kPointerSize;
10279 static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
10280 static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
10283 inline bool HasExpectedReceiverType() {
10284 return expected_receiver_type()->IsFunctionTemplateInfo();
10286 // Bit positions in flag.
10287 static const int kAllCanReadBit = 0;
10288 static const int kAllCanWriteBit = 1;
10289 static const int kSpecialDataProperty = 2;
10290 class AttributesField : public BitField<PropertyAttributes, 3, 3> {};
10292 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
10296 // An accessor must have a getter, but can have no setter.
10298 // When setting a property, V8 searches accessors in prototypes.
10299 // If an accessor was found and it does not have a setter,
10300 // the request is ignored.
10302 // If the accessor in the prototype has the READ_ONLY property attribute, then
10303 // a new value is added to the derived object when the property is set.
10304 // This shadows the accessor in the prototype.
10305 class ExecutableAccessorInfo: public AccessorInfo {
10307 DECL_ACCESSORS(getter, Object)
10308 DECL_ACCESSORS(setter, Object)
10309 DECL_ACCESSORS(data, Object)
10311 DECLARE_CAST(ExecutableAccessorInfo)
10313 // Dispatched behavior.
10314 DECLARE_PRINTER(ExecutableAccessorInfo)
10315 DECLARE_VERIFIER(ExecutableAccessorInfo)
10317 static const int kGetterOffset = AccessorInfo::kSize;
10318 static const int kSetterOffset = kGetterOffset + kPointerSize;
10319 static const int kDataOffset = kSetterOffset + kPointerSize;
10320 static const int kSize = kDataOffset + kPointerSize;
10322 static void ClearSetter(Handle<ExecutableAccessorInfo> info);
10325 DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
10329 // Support for JavaScript accessors: A pair of a getter and a setter. Each
10330 // accessor can either be
10331 // * a pointer to a JavaScript function or proxy: a real accessor
10332 // * undefined: considered an accessor by the spec, too, strangely enough
10333 // * the hole: an accessor which has not been set
10334 // * a pointer to a map: a transition used to ensure map sharing
10335 class AccessorPair: public Struct {
10337 DECL_ACCESSORS(getter, Object)
10338 DECL_ACCESSORS(setter, Object)
10340 DECLARE_CAST(AccessorPair)
10342 static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
10344 Object* get(AccessorComponent component) {
10345 return component == ACCESSOR_GETTER ? getter() : setter();
10348 void set(AccessorComponent component, Object* value) {
10349 if (component == ACCESSOR_GETTER) {
10356 // Note: Returns undefined instead in case of a hole.
10357 Object* GetComponent(AccessorComponent component);
10359 // Set both components, skipping arguments which are a JavaScript null.
10360 void SetComponents(Object* getter, Object* setter) {
10361 if (!getter->IsNull()) set_getter(getter);
10362 if (!setter->IsNull()) set_setter(setter);
10365 bool Equals(AccessorPair* pair) {
10366 return (this == pair) || pair->Equals(getter(), setter());
10369 bool Equals(Object* getter_value, Object* setter_value) {
10370 return (getter() == getter_value) && (setter() == setter_value);
10373 bool ContainsAccessor() {
10374 return IsJSAccessor(getter()) || IsJSAccessor(setter());
10377 // Dispatched behavior.
10378 DECLARE_PRINTER(AccessorPair)
10379 DECLARE_VERIFIER(AccessorPair)
10381 static const int kGetterOffset = HeapObject::kHeaderSize;
10382 static const int kSetterOffset = kGetterOffset + kPointerSize;
10383 static const int kSize = kSetterOffset + kPointerSize;
10386 // Strangely enough, in addition to functions and harmony proxies, the spec
10387 // requires us to consider undefined as a kind of accessor, too:
10389 // Object.defineProperty(obj, "foo", {get: undefined});
10390 // assertTrue("foo" in obj);
10391 bool IsJSAccessor(Object* obj) {
10392 return obj->IsSpecFunction() || obj->IsUndefined();
10395 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
10399 class AccessCheckInfo: public Struct {
10401 DECL_ACCESSORS(named_callback, Object)
10402 DECL_ACCESSORS(indexed_callback, Object)
10403 DECL_ACCESSORS(data, Object)
10405 DECLARE_CAST(AccessCheckInfo)
10407 // Dispatched behavior.
10408 DECLARE_PRINTER(AccessCheckInfo)
10409 DECLARE_VERIFIER(AccessCheckInfo)
10411 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
10412 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
10413 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
10414 static const int kSize = kDataOffset + kPointerSize;
10417 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
10421 class InterceptorInfo: public Struct {
10423 DECL_ACCESSORS(getter, Object)
10424 DECL_ACCESSORS(setter, Object)
10425 DECL_ACCESSORS(query, Object)
10426 DECL_ACCESSORS(deleter, Object)
10427 DECL_ACCESSORS(enumerator, Object)
10428 DECL_ACCESSORS(data, Object)
10429 DECL_BOOLEAN_ACCESSORS(can_intercept_symbols)
10430 DECL_BOOLEAN_ACCESSORS(all_can_read)
10431 DECL_BOOLEAN_ACCESSORS(non_masking)
10433 inline int flags() const;
10434 inline void set_flags(int flags);
10436 DECLARE_CAST(InterceptorInfo)
10438 // Dispatched behavior.
10439 DECLARE_PRINTER(InterceptorInfo)
10440 DECLARE_VERIFIER(InterceptorInfo)
10442 static const int kGetterOffset = HeapObject::kHeaderSize;
10443 static const int kSetterOffset = kGetterOffset + kPointerSize;
10444 static const int kQueryOffset = kSetterOffset + kPointerSize;
10445 static const int kDeleterOffset = kQueryOffset + kPointerSize;
10446 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
10447 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
10448 static const int kFlagsOffset = kDataOffset + kPointerSize;
10449 static const int kSize = kFlagsOffset + kPointerSize;
10451 static const int kCanInterceptSymbolsBit = 0;
10452 static const int kAllCanReadBit = 1;
10453 static const int kNonMasking = 2;
10456 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
10460 class CallHandlerInfo: public Struct {
10462 DECL_ACCESSORS(callback, Object)
10463 DECL_ACCESSORS(data, Object)
10465 DECLARE_CAST(CallHandlerInfo)
10467 // Dispatched behavior.
10468 DECLARE_PRINTER(CallHandlerInfo)
10469 DECLARE_VERIFIER(CallHandlerInfo)
10471 static const int kCallbackOffset = HeapObject::kHeaderSize;
10472 static const int kDataOffset = kCallbackOffset + kPointerSize;
10473 static const int kSize = kDataOffset + kPointerSize;
10476 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
10480 class TemplateInfo: public Struct {
10482 DECL_ACCESSORS(tag, Object)
10483 inline int number_of_properties() const;
10484 inline void set_number_of_properties(int value);
10485 DECL_ACCESSORS(property_list, Object)
10486 DECL_ACCESSORS(property_accessors, Object)
10488 DECLARE_VERIFIER(TemplateInfo)
10490 static const int kTagOffset = HeapObject::kHeaderSize;
10491 static const int kNumberOfProperties = kTagOffset + kPointerSize;
10492 static const int kPropertyListOffset = kNumberOfProperties + kPointerSize;
10493 static const int kPropertyAccessorsOffset =
10494 kPropertyListOffset + kPointerSize;
10495 static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
10498 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
10502 class FunctionTemplateInfo: public TemplateInfo {
10504 DECL_ACCESSORS(serial_number, Object)
10505 DECL_ACCESSORS(call_code, Object)
10506 DECL_ACCESSORS(prototype_template, Object)
10507 DECL_ACCESSORS(parent_template, Object)
10508 DECL_ACCESSORS(named_property_handler, Object)
10509 DECL_ACCESSORS(indexed_property_handler, Object)
10510 DECL_ACCESSORS(instance_template, Object)
10511 DECL_ACCESSORS(class_name, Object)
10512 DECL_ACCESSORS(signature, Object)
10513 DECL_ACCESSORS(instance_call_handler, Object)
10514 DECL_ACCESSORS(access_check_info, Object)
10515 DECL_ACCESSORS(flag, Smi)
10517 inline int length() const;
10518 inline void set_length(int value);
10520 // Following properties use flag bits.
10521 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
10522 DECL_BOOLEAN_ACCESSORS(undetectable)
10523 // If the bit is set, object instances created by this function
10524 // requires access check.
10525 DECL_BOOLEAN_ACCESSORS(needs_access_check)
10526 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
10527 DECL_BOOLEAN_ACCESSORS(remove_prototype)
10528 DECL_BOOLEAN_ACCESSORS(do_not_cache)
10529 DECL_BOOLEAN_ACCESSORS(instantiated)
10530 DECL_BOOLEAN_ACCESSORS(accept_any_receiver)
10532 DECLARE_CAST(FunctionTemplateInfo)
10534 // Dispatched behavior.
10535 DECLARE_PRINTER(FunctionTemplateInfo)
10536 DECLARE_VERIFIER(FunctionTemplateInfo)
10538 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
10539 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
10540 static const int kPrototypeTemplateOffset =
10541 kCallCodeOffset + kPointerSize;
10542 static const int kParentTemplateOffset =
10543 kPrototypeTemplateOffset + kPointerSize;
10544 static const int kNamedPropertyHandlerOffset =
10545 kParentTemplateOffset + kPointerSize;
10546 static const int kIndexedPropertyHandlerOffset =
10547 kNamedPropertyHandlerOffset + kPointerSize;
10548 static const int kInstanceTemplateOffset =
10549 kIndexedPropertyHandlerOffset + kPointerSize;
10550 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
10551 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
10552 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
10553 static const int kAccessCheckInfoOffset =
10554 kInstanceCallHandlerOffset + kPointerSize;
10555 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
10556 static const int kLengthOffset = kFlagOffset + kPointerSize;
10557 static const int kSize = kLengthOffset + kPointerSize;
10559 // Returns true if |object| is an instance of this function template.
10560 bool IsTemplateFor(Object* object);
10561 bool IsTemplateFor(Map* map);
10563 // Returns the holder JSObject if the function can legally be called with this
10564 // receiver. Returns Heap::null_value() if the call is illegal.
10565 Object* GetCompatibleReceiver(Isolate* isolate, Object* receiver);
10568 // Bit position in the flag, from least significant bit position.
10569 static const int kHiddenPrototypeBit = 0;
10570 static const int kUndetectableBit = 1;
10571 static const int kNeedsAccessCheckBit = 2;
10572 static const int kReadOnlyPrototypeBit = 3;
10573 static const int kRemovePrototypeBit = 4;
10574 static const int kDoNotCacheBit = 5;
10575 static const int kInstantiatedBit = 6;
10576 static const int kAcceptAnyReceiver = 7;
10578 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
10582 class ObjectTemplateInfo: public TemplateInfo {
10584 DECL_ACCESSORS(constructor, Object)
10585 DECL_ACCESSORS(internal_field_count, Object)
10587 DECLARE_CAST(ObjectTemplateInfo)
10589 // Dispatched behavior.
10590 DECLARE_PRINTER(ObjectTemplateInfo)
10591 DECLARE_VERIFIER(ObjectTemplateInfo)
10593 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10594 static const int kInternalFieldCountOffset =
10595 kConstructorOffset + kPointerSize;
10596 static const int kSize = kInternalFieldCountOffset + kPointerSize;
10600 class TypeSwitchInfo: public Struct {
10602 DECL_ACCESSORS(types, Object)
10604 DECLARE_CAST(TypeSwitchInfo)
10606 // Dispatched behavior.
10607 DECLARE_PRINTER(TypeSwitchInfo)
10608 DECLARE_VERIFIER(TypeSwitchInfo)
10610 static const int kTypesOffset = Struct::kHeaderSize;
10611 static const int kSize = kTypesOffset + kPointerSize;
10615 // The DebugInfo class holds additional information for a function being
10617 class DebugInfo: public Struct {
10619 // The shared function info for the source being debugged.
10620 DECL_ACCESSORS(shared, SharedFunctionInfo)
10621 // Code object for the patched code. This code object is the code object
10622 // currently active for the function.
10623 DECL_ACCESSORS(code, Code)
10624 // Fixed array holding status information for each active break point.
10625 DECL_ACCESSORS(break_points, FixedArray)
10627 // Check if there is a break point at a code position.
10628 bool HasBreakPoint(int code_position);
10629 // Get the break point info object for a code position.
10630 Object* GetBreakPointInfo(int code_position);
10631 // Clear a break point.
10632 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
10634 Handle<Object> break_point_object);
10635 // Set a break point.
10636 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
10637 int source_position, int statement_position,
10638 Handle<Object> break_point_object);
10639 // Get the break point objects for a code position.
10640 Handle<Object> GetBreakPointObjects(int code_position);
10641 // Find the break point info holding this break point object.
10642 static Handle<Object> FindBreakPointInfo(Handle<DebugInfo> debug_info,
10643 Handle<Object> break_point_object);
10644 // Get the number of break points for this function.
10645 int GetBreakPointCount();
10647 DECLARE_CAST(DebugInfo)
10649 // Dispatched behavior.
10650 DECLARE_PRINTER(DebugInfo)
10651 DECLARE_VERIFIER(DebugInfo)
10653 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
10654 static const int kCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
10655 static const int kBreakPointsStateIndex = kCodeIndex + kPointerSize;
10656 static const int kSize = kBreakPointsStateIndex + kPointerSize;
10658 static const int kEstimatedNofBreakPointsInFunction = 16;
10661 static const int kNoBreakPointInfo = -1;
10663 // Lookup the index in the break_points array for a code position.
10664 int GetBreakPointInfoIndex(int code_position);
10666 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
10670 // The BreakPointInfo class holds information for break points set in a
10671 // function. The DebugInfo object holds a BreakPointInfo object for each code
10672 // position with one or more break points.
10673 class BreakPointInfo: public Struct {
10675 // The position in the code for the break point.
10676 DECL_ACCESSORS(code_position, Smi)
10677 // The position in the source for the break position.
10678 DECL_ACCESSORS(source_position, Smi)
10679 // The position in the source for the last statement before this break
10681 DECL_ACCESSORS(statement_position, Smi)
10682 // List of related JavaScript break points.
10683 DECL_ACCESSORS(break_point_objects, Object)
10685 // Removes a break point.
10686 static void ClearBreakPoint(Handle<BreakPointInfo> info,
10687 Handle<Object> break_point_object);
10688 // Set a break point.
10689 static void SetBreakPoint(Handle<BreakPointInfo> info,
10690 Handle<Object> break_point_object);
10691 // Check if break point info has this break point object.
10692 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
10693 Handle<Object> break_point_object);
10694 // Get the number of break points for this code position.
10695 int GetBreakPointCount();
10697 DECLARE_CAST(BreakPointInfo)
10699 // Dispatched behavior.
10700 DECLARE_PRINTER(BreakPointInfo)
10701 DECLARE_VERIFIER(BreakPointInfo)
10703 static const int kCodePositionIndex = Struct::kHeaderSize;
10704 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
10705 static const int kStatementPositionIndex =
10706 kSourcePositionIndex + kPointerSize;
10707 static const int kBreakPointObjectsIndex =
10708 kStatementPositionIndex + kPointerSize;
10709 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
10712 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
10716 #undef DECL_BOOLEAN_ACCESSORS
10717 #undef DECL_ACCESSORS
10718 #undef DECLARE_CAST
10719 #undef DECLARE_VERIFIER
10721 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
10722 V(kStringTable, "string_table", "(Internalized strings)") \
10723 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
10724 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
10725 V(kSmiRootList, "smi_root_list", "(Smi roots)") \
10726 V(kInternalizedString, "internalized_string", "(Internal string)") \
10727 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
10728 V(kTop, "top", "(Isolate)") \
10729 V(kRelocatable, "relocatable", "(Relocatable)") \
10730 V(kDebug, "debug", "(Debugger)") \
10731 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
10732 V(kHandleScope, "handlescope", "(Handle scope)") \
10733 V(kBuiltins, "builtins", "(Builtins)") \
10734 V(kGlobalHandles, "globalhandles", "(Global handles)") \
10735 V(kEternalHandles, "eternalhandles", "(Eternal handles)") \
10736 V(kThreadManager, "threadmanager", "(Thread manager)") \
10737 V(kStrongRoots, "strong roots", "(Strong roots)") \
10738 V(kExtensions, "Extensions", "(Extensions)")
10740 class VisitorSynchronization : public AllStatic {
10742 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
10744 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
10747 #undef DECLARE_ENUM
10749 static const char* const kTags[kNumberOfSyncTags];
10750 static const char* const kTagNames[kNumberOfSyncTags];
10753 // Abstract base class for visiting, and optionally modifying, the
10754 // pointers contained in Objects. Used in GC and serialization/deserialization.
10755 class ObjectVisitor BASE_EMBEDDED {
10757 virtual ~ObjectVisitor() {}
10759 // Visits a contiguous arrays of pointers in the half-open range
10760 // [start, end). Any or all of the values may be modified on return.
10761 virtual void VisitPointers(Object** start, Object** end) = 0;
10763 // Handy shorthand for visiting a single pointer.
10764 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
10766 // Visit weak next_code_link in Code object.
10767 virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
10769 // To allow lazy clearing of inline caches the visitor has
10770 // a rich interface for iterating over Code objects..
10772 // Visits a code target in the instruction stream.
10773 virtual void VisitCodeTarget(RelocInfo* rinfo);
10775 // Visits a code entry in a JS function.
10776 virtual void VisitCodeEntry(Address entry_address);
10778 // Visits a global property cell reference in the instruction stream.
10779 virtual void VisitCell(RelocInfo* rinfo);
10781 // Visits a runtime entry in the instruction stream.
10782 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
10784 // Visits the resource of an one-byte or two-byte string.
10785 virtual void VisitExternalOneByteString(
10786 v8::String::ExternalOneByteStringResource** resource) {}
10787 virtual void VisitExternalTwoByteString(
10788 v8::String::ExternalStringResource** resource) {}
10790 // Visits a debug call target in the instruction stream.
10791 virtual void VisitDebugTarget(RelocInfo* rinfo);
10793 // Visits the byte sequence in a function's prologue that contains information
10794 // about the code's age.
10795 virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
10797 // Visit pointer embedded into a code object.
10798 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
10800 // Visits an external reference embedded into a code object.
10801 virtual void VisitExternalReference(RelocInfo* rinfo);
10803 // Visits an external reference.
10804 virtual void VisitExternalReference(Address* p) {}
10806 // Visits an (encoded) internal reference.
10807 virtual void VisitInternalReference(RelocInfo* rinfo) {}
10809 // Visits a handle that has an embedder-assigned class ID.
10810 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
10812 // Intended for serialization/deserialization checking: insert, or
10813 // check for the presence of, a tag at this position in the stream.
10814 // Also used for marking up GC roots in heap snapshots.
10815 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
10819 class StructBodyDescriptor : public
10820 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
10822 static inline int SizeOf(Map* map, HeapObject* object) {
10823 return map->instance_size();
10828 // BooleanBit is a helper class for setting and getting a bit in an
10830 class BooleanBit : public AllStatic {
10832 static inline bool get(Smi* smi, int bit_position) {
10833 return get(smi->value(), bit_position);
10836 static inline bool get(int value, int bit_position) {
10837 return (value & (1 << bit_position)) != 0;
10840 static inline Smi* set(Smi* smi, int bit_position, bool v) {
10841 return Smi::FromInt(set(smi->value(), bit_position, v));
10844 static inline int set(int value, int bit_position, bool v) {
10846 value |= (1 << bit_position);
10848 value &= ~(1 << bit_position);
10854 } } // namespace v8::internal
10856 #endif // V8_OBJECTS_H_