1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
6 // * Redistributions of source code must retain the above copyright
7 // notice, this list of conditions and the following disclaimer.
8 // * Redistributions in binary form must reproduce the above
9 // copyright notice, this list of conditions and the following
10 // disclaimer in the documentation and/or other materials provided
11 // with the distribution.
12 // * Neither the name of Google Inc. nor the names of its
13 // contributors may be used to endorse or promote products derived
14 // from this software without specific prior written permission.
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 #include "allocation.h"
32 #include "assert-scope.h"
34 #include "elements-kind.h"
37 #include "property-details.h"
38 #include "smart-pointers.h"
39 #include "unicode-inl.h"
40 #if V8_TARGET_ARCH_ARM
41 #include "arm/constants-arm.h"
42 #elif V8_TARGET_ARCH_MIPS
43 #include "mips/constants-mips.h"
50 // Most object types in the V8 JavaScript are described in this file.
52 // Inheritance hierarchy:
53 // - MaybeObject (an object or a failure)
54 // - Failure (immediate for marking failed operation)
56 // - Smi (immediate small integer)
57 // - HeapObject (superclass for everything allocated in the heap)
58 // - JSReceiver (suitable for property access)
62 // - JSArrayBufferView
72 // - JSGeneratorObject
90 // - CompilationCacheTable
91 // - CodeCacheHashTable
94 // - JSFunctionResultCache
99 // - ExternalUint8ClampedArray
100 // - ExternalInt8Array
101 // - ExternalUint8Array
102 // - ExternalInt16Array
103 // - ExternalUint16Array
104 // - ExternalInt32Array
105 // - ExternalUint32Array
106 // - ExternalFloat32Array
107 // - ExternalFloat32x4Array
108 // - ExternalInt32x4Array
112 // - SeqOneByteString
113 // - SeqTwoByteString
117 // - ExternalAsciiString
118 // - ExternalTwoByteString
119 // - InternalizedString
120 // - SeqInternalizedString
121 // - SeqOneByteInternalizedString
122 // - SeqTwoByteInternalizedString
123 // - ConsInternalizedString
124 // - ExternalInternalizedString
125 // - ExternalAsciiInternalizedString
126 // - ExternalTwoByteInternalizedString
137 // - SharedFunctionInfo
140 // - DeclaredAccessorDescriptor
142 // - DeclaredAccessorInfo
143 // - ExecutableAccessorInfo
149 // - FunctionTemplateInfo
150 // - ObjectTemplateInfo
158 // Formats of Object*:
159 // Smi: [31 bit signed int] 0
160 // HeapObject: [32 bit direct pointer] (4 byte aligned) | 01
161 // Failure: [30 bit signed int] 11
166 enum KeyedAccessStoreMode {
168 STORE_TRANSITION_SMI_TO_OBJECT,
169 STORE_TRANSITION_SMI_TO_DOUBLE,
170 STORE_TRANSITION_DOUBLE_TO_OBJECT,
171 STORE_TRANSITION_HOLEY_SMI_TO_OBJECT,
172 STORE_TRANSITION_HOLEY_SMI_TO_DOUBLE,
173 STORE_TRANSITION_HOLEY_DOUBLE_TO_OBJECT,
174 STORE_AND_GROW_NO_TRANSITION,
175 STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT,
176 STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE,
177 STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT,
178 STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_OBJECT,
179 STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_DOUBLE,
180 STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT,
181 STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS,
182 STORE_NO_TRANSITION_HANDLE_COW
186 enum ContextualMode {
192 static const int kGrowICDelta = STORE_AND_GROW_NO_TRANSITION -
194 STATIC_ASSERT(STANDARD_STORE == 0);
195 STATIC_ASSERT(kGrowICDelta ==
196 STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT -
197 STORE_TRANSITION_SMI_TO_OBJECT);
198 STATIC_ASSERT(kGrowICDelta ==
199 STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE -
200 STORE_TRANSITION_SMI_TO_DOUBLE);
201 STATIC_ASSERT(kGrowICDelta ==
202 STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT -
203 STORE_TRANSITION_DOUBLE_TO_OBJECT);
206 static inline KeyedAccessStoreMode GetGrowStoreMode(
207 KeyedAccessStoreMode store_mode) {
208 if (store_mode < STORE_AND_GROW_NO_TRANSITION) {
209 store_mode = static_cast<KeyedAccessStoreMode>(
210 static_cast<int>(store_mode) + kGrowICDelta);
216 static inline bool IsTransitionStoreMode(KeyedAccessStoreMode store_mode) {
217 return store_mode > STANDARD_STORE &&
218 store_mode <= STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT &&
219 store_mode != STORE_AND_GROW_NO_TRANSITION;
223 static inline KeyedAccessStoreMode GetNonTransitioningStoreMode(
224 KeyedAccessStoreMode store_mode) {
225 if (store_mode >= STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS) {
228 if (store_mode >= STORE_AND_GROW_NO_TRANSITION) {
229 return STORE_AND_GROW_NO_TRANSITION;
231 return STANDARD_STORE;
235 static inline bool IsGrowStoreMode(KeyedAccessStoreMode store_mode) {
236 return store_mode >= STORE_AND_GROW_NO_TRANSITION &&
237 store_mode <= STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT;
241 // Setter that skips the write barrier if mode is SKIP_WRITE_BARRIER.
242 enum WriteBarrierMode { SKIP_WRITE_BARRIER, UPDATE_WRITE_BARRIER };
245 // Indicates whether a value can be loaded as a constant.
252 // PropertyNormalizationMode is used to specify whether to keep
253 // inobject properties when normalizing properties of a JSObject.
254 enum PropertyNormalizationMode {
255 CLEAR_INOBJECT_PROPERTIES,
256 KEEP_INOBJECT_PROPERTIES
260 // NormalizedMapSharingMode is used to specify whether a map may be shared
261 // by different objects with normalized properties.
262 enum NormalizedMapSharingMode {
263 UNIQUE_NORMALIZED_MAP,
264 SHARED_NORMALIZED_MAP
268 // Indicates whether transitions can be added to a source map or not.
269 enum TransitionFlag {
275 enum DebugExtraICState {
277 DEBUG_PREPARE_STEP_IN
281 // Indicates whether the transition is simple: the target map of the transition
282 // either extends the current map with a new property, or it modifies the
283 // property that was added last to the current map.
284 enum SimpleTransitionFlag {
290 // Indicates whether we are only interested in the descriptors of a particular
291 // map, or in all descriptors in the descriptor array.
292 enum DescriptorFlag {
297 // The GC maintains a bit of information, the MarkingParity, which toggles
298 // from odd to even and back every time marking is completed. Incremental
299 // marking can visit an object twice during a marking phase, so algorithms that
300 // that piggy-back on marking can use the parity to ensure that they only
301 // perform an operation on an object once per marking phase: they record the
302 // MarkingParity when they visit an object, and only re-visit the object when it
303 // is marked again and the MarkingParity changes.
310 // ICs store extra state in a Code object. The default extra state is
312 typedef int ExtraICState;
313 static const ExtraICState kNoExtraICState = 0;
315 // Instance size sentinel for objects of variable size.
316 const int kVariableSizeSentinel = 0;
318 const int kStubMajorKeyBits = 7;
319 const int kStubMinorKeyBits = kBitsPerInt - kSmiTagSize - kStubMajorKeyBits;
321 // All Maps have a field instance_type containing a InstanceType.
322 // It describes the type of the instances.
324 // As an example, a JavaScript object is a heap object and its map
325 // instance_type is JS_OBJECT_TYPE.
327 // The names of the string instance types are intended to systematically
328 // mirror their encoding in the instance_type field of the map. The default
329 // encoding is considered TWO_BYTE. It is not mentioned in the name. ASCII
330 // encoding is mentioned explicitly in the name. Likewise, the default
331 // representation is considered sequential. It is not mentioned in the
332 // name. The other representations (e.g. CONS, EXTERNAL) are explicitly
333 // mentioned. Finally, the string is either a STRING_TYPE (if it is a normal
334 // string) or a INTERNALIZED_STRING_TYPE (if it is a internalized string).
336 // NOTE: The following things are some that depend on the string types having
337 // instance_types that are less than those of all other types:
338 // HeapObject::Size, HeapObject::IterateBody, the typeof operator, and
341 // NOTE: Everything following JS_VALUE_TYPE is considered a
342 // JSObject for GC purposes. The first four entries here have typeof
343 // 'object', whereas JS_FUNCTION_TYPE has typeof 'function'.
344 #define INSTANCE_TYPE_LIST(V) \
346 V(ASCII_STRING_TYPE) \
347 V(CONS_STRING_TYPE) \
348 V(CONS_ASCII_STRING_TYPE) \
349 V(SLICED_STRING_TYPE) \
350 V(SLICED_ASCII_STRING_TYPE) \
351 V(EXTERNAL_STRING_TYPE) \
352 V(EXTERNAL_ASCII_STRING_TYPE) \
353 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
354 V(SHORT_EXTERNAL_STRING_TYPE) \
355 V(SHORT_EXTERNAL_ASCII_STRING_TYPE) \
356 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
358 V(INTERNALIZED_STRING_TYPE) \
359 V(ASCII_INTERNALIZED_STRING_TYPE) \
360 V(CONS_INTERNALIZED_STRING_TYPE) \
361 V(CONS_ASCII_INTERNALIZED_STRING_TYPE) \
362 V(EXTERNAL_INTERNALIZED_STRING_TYPE) \
363 V(EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE) \
364 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
365 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE) \
366 V(SHORT_EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE) \
367 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
375 V(PROPERTY_CELL_TYPE) \
377 V(HEAP_NUMBER_TYPE) \
383 /* Note: the order of these external array */ \
384 /* types is relied upon in */ \
385 /* Object::IsExternalArray(). */ \
386 V(EXTERNAL_INT8_ARRAY_TYPE) \
387 V(EXTERNAL_UINT8_ARRAY_TYPE) \
388 V(EXTERNAL_INT16_ARRAY_TYPE) \
389 V(EXTERNAL_UINT16_ARRAY_TYPE) \
390 V(EXTERNAL_INT32_ARRAY_TYPE) \
391 V(EXTERNAL_UINT32_ARRAY_TYPE) \
392 V(EXTERNAL_FLOAT32_ARRAY_TYPE) \
393 V(EXTERNAL_FLOAT32x4_ARRAY_TYPE) \
394 V(EXTERNAL_INT32x4_ARRAY_TYPE) \
395 V(EXTERNAL_FLOAT64_ARRAY_TYPE) \
396 V(EXTERNAL_UINT8_CLAMPED_ARRAY_TYPE) \
398 V(FIXED_INT8_ARRAY_TYPE) \
399 V(FIXED_UINT8_ARRAY_TYPE) \
400 V(FIXED_INT16_ARRAY_TYPE) \
401 V(FIXED_UINT16_ARRAY_TYPE) \
402 V(FIXED_INT32_ARRAY_TYPE) \
403 V(FIXED_INT32x4_ARRAY_TYPE) \
404 V(FIXED_UINT32_ARRAY_TYPE) \
405 V(FIXED_FLOAT32_ARRAY_TYPE) \
406 V(FIXED_FLOAT32x4_ARRAY_TYPE) \
407 V(FIXED_FLOAT64_ARRAY_TYPE) \
408 V(FIXED_UINT8_CLAMPED_ARRAY_TYPE) \
412 V(DECLARED_ACCESSOR_DESCRIPTOR_TYPE) \
413 V(DECLARED_ACCESSOR_INFO_TYPE) \
414 V(EXECUTABLE_ACCESSOR_INFO_TYPE) \
415 V(ACCESSOR_PAIR_TYPE) \
416 V(ACCESS_CHECK_INFO_TYPE) \
417 V(INTERCEPTOR_INFO_TYPE) \
418 V(CALL_HANDLER_INFO_TYPE) \
419 V(FUNCTION_TEMPLATE_INFO_TYPE) \
420 V(OBJECT_TEMPLATE_INFO_TYPE) \
421 V(SIGNATURE_INFO_TYPE) \
422 V(TYPE_SWITCH_INFO_TYPE) \
423 V(ALLOCATION_MEMENTO_TYPE) \
424 V(ALLOCATION_SITE_TYPE) \
427 V(POLYMORPHIC_CODE_CACHE_TYPE) \
428 V(TYPE_FEEDBACK_INFO_TYPE) \
429 V(ALIASED_ARGUMENTS_ENTRY_TYPE) \
432 V(FIXED_ARRAY_TYPE) \
433 V(FIXED_DOUBLE_ARRAY_TYPE) \
434 V(CONSTANT_POOL_ARRAY_TYPE) \
435 V(SHARED_FUNCTION_INFO_TYPE) \
437 V(JS_MESSAGE_OBJECT_TYPE) \
442 V(JS_CONTEXT_EXTENSION_OBJECT_TYPE) \
443 V(JS_GENERATOR_OBJECT_TYPE) \
445 V(JS_GLOBAL_OBJECT_TYPE) \
446 V(JS_BUILTINS_OBJECT_TYPE) \
447 V(JS_GLOBAL_PROXY_TYPE) \
449 V(JS_ARRAY_BUFFER_TYPE) \
450 V(JS_TYPED_ARRAY_TYPE) \
451 V(JS_DATA_VIEW_TYPE) \
455 V(JS_WEAK_MAP_TYPE) \
456 V(JS_WEAK_SET_TYPE) \
459 V(JS_FUNCTION_TYPE) \
460 V(JS_FUNCTION_PROXY_TYPE) \
462 V(BREAK_POINT_INFO_TYPE)
465 // Since string types are not consecutive, this macro is used to
466 // iterate over them.
467 #define STRING_TYPE_LIST(V) \
469 kVariableSizeSentinel, \
472 V(ASCII_STRING_TYPE, \
473 kVariableSizeSentinel, \
476 V(CONS_STRING_TYPE, \
480 V(CONS_ASCII_STRING_TYPE, \
484 V(SLICED_STRING_TYPE, \
485 SlicedString::kSize, \
488 V(SLICED_ASCII_STRING_TYPE, \
489 SlicedString::kSize, \
490 sliced_ascii_string, \
492 V(EXTERNAL_STRING_TYPE, \
493 ExternalTwoByteString::kSize, \
496 V(EXTERNAL_ASCII_STRING_TYPE, \
497 ExternalAsciiString::kSize, \
498 external_ascii_string, \
499 ExternalAsciiString) \
500 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, \
501 ExternalTwoByteString::kSize, \
502 external_string_with_one_byte_data, \
503 ExternalStringWithOneByteData) \
504 V(SHORT_EXTERNAL_STRING_TYPE, \
505 ExternalTwoByteString::kShortSize, \
506 short_external_string, \
507 ShortExternalString) \
508 V(SHORT_EXTERNAL_ASCII_STRING_TYPE, \
509 ExternalAsciiString::kShortSize, \
510 short_external_ascii_string, \
511 ShortExternalAsciiString) \
512 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, \
513 ExternalTwoByteString::kShortSize, \
514 short_external_string_with_one_byte_data, \
515 ShortExternalStringWithOneByteData) \
517 V(INTERNALIZED_STRING_TYPE, \
518 kVariableSizeSentinel, \
519 internalized_string, \
520 InternalizedString) \
521 V(ASCII_INTERNALIZED_STRING_TYPE, \
522 kVariableSizeSentinel, \
523 ascii_internalized_string, \
524 AsciiInternalizedString) \
525 V(CONS_INTERNALIZED_STRING_TYPE, \
527 cons_internalized_string, \
528 ConsInternalizedString) \
529 V(CONS_ASCII_INTERNALIZED_STRING_TYPE, \
531 cons_ascii_internalized_string, \
532 ConsAsciiInternalizedString) \
533 V(EXTERNAL_INTERNALIZED_STRING_TYPE, \
534 ExternalTwoByteString::kSize, \
535 external_internalized_string, \
536 ExternalInternalizedString) \
537 V(EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE, \
538 ExternalAsciiString::kSize, \
539 external_ascii_internalized_string, \
540 ExternalAsciiInternalizedString) \
541 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
542 ExternalTwoByteString::kSize, \
543 external_internalized_string_with_one_byte_data, \
544 ExternalInternalizedStringWithOneByteData) \
545 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE, \
546 ExternalTwoByteString::kShortSize, \
547 short_external_internalized_string, \
548 ShortExternalInternalizedString) \
549 V(SHORT_EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE, \
550 ExternalAsciiString::kShortSize, \
551 short_external_ascii_internalized_string, \
552 ShortExternalAsciiInternalizedString) \
553 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
554 ExternalTwoByteString::kShortSize, \
555 short_external_internalized_string_with_one_byte_data, \
556 ShortExternalInternalizedStringWithOneByteData) \
558 // A struct is a simple object a set of object-valued fields. Including an
559 // object type in this causes the compiler to generate most of the boilerplate
560 // code for the class including allocation and garbage collection routines,
561 // casts and predicates. All you need to define is the class, methods and
562 // object verification routines. Easy, no?
564 // Note that for subtle reasons related to the ordering or numerical values of
565 // type tags, elements in this list have to be added to the INSTANCE_TYPE_LIST
567 #define STRUCT_LIST_ALL(V) \
569 V(DECLARED_ACCESSOR_DESCRIPTOR, \
570 DeclaredAccessorDescriptor, \
571 declared_accessor_descriptor) \
572 V(DECLARED_ACCESSOR_INFO, DeclaredAccessorInfo, declared_accessor_info) \
573 V(EXECUTABLE_ACCESSOR_INFO, ExecutableAccessorInfo, executable_accessor_info)\
574 V(ACCESSOR_PAIR, AccessorPair, accessor_pair) \
575 V(ACCESS_CHECK_INFO, AccessCheckInfo, access_check_info) \
576 V(INTERCEPTOR_INFO, InterceptorInfo, interceptor_info) \
577 V(CALL_HANDLER_INFO, CallHandlerInfo, call_handler_info) \
578 V(FUNCTION_TEMPLATE_INFO, FunctionTemplateInfo, function_template_info) \
579 V(OBJECT_TEMPLATE_INFO, ObjectTemplateInfo, object_template_info) \
580 V(SIGNATURE_INFO, SignatureInfo, signature_info) \
581 V(TYPE_SWITCH_INFO, TypeSwitchInfo, type_switch_info) \
582 V(SCRIPT, Script, script) \
583 V(ALLOCATION_SITE, AllocationSite, allocation_site) \
584 V(ALLOCATION_MEMENTO, AllocationMemento, allocation_memento) \
585 V(CODE_CACHE, CodeCache, code_cache) \
586 V(POLYMORPHIC_CODE_CACHE, PolymorphicCodeCache, polymorphic_code_cache) \
587 V(TYPE_FEEDBACK_INFO, TypeFeedbackInfo, type_feedback_info) \
588 V(ALIASED_ARGUMENTS_ENTRY, AliasedArgumentsEntry, aliased_arguments_entry)
590 #ifdef ENABLE_DEBUGGER_SUPPORT
591 #define STRUCT_LIST_DEBUGGER(V) \
592 V(DEBUG_INFO, DebugInfo, debug_info) \
593 V(BREAK_POINT_INFO, BreakPointInfo, break_point_info)
595 #define STRUCT_LIST_DEBUGGER(V)
598 #define STRUCT_LIST(V) \
600 STRUCT_LIST_DEBUGGER(V)
602 // We use the full 8 bits of the instance_type field to encode heap object
603 // instance types. The high-order bit (bit 7) is set if the object is not a
604 // string, and cleared if it is a string.
605 const uint32_t kIsNotStringMask = 0x80;
606 const uint32_t kStringTag = 0x0;
607 const uint32_t kNotStringTag = 0x80;
609 // Bit 6 indicates that the object is an internalized string (if set) or not.
610 // Bit 7 has to be clear as well.
611 const uint32_t kIsNotInternalizedMask = 0x40;
612 const uint32_t kNotInternalizedTag = 0x40;
613 const uint32_t kInternalizedTag = 0x0;
615 // If bit 7 is clear then bit 2 indicates whether the string consists of
616 // two-byte characters or one-byte characters.
617 const uint32_t kStringEncodingMask = 0x4;
618 const uint32_t kTwoByteStringTag = 0x0;
619 const uint32_t kOneByteStringTag = 0x4;
621 // If bit 7 is clear, the low-order 2 bits indicate the representation
623 const uint32_t kStringRepresentationMask = 0x03;
624 enum StringRepresentationTag {
626 kConsStringTag = 0x1,
627 kExternalStringTag = 0x2,
628 kSlicedStringTag = 0x3
630 const uint32_t kIsIndirectStringMask = 0x1;
631 const uint32_t kIsIndirectStringTag = 0x1;
632 STATIC_ASSERT((kSeqStringTag & kIsIndirectStringMask) == 0);
633 STATIC_ASSERT((kExternalStringTag & kIsIndirectStringMask) == 0);
635 (kConsStringTag & kIsIndirectStringMask) == kIsIndirectStringTag);
637 (kSlicedStringTag & kIsIndirectStringMask) == kIsIndirectStringTag);
639 // Use this mask to distinguish between cons and slice only after making
640 // sure that the string is one of the two (an indirect string).
641 const uint32_t kSlicedNotConsMask = kSlicedStringTag & ~kConsStringTag;
642 STATIC_ASSERT(IS_POWER_OF_TWO(kSlicedNotConsMask) && kSlicedNotConsMask != 0);
644 // If bit 7 is clear, then bit 3 indicates whether this two-byte
645 // string actually contains one byte data.
646 const uint32_t kOneByteDataHintMask = 0x08;
647 const uint32_t kOneByteDataHintTag = 0x08;
649 // If bit 7 is clear and string representation indicates an external string,
650 // then bit 4 indicates whether the data pointer is cached.
651 const uint32_t kShortExternalStringMask = 0x10;
652 const uint32_t kShortExternalStringTag = 0x10;
655 // A ConsString with an empty string as the right side is a candidate
656 // for being shortcut by the garbage collector unless it is internalized.
657 // It's not common to have non-flat internalized strings, so we do not
658 // shortcut them thereby avoiding turning internalized strings into strings.
659 // See heap.cc and mark-compact.cc.
660 const uint32_t kShortcutTypeMask =
662 kIsNotInternalizedMask |
663 kStringRepresentationMask;
664 const uint32_t kShortcutTypeTag = kConsStringTag | kNotInternalizedTag;
669 INTERNALIZED_STRING_TYPE = kTwoByteStringTag | kSeqStringTag
671 ASCII_INTERNALIZED_STRING_TYPE = kOneByteStringTag | kSeqStringTag
673 CONS_INTERNALIZED_STRING_TYPE = kTwoByteStringTag | kConsStringTag
675 CONS_ASCII_INTERNALIZED_STRING_TYPE = kOneByteStringTag | kConsStringTag
677 EXTERNAL_INTERNALIZED_STRING_TYPE = kTwoByteStringTag | kExternalStringTag
679 EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE = kOneByteStringTag
680 | kExternalStringTag | kInternalizedTag,
681 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
682 EXTERNAL_INTERNALIZED_STRING_TYPE | kOneByteDataHintTag
684 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE =
685 EXTERNAL_INTERNALIZED_STRING_TYPE | kShortExternalStringTag
687 SHORT_EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE =
688 EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE | kShortExternalStringTag
690 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
691 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE
692 | kShortExternalStringTag | kInternalizedTag,
694 STRING_TYPE = INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
695 ASCII_STRING_TYPE = ASCII_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
696 CONS_STRING_TYPE = CONS_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
697 CONS_ASCII_STRING_TYPE =
698 CONS_ASCII_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
701 kTwoByteStringTag | kSlicedStringTag | kNotInternalizedTag,
702 SLICED_ASCII_STRING_TYPE =
703 kOneByteStringTag | kSlicedStringTag | kNotInternalizedTag,
704 EXTERNAL_STRING_TYPE =
705 EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
706 EXTERNAL_ASCII_STRING_TYPE =
707 EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
708 EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
709 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE
710 | kNotInternalizedTag,
711 SHORT_EXTERNAL_STRING_TYPE =
712 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
713 SHORT_EXTERNAL_ASCII_STRING_TYPE =
714 SHORT_EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
715 SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
716 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE
717 | kNotInternalizedTag,
720 SYMBOL_TYPE = kNotStringTag, // FIRST_NONSTRING_TYPE, LAST_NAME_TYPE
722 // Objects allocated in their own spaces (never in new space).
729 // "Data", objects that cannot contain non-map-word pointers to heap
738 EXTERNAL_INT8_ARRAY_TYPE, // FIRST_EXTERNAL_ARRAY_TYPE
739 EXTERNAL_UINT8_ARRAY_TYPE,
740 EXTERNAL_INT16_ARRAY_TYPE,
741 EXTERNAL_UINT16_ARRAY_TYPE,
742 EXTERNAL_INT32_ARRAY_TYPE,
743 EXTERNAL_UINT32_ARRAY_TYPE,
744 EXTERNAL_FLOAT32_ARRAY_TYPE,
745 EXTERNAL_FLOAT32x4_ARRAY_TYPE,
746 EXTERNAL_INT32x4_ARRAY_TYPE,
747 EXTERNAL_FLOAT64_ARRAY_TYPE,
748 EXTERNAL_UINT8_CLAMPED_ARRAY_TYPE, // LAST_EXTERNAL_ARRAY_TYPE
750 FIXED_INT8_ARRAY_TYPE, // FIRST_FIXED_TYPED_ARRAY_TYPE
751 FIXED_UINT8_ARRAY_TYPE,
752 FIXED_INT16_ARRAY_TYPE,
753 FIXED_UINT16_ARRAY_TYPE,
754 FIXED_INT32_ARRAY_TYPE,
755 FIXED_INT32x4_ARRAY_TYPE,
756 FIXED_UINT32_ARRAY_TYPE,
757 FIXED_FLOAT32_ARRAY_TYPE,
758 FIXED_FLOAT32x4_ARRAY_TYPE,
759 FIXED_FLOAT64_ARRAY_TYPE,
760 FIXED_UINT8_CLAMPED_ARRAY_TYPE, // LAST_FIXED_TYPED_ARRAY_TYPE
762 FIXED_DOUBLE_ARRAY_TYPE,
763 FILLER_TYPE, // LAST_DATA_TYPE
766 DECLARED_ACCESSOR_DESCRIPTOR_TYPE,
767 DECLARED_ACCESSOR_INFO_TYPE,
768 EXECUTABLE_ACCESSOR_INFO_TYPE,
770 ACCESS_CHECK_INFO_TYPE,
771 INTERCEPTOR_INFO_TYPE,
772 CALL_HANDLER_INFO_TYPE,
773 FUNCTION_TEMPLATE_INFO_TYPE,
774 OBJECT_TEMPLATE_INFO_TYPE,
776 TYPE_SWITCH_INFO_TYPE,
777 ALLOCATION_SITE_TYPE,
778 ALLOCATION_MEMENTO_TYPE,
781 POLYMORPHIC_CODE_CACHE_TYPE,
782 TYPE_FEEDBACK_INFO_TYPE,
783 ALIASED_ARGUMENTS_ENTRY_TYPE,
785 // The following two instance types are only used when ENABLE_DEBUGGER_SUPPORT
786 // is defined. However as include/v8.h contain some of the instance type
787 // constants always having them avoids them getting different numbers
788 // depending on whether ENABLE_DEBUGGER_SUPPORT is defined or not.
790 BREAK_POINT_INFO_TYPE,
793 CONSTANT_POOL_ARRAY_TYPE,
794 SHARED_FUNCTION_INFO_TYPE,
796 JS_MESSAGE_OBJECT_TYPE,
798 // All the following types are subtypes of JSReceiver, which corresponds to
799 // objects in the JS sense. The first and the last type in this range are
800 // the two forms of function. This organization enables using the same
801 // compares for checking the JS_RECEIVER/SPEC_OBJECT range and the
802 // NONCALLABLE_JS_OBJECT range.
803 JS_FUNCTION_PROXY_TYPE, // FIRST_JS_RECEIVER_TYPE, FIRST_JS_PROXY_TYPE
804 JS_PROXY_TYPE, // LAST_JS_PROXY_TYPE
806 JS_VALUE_TYPE, // FIRST_JS_OBJECT_TYPE
809 JS_CONTEXT_EXTENSION_OBJECT_TYPE,
810 JS_GENERATOR_OBJECT_TYPE,
812 JS_GLOBAL_OBJECT_TYPE,
813 JS_BUILTINS_OBJECT_TYPE,
814 JS_GLOBAL_PROXY_TYPE,
816 JS_ARRAY_BUFFER_TYPE,
826 JS_FUNCTION_TYPE, // LAST_JS_OBJECT_TYPE, LAST_JS_RECEIVER_TYPE
830 LAST_TYPE = JS_FUNCTION_TYPE,
831 FIRST_NAME_TYPE = FIRST_TYPE,
832 LAST_NAME_TYPE = SYMBOL_TYPE,
833 FIRST_UNIQUE_NAME_TYPE = INTERNALIZED_STRING_TYPE,
834 LAST_UNIQUE_NAME_TYPE = SYMBOL_TYPE,
835 FIRST_NONSTRING_TYPE = SYMBOL_TYPE,
836 // Boundaries for testing for an external array.
837 FIRST_EXTERNAL_ARRAY_TYPE = EXTERNAL_INT8_ARRAY_TYPE,
838 LAST_EXTERNAL_ARRAY_TYPE = EXTERNAL_UINT8_CLAMPED_ARRAY_TYPE,
839 // Boundaries for testing for a fixed typed array.
840 FIRST_FIXED_TYPED_ARRAY_TYPE = FIXED_INT8_ARRAY_TYPE,
841 LAST_FIXED_TYPED_ARRAY_TYPE = FIXED_UINT8_CLAMPED_ARRAY_TYPE,
842 // Boundary for promotion to old data space/old pointer space.
843 LAST_DATA_TYPE = FILLER_TYPE,
844 // Boundary for objects represented as JSReceiver (i.e. JSObject or JSProxy).
845 // Note that there is no range for JSObject or JSProxy, since their subtypes
846 // are not continuous in this enum! The enum ranges instead reflect the
847 // external class names, where proxies are treated as either ordinary objects,
849 FIRST_JS_RECEIVER_TYPE = JS_FUNCTION_PROXY_TYPE,
850 LAST_JS_RECEIVER_TYPE = LAST_TYPE,
851 // Boundaries for testing the types represented as JSObject
852 FIRST_JS_OBJECT_TYPE = JS_VALUE_TYPE,
853 LAST_JS_OBJECT_TYPE = LAST_TYPE,
854 // Boundaries for testing the types represented as JSProxy
855 FIRST_JS_PROXY_TYPE = JS_FUNCTION_PROXY_TYPE,
856 LAST_JS_PROXY_TYPE = JS_PROXY_TYPE,
857 // Boundaries for testing whether the type is a JavaScript object.
858 FIRST_SPEC_OBJECT_TYPE = FIRST_JS_RECEIVER_TYPE,
859 LAST_SPEC_OBJECT_TYPE = LAST_JS_RECEIVER_TYPE,
860 // Boundaries for testing the types for which typeof is "object".
861 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_PROXY_TYPE,
862 LAST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_REGEXP_TYPE,
863 // Note that the types for which typeof is "function" are not continuous.
864 // Define this so that we can put assertions on discrete checks.
865 NUM_OF_CALLABLE_SPEC_OBJECT_TYPES = 2
868 const int kExternalArrayTypeCount =
869 LAST_EXTERNAL_ARRAY_TYPE - FIRST_EXTERNAL_ARRAY_TYPE + 1;
871 STATIC_CHECK(JS_OBJECT_TYPE == Internals::kJSObjectType);
872 STATIC_CHECK(FIRST_NONSTRING_TYPE == Internals::kFirstNonstringType);
873 STATIC_CHECK(ODDBALL_TYPE == Internals::kOddballType);
874 STATIC_CHECK(FOREIGN_TYPE == Internals::kForeignType);
877 #define FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(V) \
878 V(FAST_ELEMENTS_SUB_TYPE) \
879 V(DICTIONARY_ELEMENTS_SUB_TYPE) \
880 V(FAST_PROPERTIES_SUB_TYPE) \
881 V(DICTIONARY_PROPERTIES_SUB_TYPE) \
882 V(MAP_CODE_CACHE_SUB_TYPE) \
883 V(SCOPE_INFO_SUB_TYPE) \
884 V(STRING_TABLE_SUB_TYPE) \
885 V(DESCRIPTOR_ARRAY_SUB_TYPE) \
886 V(TRANSITION_ARRAY_SUB_TYPE)
888 enum FixedArraySubInstanceType {
889 #define DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE(name) name,
890 FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE)
891 #undef DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE
892 LAST_FIXED_ARRAY_SUB_TYPE = TRANSITION_ARRAY_SUB_TYPE
905 #define DECL_BOOLEAN_ACCESSORS(name) \
906 inline bool name(); \
907 inline void set_##name(bool value); \
910 #define DECL_ACCESSORS(name, type) \
911 inline type* name(); \
912 inline void set_##name(type* value, \
913 WriteBarrierMode mode = UPDATE_WRITE_BARRIER); \
916 class AllocationSite;
917 class AllocationSiteCreationContext;
918 class AllocationSiteUsageContext;
919 class DictionaryElementsAccessor;
920 class ElementsAccessor;
922 class FixedArrayBase;
926 // We cannot just say "class HeapType;" if it is created from a template... =8-?
927 template<class> class TypeImpl;
928 struct HeapTypeConfig;
929 typedef TypeImpl<HeapTypeConfig> HeapType;
932 // A template-ized version of the IsXXX functions.
933 template <class C> inline bool Is(Object* obj);
936 #define DECLARE_VERIFIER(Name) void Name##Verify();
938 #define DECLARE_VERIFIER(Name)
942 #define DECLARE_PRINTER(Name) void Name##Print(FILE* out = stdout);
944 #define DECLARE_PRINTER(Name)
947 class MaybeObject BASE_EMBEDDED {
949 inline bool IsFailure();
950 inline bool IsRetryAfterGC();
951 inline bool IsOutOfMemory();
952 inline bool IsException();
953 INLINE(bool IsTheHole());
954 INLINE(bool IsUninitialized());
955 inline bool ToObject(Object** obj) {
956 if (IsFailure()) return false;
957 *obj = reinterpret_cast<Object*>(this);
960 inline Failure* ToFailureUnchecked() {
962 return reinterpret_cast<Failure*>(this);
964 inline Object* ToObjectUnchecked() {
965 // TODO(jkummerow): Turn this back into an ASSERT when we can be certain
966 // that it never fires in Release mode in the wild.
968 return reinterpret_cast<Object*>(this);
970 inline Object* ToObjectChecked() {
972 return reinterpret_cast<Object*>(this);
976 inline bool To(T** obj) {
977 if (IsFailure()) return false;
978 *obj = T::cast(reinterpret_cast<Object*>(this));
983 inline bool ToHandle(Handle<T>* obj, Isolate* isolate) {
984 if (IsFailure()) return false;
985 *obj = handle(T::cast(reinterpret_cast<Object*>(this)), isolate);
990 // Prints this object with details.
992 void Print(FILE* out);
994 void PrintLn(FILE* out);
997 // Verifies the object.
1003 #define OBJECT_TYPE_LIST(V) \
1008 #define HEAP_OBJECT_TYPE_LIST(V) \
1019 V(ExternalTwoByteString) \
1020 V(ExternalAsciiString) \
1021 V(SeqTwoByteString) \
1022 V(SeqOneByteString) \
1023 V(InternalizedString) \
1027 V(ExternalInt8Array) \
1028 V(ExternalUint8Array) \
1029 V(ExternalInt16Array) \
1030 V(ExternalUint16Array) \
1031 V(ExternalInt32Array) \
1032 V(ExternalUint32Array) \
1033 V(ExternalFloat32Array) \
1034 V(ExternalFloat32x4Array) \
1035 V(ExternalInt32x4Array) \
1036 V(ExternalFloat64Array) \
1037 V(ExternalUint8ClampedArray) \
1038 V(FixedTypedArrayBase) \
1039 V(FixedUint8Array) \
1041 V(FixedUint16Array) \
1042 V(FixedInt16Array) \
1043 V(FixedUint32Array) \
1044 V(FixedInt32Array) \
1045 V(FixedFloat32Array) \
1046 V(FixedFloat32x4Array) \
1047 V(FixedInt32x4Array) \
1048 V(FixedFloat64Array) \
1049 V(FixedUint8ClampedArray) \
1054 V(JSContextExtensionObject) \
1055 V(JSGeneratorObject) \
1058 V(DescriptorArray) \
1059 V(TransitionArray) \
1060 V(DeoptimizationInputData) \
1061 V(DeoptimizationOutputData) \
1063 V(TypeFeedbackCells) \
1065 V(FixedDoubleArray) \
1066 V(ConstantPoolArray) \
1073 V(SharedFunctionInfo) \
1076 V(JSMessageObject) \
1082 V(JSArrayBufferView) \
1086 V(JSFunctionProxy) \
1089 V(JSWeakCollection) \
1096 V(JSFunctionResultCache) \
1097 V(NormalizedMapCache) \
1098 V(CompilationCacheTable) \
1099 V(CodeCacheHashTable) \
1100 V(PolymorphicCodeCacheHashTable) \
1105 V(JSBuiltinsObject) \
1107 V(UndetectableObject) \
1108 V(AccessCheckNeeded) \
1111 V(ObjectHashTable) \
1115 #define ERROR_MESSAGES_LIST(V) \
1116 V(kNoReason, "no reason") \
1118 V(k32BitValueInRegisterIsNotZeroExtended, \
1119 "32 bit value in register is not zero-extended") \
1120 V(kAlignmentMarkerExpected, "Alignment marker expected") \
1121 V(kAllocationIsNotDoubleAligned, "Allocation is not double aligned") \
1122 V(kAPICallReturnedInvalidObject, "API call returned invalid object") \
1123 V(kArgumentsObjectValueInATestContext, \
1124 "Arguments object value in a test context") \
1125 V(kArrayBoilerplateCreationFailed, "Array boilerplate creation failed") \
1126 V(kArrayIndexConstantValueTooBig, "Array index constant value too big") \
1127 V(kAssignmentToArguments, "Assignment to arguments") \
1128 V(kAssignmentToLetVariableBeforeInitialization, \
1129 "Assignment to let variable before initialization") \
1130 V(kAssignmentToLOOKUPVariable, "Assignment to LOOKUP variable") \
1131 V(kAssignmentToParameterFunctionUsesArgumentsObject, \
1132 "Assignment to parameter, function uses arguments object") \
1133 V(kAssignmentToParameterInArgumentsObject, \
1134 "Assignment to parameter in arguments object") \
1135 V(kAttemptToUseUndefinedCache, "Attempt to use undefined cache") \
1136 V(kBadValueContextForArgumentsObjectValue, \
1137 "Bad value context for arguments object value") \
1138 V(kBadValueContextForArgumentsValue, \
1139 "Bad value context for arguments value") \
1140 V(kBailedOutDueToDependencyChange, "Bailed out due to dependency change") \
1141 V(kBailoutWasNotPrepared, "Bailout was not prepared") \
1142 V(kBinaryStubGenerateFloatingPointCode, \
1143 "BinaryStub_GenerateFloatingPointCode") \
1144 V(kBothRegistersWereSmisInSelectNonSmi, \
1145 "Both registers were smis in SelectNonSmi") \
1146 V(kCallToAJavaScriptRuntimeFunction, \
1147 "Call to a JavaScript runtime function") \
1148 V(kCannotTranslatePositionInChangedArea, \
1149 "Cannot translate position in changed area") \
1150 V(kCodeGenerationFailed, "Code generation failed") \
1151 V(kCodeObjectNotProperlyPatched, "Code object not properly patched") \
1152 V(kCompoundAssignmentToLookupSlot, "Compound assignment to lookup slot") \
1153 V(kContextAllocatedArguments, "Context-allocated arguments") \
1154 V(kDebuggerIsActive, "Debugger is active") \
1155 V(kDebuggerStatement, "DebuggerStatement") \
1156 V(kDeclarationInCatchContext, "Declaration in catch context") \
1157 V(kDeclarationInWithContext, "Declaration in with context") \
1158 V(kDefaultNaNModeNotSet, "Default NaN mode not set") \
1159 V(kDeleteWithGlobalVariable, "Delete with global variable") \
1160 V(kDeleteWithNonGlobalVariable, "Delete with non-global variable") \
1161 V(kDestinationOfCopyNotAligned, "Destination of copy not aligned") \
1162 V(kDontDeleteCellsCannotContainTheHole, \
1163 "DontDelete cells can't contain the hole") \
1164 V(kDoPushArgumentNotImplementedForDoubleType, \
1165 "DoPushArgument not implemented for double type") \
1166 V(kEmitLoadRegisterUnsupportedDoubleImmediate, \
1167 "EmitLoadRegister: Unsupported double immediate") \
1169 V(kExpected0AsASmiSentinel, "Expected 0 as a Smi sentinel") \
1170 V(kExpectedAlignmentMarker, "expected alignment marker") \
1171 V(kExpectedAllocationSite, "expected allocation site") \
1172 V(kExpectedPropertyCellInRegisterA2, \
1173 "Expected property cell in register a2") \
1174 V(kExpectedPropertyCellInRegisterEbx, \
1175 "Expected property cell in register ebx") \
1176 V(kExpectedPropertyCellInRegisterRbx, \
1177 "Expected property cell in register rbx") \
1178 V(kExpectingAlignmentForCopyBytes, \
1179 "Expecting alignment for CopyBytes") \
1180 V(kExportDeclaration, "Export declaration") \
1181 V(kExternalStringExpectedButNotFound, \
1182 "External string expected, but not found") \
1183 V(kFailedBailedOutLastTime, "Failed/bailed out last time") \
1184 V(kForInStatementIsNotFastCase, "ForInStatement is not fast case") \
1185 V(kForInStatementOptimizationIsDisabled, \
1186 "ForInStatement optimization is disabled") \
1187 V(kForInStatementWithNonLocalEachVariable, \
1188 "ForInStatement with non-local each variable") \
1189 V(kForOfStatement, "ForOfStatement") \
1190 V(kFrameIsExpectedToBeAligned, "Frame is expected to be aligned") \
1191 V(kFunctionCallsEval, "Function calls eval") \
1192 V(kFunctionIsAGenerator, "Function is a generator") \
1193 V(kFunctionWithIllegalRedeclaration, "Function with illegal redeclaration") \
1194 V(kGeneratedCodeIsTooLarge, "Generated code is too large") \
1195 V(kGeneratorFailedToResume, "Generator failed to resume") \
1196 V(kGenerator, "Generator") \
1197 V(kGlobalFunctionsMustHaveInitialMap, \
1198 "Global functions must have initial map") \
1199 V(kHeapNumberMapRegisterClobbered, "HeapNumberMap register clobbered") \
1200 V(kHydrogenFilter, "Optimization disabled by filter") \
1201 V(kImportDeclaration, "Import declaration") \
1202 V(kImproperObjectOnPrototypeChainForStore, \
1203 "Improper object on prototype chain for store") \
1204 V(kIndexIsNegative, "Index is negative") \
1205 V(kIndexIsTooLarge, "Index is too large") \
1206 V(kInlinedRuntimeFunctionClassOf, "Inlined runtime function: ClassOf") \
1207 V(kInlinedRuntimeFunctionFastAsciiArrayJoin, \
1208 "Inlined runtime function: FastAsciiArrayJoin") \
1209 V(kInlinedRuntimeFunctionGeneratorNext, \
1210 "Inlined runtime function: GeneratorNext") \
1211 V(kInlinedRuntimeFunctionGeneratorThrow, \
1212 "Inlined runtime function: GeneratorThrow") \
1213 V(kInlinedRuntimeFunctionGetFromCache, \
1214 "Inlined runtime function: GetFromCache") \
1215 V(kInlinedRuntimeFunctionIsNonNegativeSmi, \
1216 "Inlined runtime function: IsNonNegativeSmi") \
1217 V(kInlinedRuntimeFunctionIsStringWrapperSafeForDefaultValueOf, \
1218 "Inlined runtime function: IsStringWrapperSafeForDefaultValueOf") \
1219 V(kInliningBailedOut, "Inlining bailed out") \
1220 V(kInputGPRIsExpectedToHaveUpper32Cleared, \
1221 "Input GPR is expected to have upper32 cleared") \
1222 V(kInstanceofStubUnexpectedCallSiteCacheCheck, \
1223 "InstanceofStub unexpected call site cache (check)") \
1224 V(kInstanceofStubUnexpectedCallSiteCacheCmp1, \
1225 "InstanceofStub unexpected call site cache (cmp 1)") \
1226 V(kInstanceofStubUnexpectedCallSiteCacheCmp2, \
1227 "InstanceofStub unexpected call site cache (cmp 2)") \
1228 V(kInstanceofStubUnexpectedCallSiteCacheMov, \
1229 "InstanceofStub unexpected call site cache (mov)") \
1230 V(kInteger32ToSmiFieldWritingToNonSmiLocation, \
1231 "Integer32ToSmiField writing to non-smi location") \
1232 V(kInvalidCaptureReferenced, "Invalid capture referenced") \
1233 V(kInvalidElementsKindForInternalArrayOrInternalPackedArray, \
1234 "Invalid ElementsKind for InternalArray or InternalPackedArray") \
1235 V(kInvalidHandleScopeLevel, "Invalid HandleScope level") \
1236 V(kInvalidLeftHandSideInAssignment, "Invalid left-hand side in assignment") \
1237 V(kInvalidLhsInCompoundAssignment, "Invalid lhs in compound assignment") \
1238 V(kInvalidLhsInCountOperation, "Invalid lhs in count operation") \
1239 V(kInvalidMinLength, "Invalid min_length") \
1240 V(kJSGlobalObjectNativeContextShouldBeANativeContext, \
1241 "JSGlobalObject::native_context should be a native context") \
1242 V(kJSGlobalProxyContextShouldNotBeNull, \
1243 "JSGlobalProxy::context() should not be null") \
1244 V(kJSObjectWithFastElementsMapHasSlowElements, \
1245 "JSObject with fast elements map has slow elements") \
1246 V(kLetBindingReInitialization, "Let binding re-initialization") \
1247 V(kLiveBytesCountOverflowChunkSize, "Live Bytes Count overflow chunk size") \
1248 V(kLiveEditFrameDroppingIsNotSupportedOnArm, \
1249 "LiveEdit frame dropping is not supported on arm") \
1250 V(kLiveEditFrameDroppingIsNotSupportedOnMips, \
1251 "LiveEdit frame dropping is not supported on mips") \
1252 V(kLiveEdit, "LiveEdit") \
1253 V(kLookupVariableInCountOperation, \
1254 "Lookup variable in count operation") \
1255 V(kMapIsNoLongerInEax, "Map is no longer in eax") \
1256 V(kModuleDeclaration, "Module declaration") \
1257 V(kModuleLiteral, "Module literal") \
1258 V(kModulePath, "Module path") \
1259 V(kModuleStatement, "Module statement") \
1260 V(kModuleVariable, "Module variable") \
1261 V(kModuleUrl, "Module url") \
1262 V(kNativeFunctionLiteral, "Native function literal") \
1263 V(kNoCasesLeft, "No cases left") \
1264 V(kNoEmptyArraysHereInEmitFastAsciiArrayJoin, \
1265 "No empty arrays here in EmitFastAsciiArrayJoin") \
1266 V(kNonInitializerAssignmentToConst, \
1267 "Non-initializer assignment to const") \
1268 V(kNonSmiIndex, "Non-smi index") \
1269 V(kNonSmiKeyInArrayLiteral, "Non-smi key in array literal") \
1270 V(kNonSmiValue, "Non-smi value") \
1271 V(kNonObject, "Non-object value") \
1272 V(kNotEnoughVirtualRegistersForValues, \
1273 "Not enough virtual registers for values") \
1274 V(kNotEnoughSpillSlotsForOsr, \
1275 "Not enough spill slots for OSR") \
1276 V(kNotEnoughVirtualRegistersRegalloc, \
1277 "Not enough virtual registers (regalloc)") \
1278 V(kObjectFoundInSmiOnlyArray, "Object found in smi-only array") \
1279 V(kObjectLiteralWithComplexProperty, \
1280 "Object literal with complex property") \
1281 V(kOddballInStringTableIsNotUndefinedOrTheHole, \
1282 "Oddball in string table is not undefined or the hole") \
1283 V(kOperandIsASmiAndNotAName, "Operand is a smi and not a name") \
1284 V(kOperandIsASmiAndNotAString, "Operand is a smi and not a string") \
1285 V(kOperandIsASmi, "Operand is a smi") \
1286 V(kOperandIsNotAName, "Operand is not a name") \
1287 V(kOperandIsNotANumber, "Operand is not a number") \
1288 V(kOperandIsNotASmi, "Operand is not a smi") \
1289 V(kOperandIsNotAString, "Operand is not a string") \
1290 V(kOperandIsNotSmi, "Operand is not smi") \
1291 V(kOperandNotANumber, "Operand not a number") \
1292 V(kOptimizationDisabled, "Optimization is disabled") \
1293 V(kOptimizedTooManyTimes, "Optimized too many times") \
1294 V(kOutOfVirtualRegistersWhileTryingToAllocateTempRegister, \
1295 "Out of virtual registers while trying to allocate temp register") \
1296 V(kParseScopeError, "Parse/scope error") \
1297 V(kPossibleDirectCallToEval, "Possible direct call to eval") \
1298 V(kPropertyAllocationCountFailed, "Property allocation count failed") \
1299 V(kReceivedInvalidReturnAddress, "Received invalid return address") \
1300 V(kReferenceToAVariableWhichRequiresDynamicLookup, \
1301 "Reference to a variable which requires dynamic lookup") \
1302 V(kReferenceToGlobalLexicalVariable, \
1303 "Reference to global lexical variable") \
1304 V(kReferenceToUninitializedVariable, "Reference to uninitialized variable") \
1305 V(kRegisterDidNotMatchExpectedRoot, "Register did not match expected root") \
1306 V(kRegisterWasClobbered, "Register was clobbered") \
1307 V(kScopedBlock, "ScopedBlock") \
1308 V(kSmiAdditionOverflow, "Smi addition overflow") \
1309 V(kSmiSubtractionOverflow, "Smi subtraction overflow") \
1310 V(kStackFrameTypesMustMatch, "Stack frame types must match") \
1311 V(kSwitchStatementMixedOrNonLiteralSwitchLabels, \
1312 "SwitchStatement: mixed or non-literal switch labels") \
1313 V(kSwitchStatementTooManyClauses, "SwitchStatement: too many clauses") \
1314 V(kTheInstructionShouldBeALui, "The instruction should be a lui") \
1315 V(kTheInstructionShouldBeAnOri, "The instruction should be an ori") \
1316 V(kTheInstructionToPatchShouldBeALoadFromPc, \
1317 "The instruction to patch should be a load from pc") \
1318 V(kTheInstructionToPatchShouldBeALui, \
1319 "The instruction to patch should be a lui") \
1320 V(kTheInstructionToPatchShouldBeAnOri, \
1321 "The instruction to patch should be an ori") \
1322 V(kTooManyParametersLocals, "Too many parameters/locals") \
1323 V(kTooManyParameters, "Too many parameters") \
1324 V(kTooManySpillSlotsNeededForOSR, "Too many spill slots needed for OSR") \
1325 V(kToOperandIsDoubleRegisterUnimplemented, \
1326 "ToOperand IsDoubleRegister unimplemented") \
1327 V(kToOperandUnsupportedDoubleImmediate, \
1328 "ToOperand Unsupported double immediate") \
1329 V(kTryCatchStatement, "TryCatchStatement") \
1330 V(kTryFinallyStatement, "TryFinallyStatement") \
1331 V(kUnableToEncodeValueAsSmi, "Unable to encode value as smi") \
1332 V(kUnalignedAllocationInNewSpace, "Unaligned allocation in new space") \
1333 V(kUndefinedValueNotLoaded, "Undefined value not loaded") \
1334 V(kUndoAllocationOfNonAllocatedMemory, \
1335 "Undo allocation of non allocated memory") \
1336 V(kUnexpectedAllocationTop, "Unexpected allocation top") \
1337 V(kUnexpectedElementsKindInArrayConstructor, \
1338 "Unexpected ElementsKind in array constructor") \
1339 V(kUnexpectedFallthroughFromCharCodeAtSlowCase, \
1340 "Unexpected fallthrough from CharCodeAt slow case") \
1341 V(kUnexpectedFallthroughFromCharFromCodeSlowCase, \
1342 "Unexpected fallthrough from CharFromCode slow case") \
1343 V(kUnexpectedFallThroughFromStringComparison, \
1344 "Unexpected fall-through from string comparison") \
1345 V(kUnexpectedFallThroughInBinaryStubGenerateFloatingPointCode, \
1346 "Unexpected fall-through in BinaryStub_GenerateFloatingPointCode") \
1347 V(kUnexpectedFallthroughToCharCodeAtSlowCase, \
1348 "Unexpected fallthrough to CharCodeAt slow case") \
1349 V(kUnexpectedFallthroughToCharFromCodeSlowCase, \
1350 "Unexpected fallthrough to CharFromCode slow case") \
1351 V(kUnexpectedFPUStackDepthAfterInstruction, \
1352 "Unexpected FPU stack depth after instruction") \
1353 V(kUnexpectedInitialMapForArrayFunction1, \
1354 "Unexpected initial map for Array function (1)") \
1355 V(kUnexpectedInitialMapForArrayFunction2, \
1356 "Unexpected initial map for Array function (2)") \
1357 V(kUnexpectedInitialMapForArrayFunction, \
1358 "Unexpected initial map for Array function") \
1359 V(kUnexpectedInitialMapForInternalArrayFunction, \
1360 "Unexpected initial map for InternalArray function") \
1361 V(kUnexpectedLevelAfterReturnFromApiCall, \
1362 "Unexpected level after return from api call") \
1363 V(kUnexpectedNumberOfPreAllocatedPropertyFields, \
1364 "Unexpected number of pre-allocated property fields") \
1365 V(kUnexpectedStringFunction, "Unexpected String function") \
1366 V(kUnexpectedStringType, "Unexpected string type") \
1367 V(kUnexpectedStringWrapperInstanceSize, \
1368 "Unexpected string wrapper instance size") \
1369 V(kUnexpectedTypeForRegExpDataFixedArrayExpected, \
1370 "Unexpected type for RegExp data, FixedArray expected") \
1371 V(kUnexpectedUnusedPropertiesOfStringWrapper, \
1372 "Unexpected unused properties of string wrapper") \
1373 V(kUninitializedKSmiConstantRegister, "Uninitialized kSmiConstantRegister") \
1374 V(kUnknown, "Unknown") \
1375 V(kUnsupportedConstCompoundAssignment, \
1376 "Unsupported const compound assignment") \
1377 V(kUnsupportedCountOperationWithConst, \
1378 "Unsupported count operation with const") \
1379 V(kUnsupportedDoubleImmediate, "Unsupported double immediate") \
1380 V(kUnsupportedLetCompoundAssignment, "Unsupported let compound assignment") \
1381 V(kUnsupportedLookupSlotInDeclaration, \
1382 "Unsupported lookup slot in declaration") \
1383 V(kUnsupportedNonPrimitiveCompare, "Unsupported non-primitive compare") \
1384 V(kUnsupportedPhiUseOfArguments, "Unsupported phi use of arguments") \
1385 V(kUnsupportedPhiUseOfConstVariable, \
1386 "Unsupported phi use of const variable") \
1387 V(kUnsupportedTaggedImmediate, "Unsupported tagged immediate") \
1388 V(kVariableResolvedToWithContext, "Variable resolved to with context") \
1389 V(kWeShouldNotHaveAnEmptyLexicalContext, \
1390 "We should not have an empty lexical context") \
1391 V(kWithStatement, "WithStatement") \
1392 V(kWrongAddressOrValuePassedToRecordWrite, \
1393 "Wrong address or value passed to RecordWrite") \
1397 #define ERROR_MESSAGES_CONSTANTS(C, T) C,
1398 enum BailoutReason {
1399 ERROR_MESSAGES_LIST(ERROR_MESSAGES_CONSTANTS)
1402 #undef ERROR_MESSAGES_CONSTANTS
1405 const char* GetBailoutReason(BailoutReason reason);
1408 // Object is the abstract superclass for all classes in the
1409 // object hierarchy.
1410 // Object does not use any virtual functions to avoid the
1411 // allocation of the C++ vtable.
1412 // Since Smi and Failure are subclasses of Object no
1413 // data members can be present in Object.
1414 class Object : public MaybeObject {
1417 bool IsObject() { return true; }
1419 #define IS_TYPE_FUNCTION_DECL(type_) inline bool Is##type_();
1420 OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1421 HEAP_OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1422 #undef IS_TYPE_FUNCTION_DECL
1424 inline bool IsFixedArrayBase();
1425 inline bool IsExternal();
1426 inline bool IsAccessorInfo();
1428 inline bool IsStruct();
1429 #define DECLARE_STRUCT_PREDICATE(NAME, Name, name) inline bool Is##Name();
1430 STRUCT_LIST(DECLARE_STRUCT_PREDICATE)
1431 #undef DECLARE_STRUCT_PREDICATE
1433 INLINE(bool IsSpecObject());
1434 INLINE(bool IsSpecFunction());
1438 INLINE(bool IsUndefined());
1439 INLINE(bool IsNull());
1440 INLINE(bool IsTheHole()); // Shadows MaybeObject's implementation.
1441 INLINE(bool IsUninitialized());
1442 INLINE(bool IsTrue());
1443 INLINE(bool IsFalse());
1444 inline bool IsArgumentsMarker();
1445 inline bool NonFailureIsHeapObject();
1447 // Filler objects (fillers and free space objects).
1448 inline bool IsFiller();
1450 // Extract the number.
1451 inline double Number();
1452 inline bool IsNaN();
1453 bool ToInt32(int32_t* value);
1454 bool ToUint32(uint32_t* value);
1456 // Indicates whether OptimalRepresentation can do its work, or whether it
1457 // always has to return Representation::Tagged().
1459 OPTIMAL_REPRESENTATION,
1463 inline Representation OptimalRepresentation(
1464 ValueType type = OPTIMAL_REPRESENTATION) {
1465 if (!FLAG_track_fields) return Representation::Tagged();
1466 if (type == FORCE_TAGGED) return Representation::Tagged();
1468 return Representation::Smi();
1469 } else if (FLAG_track_double_fields && IsHeapNumber()) {
1470 return Representation::Double();
1471 } else if (FLAG_track_computed_fields && IsUninitialized()) {
1472 return Representation::None();
1473 } else if (FLAG_track_heap_object_fields) {
1474 ASSERT(IsHeapObject());
1475 return Representation::HeapObject();
1477 return Representation::Tagged();
1481 inline bool FitsRepresentation(Representation representation) {
1482 if (FLAG_track_fields && representation.IsNone()) {
1484 } else if (FLAG_track_fields && representation.IsSmi()) {
1486 } else if (FLAG_track_double_fields && representation.IsDouble()) {
1488 } else if (FLAG_track_heap_object_fields && representation.IsHeapObject()) {
1489 return IsHeapObject();
1494 inline MaybeObject* AllocateNewStorageFor(Heap* heap,
1495 Representation representation);
1497 // Returns true if the object is of the correct type to be used as a
1498 // implementation of a JSObject's elements.
1499 inline bool HasValidElements();
1501 inline bool HasSpecificClassOf(String* name);
1503 MUST_USE_RESULT MaybeObject* ToObject(Isolate* isolate); // ECMA-262 9.9.
1504 bool BooleanValue(); // ECMA-262 9.2.
1506 // Convert to a JSObject if needed.
1507 // native_context is used when creating wrapper object.
1508 MUST_USE_RESULT MaybeObject* ToObject(Context* native_context);
1510 // Converts this to a Smi if possible.
1511 // Failure is returned otherwise.
1512 MUST_USE_RESULT inline MaybeObject* ToSmi();
1514 void Lookup(Name* name, LookupResult* result);
1517 MUST_USE_RESULT inline MaybeObject* GetProperty(Name* key);
1518 MUST_USE_RESULT inline MaybeObject* GetProperty(
1520 PropertyAttributes* attributes);
1522 // TODO(yangguo): this should eventually replace the non-handlified version.
1523 static Handle<Object> GetPropertyWithReceiver(Handle<Object> object,
1524 Handle<Object> receiver,
1526 PropertyAttributes* attributes);
1527 MUST_USE_RESULT MaybeObject* GetPropertyWithReceiver(
1530 PropertyAttributes* attributes);
1532 static Handle<Object> GetProperty(Handle<Object> object,
1534 static Handle<Object> GetProperty(Handle<Object> object,
1535 Handle<Object> receiver,
1536 LookupResult* result,
1538 PropertyAttributes* attributes);
1540 MUST_USE_RESULT static MaybeObject* GetPropertyOrFail(
1541 Handle<Object> object,
1542 Handle<Object> receiver,
1543 LookupResult* result,
1545 PropertyAttributes* attributes);
1547 MUST_USE_RESULT MaybeObject* GetProperty(Object* receiver,
1548 LookupResult* result,
1550 PropertyAttributes* attributes);
1552 MUST_USE_RESULT MaybeObject* GetPropertyWithDefinedGetter(Object* receiver,
1553 JSReceiver* getter);
1555 static Handle<Object> GetElement(Isolate* isolate,
1556 Handle<Object> object,
1558 MUST_USE_RESULT inline MaybeObject* GetElement(Isolate* isolate,
1560 // For use when we know that no exception can be thrown.
1561 inline Object* GetElementNoExceptionThrown(Isolate* isolate, uint32_t index);
1562 MUST_USE_RESULT MaybeObject* GetElementWithReceiver(Isolate* isolate,
1566 // Return the object's prototype (might be Heap::null_value()).
1567 Object* GetPrototype(Isolate* isolate);
1568 Map* GetMarkerMap(Isolate* isolate);
1570 // Returns the permanent hash code associated with this object. May return
1571 // undefined if not yet created.
1574 // Returns the permanent hash code associated with this object depending on
1575 // the actual object type. May create and store a hash code if needed and none
1577 // TODO(rafaelw): Remove isolate parameter when objects.cc is fully
1579 static Handle<Object> GetOrCreateHash(Handle<Object> object,
1582 // Checks whether this object has the same value as the given one. This
1583 // function is implemented according to ES5, section 9.12 and can be used
1584 // to implement the Harmony "egal" function.
1585 bool SameValue(Object* other);
1587 // Tries to convert an object to an array index. Returns true and sets
1588 // the output parameter if it succeeds.
1589 inline bool ToArrayIndex(uint32_t* index);
1591 // Returns true if this is a JSValue containing a string and the index is
1592 // < the length of the string. Used to implement [] on strings.
1593 inline bool IsStringObjectWithCharacterAt(uint32_t index);
1596 // Verify a pointer is a valid object pointer.
1597 static void VerifyPointer(Object* p);
1600 inline void VerifyApiCallResultType();
1602 // Prints this object without details.
1603 void ShortPrint(FILE* out = stdout);
1605 // Prints this object without details to a message accumulator.
1606 void ShortPrint(StringStream* accumulator);
1608 // Casting: This cast is only needed to satisfy macros in objects-inl.h.
1609 static Object* cast(Object* value) { return value; }
1611 // Layout description.
1612 static const int kHeaderSize = 0; // Object does not take up any space.
1615 DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
1619 // Smi represents integer Numbers that can be stored in 31 bits.
1620 // Smis are immediate which means they are NOT allocated in the heap.
1621 // The this pointer has the following format: [31 bit signed int] 0
1622 // For long smis it has the following format:
1623 // [32 bit signed int] [31 bits zero padding] 0
1624 // Smi stands for small integer.
1625 class Smi: public Object {
1627 // Returns the integer value.
1630 // Convert a value to a Smi object.
1631 static inline Smi* FromInt(int value);
1633 static inline Smi* FromIntptr(intptr_t value);
1635 // Returns whether value can be represented in a Smi.
1636 static inline bool IsValid(intptr_t value);
1639 static inline Smi* cast(Object* object);
1641 // Dispatched behavior.
1642 void SmiPrint(FILE* out = stdout);
1643 void SmiPrint(StringStream* accumulator);
1645 DECLARE_VERIFIER(Smi)
1647 static const int kMinValue =
1648 (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1649 static const int kMaxValue = -(kMinValue + 1);
1652 DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1656 // Failure is used for reporting out of memory situations and
1657 // propagating exceptions through the runtime system. Failure objects
1658 // are transient and cannot occur as part of the object graph.
1660 // Failures are a single word, encoded as follows:
1661 // +-------------------------+---+--+--+
1662 // |.........unused..........|sss|tt|11|
1663 // +-------------------------+---+--+--+
1667 // The low two bits, 0-1, are the failure tag, 11. The next two bits,
1668 // 2-3, are a failure type tag 'tt' with possible values:
1669 // 00 RETRY_AFTER_GC
1671 // 10 INTERNAL_ERROR
1672 // 11 OUT_OF_MEMORY_EXCEPTION
1674 // The next three bits, 4-6, are an allocation space tag 'sss'. The
1675 // allocation space tag is 000 for all failure types except
1676 // RETRY_AFTER_GC. For RETRY_AFTER_GC, the possible values are the
1677 // allocation spaces (the encoding is found in globals.h).
1679 // Failure type tag info.
1680 const int kFailureTypeTagSize = 2;
1681 const int kFailureTypeTagMask = (1 << kFailureTypeTagSize) - 1;
1683 class Failure: public MaybeObject {
1685 // RuntimeStubs assumes EXCEPTION = 1 in the compiler-generated code.
1688 EXCEPTION = 1, // Returning this marker tells the real exception
1689 // is in Isolate::pending_exception.
1691 OUT_OF_MEMORY_EXCEPTION = 3
1694 inline Type type() const;
1696 // Returns the space that needs to be collected for RetryAfterGC failures.
1697 inline AllocationSpace allocation_space() const;
1699 inline bool IsInternalError() const;
1700 inline bool IsOutOfMemoryException() const;
1702 static inline Failure* RetryAfterGC(AllocationSpace space);
1703 static inline Failure* RetryAfterGC(); // NEW_SPACE
1704 static inline Failure* Exception();
1705 static inline Failure* InternalError();
1706 // TODO(jkummerow): The value is temporary instrumentation. Remove it
1707 // when it has served its purpose.
1708 static inline Failure* OutOfMemoryException(intptr_t value);
1710 static inline Failure* cast(MaybeObject* object);
1712 // Dispatched behavior.
1713 void FailurePrint(FILE* out = stdout);
1714 void FailurePrint(StringStream* accumulator);
1716 DECLARE_VERIFIER(Failure)
1719 inline intptr_t value() const;
1720 static inline Failure* Construct(Type type, intptr_t value = 0);
1722 DISALLOW_IMPLICIT_CONSTRUCTORS(Failure);
1726 // Heap objects typically have a map pointer in their first word. However,
1727 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1728 // encoded in the first word. The class MapWord is an abstraction of the
1729 // value in a heap object's first word.
1730 class MapWord BASE_EMBEDDED {
1732 // Normal state: the map word contains a map pointer.
1734 // Create a map word from a map pointer.
1735 static inline MapWord FromMap(Map* map);
1737 // View this map word as a map pointer.
1738 inline Map* ToMap();
1741 // Scavenge collection: the map word of live objects in the from space
1742 // contains a forwarding address (a heap object pointer in the to space).
1744 // True if this map word is a forwarding address for a scavenge
1745 // collection. Only valid during a scavenge collection (specifically,
1746 // when all map words are heap object pointers, i.e. not during a full GC).
1747 inline bool IsForwardingAddress();
1749 // Create a map word from a forwarding address.
1750 static inline MapWord FromForwardingAddress(HeapObject* object);
1752 // View this map word as a forwarding address.
1753 inline HeapObject* ToForwardingAddress();
1755 static inline MapWord FromRawValue(uintptr_t value) {
1756 return MapWord(value);
1759 inline uintptr_t ToRawValue() {
1764 // HeapObject calls the private constructor and directly reads the value.
1765 friend class HeapObject;
1767 explicit MapWord(uintptr_t value) : value_(value) {}
1773 // HeapObject is the superclass for all classes describing heap allocated
1775 class HeapObject: public Object {
1777 // [map]: Contains a map which contains the object's reflective
1780 inline void set_map(Map* value);
1781 // The no-write-barrier version. This is OK if the object is white and in
1782 // new space, or if the value is an immortal immutable object, like the maps
1783 // of primitive (non-JS) objects like strings, heap numbers etc.
1784 inline void set_map_no_write_barrier(Map* value);
1786 // During garbage collection, the map word of a heap object does not
1787 // necessarily contain a map pointer.
1788 inline MapWord map_word();
1789 inline void set_map_word(MapWord map_word);
1791 // The Heap the object was allocated in. Used also to access Isolate.
1792 inline Heap* GetHeap();
1794 // Convenience method to get current isolate.
1795 inline Isolate* GetIsolate();
1797 // Converts an address to a HeapObject pointer.
1798 static inline HeapObject* FromAddress(Address address);
1800 // Returns the address of this HeapObject.
1801 inline Address address();
1803 // Iterates over pointers contained in the object (including the Map)
1804 void Iterate(ObjectVisitor* v);
1806 // Iterates over all pointers contained in the object except the
1807 // first map pointer. The object type is given in the first
1808 // parameter. This function does not access the map pointer in the
1809 // object, and so is safe to call while the map pointer is modified.
1810 void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1812 // Returns the heap object's size in bytes
1815 // Given a heap object's map pointer, returns the heap size in bytes
1816 // Useful when the map pointer field is used for other purposes.
1818 inline int SizeFromMap(Map* map);
1820 // Returns the field at offset in obj, as a read/write Object* reference.
1821 // Does no checking, and is safe to use during GC, while maps are invalid.
1822 // Does not invoke write barrier, so should only be assigned to
1823 // during marking GC.
1824 static inline Object** RawField(HeapObject* obj, int offset);
1826 // Adds the |code| object related to |name| to the code cache of this map. If
1827 // this map is a dictionary map that is shared, the map copied and installed
1829 static void UpdateMapCodeCache(Handle<HeapObject> object,
1834 static inline HeapObject* cast(Object* obj);
1836 // Return the write barrier mode for this. Callers of this function
1837 // must be able to present a reference to an DisallowHeapAllocation
1838 // object as a sign that they are not going to use this function
1839 // from code that allocates and thus invalidates the returned write
1841 inline WriteBarrierMode GetWriteBarrierMode(
1842 const DisallowHeapAllocation& promise);
1844 // Dispatched behavior.
1845 void HeapObjectShortPrint(StringStream* accumulator);
1847 void PrintHeader(FILE* out, const char* id);
1849 DECLARE_PRINTER(HeapObject)
1850 DECLARE_VERIFIER(HeapObject)
1852 inline void VerifyObjectField(int offset);
1853 inline void VerifySmiField(int offset);
1855 // Verify a pointer is a valid HeapObject pointer that points to object
1856 // areas in the heap.
1857 static void VerifyHeapPointer(Object* p);
1860 // Layout description.
1861 // First field in a heap object is map.
1862 static const int kMapOffset = Object::kHeaderSize;
1863 static const int kHeaderSize = kMapOffset + kPointerSize;
1865 STATIC_CHECK(kMapOffset == Internals::kHeapObjectMapOffset);
1868 // helpers for calling an ObjectVisitor to iterate over pointers in the
1869 // half-open range [start, end) specified as integer offsets
1870 inline void IteratePointers(ObjectVisitor* v, int start, int end);
1871 // as above, for the single element at "offset"
1872 inline void IteratePointer(ObjectVisitor* v, int offset);
1875 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1879 // This class describes a body of an object of a fixed size
1880 // in which all pointer fields are located in the [start_offset, end_offset)
1882 template<int start_offset, int end_offset, int size>
1883 class FixedBodyDescriptor {
1885 static const int kStartOffset = start_offset;
1886 static const int kEndOffset = end_offset;
1887 static const int kSize = size;
1889 static inline void IterateBody(HeapObject* obj, ObjectVisitor* v);
1891 template<typename StaticVisitor>
1892 static inline void IterateBody(HeapObject* obj) {
1893 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1894 HeapObject::RawField(obj, end_offset));
1899 // This class describes a body of an object of a variable size
1900 // in which all pointer fields are located in the [start_offset, object_size)
1902 template<int start_offset>
1903 class FlexibleBodyDescriptor {
1905 static const int kStartOffset = start_offset;
1907 static inline void IterateBody(HeapObject* obj,
1911 template<typename StaticVisitor>
1912 static inline void IterateBody(HeapObject* obj, int object_size) {
1913 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1914 HeapObject::RawField(obj, object_size));
1919 // The HeapNumber class describes heap allocated numbers that cannot be
1920 // represented in a Smi (small integer)
1921 class HeapNumber: public HeapObject {
1923 // [value]: number value.
1924 inline double value();
1925 inline void set_value(double value);
1928 static inline HeapNumber* cast(Object* obj);
1930 // Dispatched behavior.
1931 bool HeapNumberBooleanValue();
1933 void HeapNumberPrint(FILE* out = stdout);
1934 void HeapNumberPrint(StringStream* accumulator);
1935 DECLARE_VERIFIER(HeapNumber)
1937 inline int get_exponent();
1938 inline int get_sign();
1940 // Layout description.
1941 static const int kValueOffset = HeapObject::kHeaderSize;
1942 // IEEE doubles are two 32 bit words. The first is just mantissa, the second
1943 // is a mixture of sign, exponent and mantissa. Our current platforms are all
1944 // little endian apart from non-EABI arm which is little endian with big
1945 // endian floating point word ordering!
1946 static const int kMantissaOffset = kValueOffset;
1947 static const int kExponentOffset = kValueOffset + 4;
1949 static const int kSize = kValueOffset + kDoubleSize;
1950 static const uint32_t kSignMask = 0x80000000u;
1951 static const uint32_t kExponentMask = 0x7ff00000u;
1952 static const uint32_t kMantissaMask = 0xfffffu;
1953 static const int kMantissaBits = 52;
1954 static const int kExponentBits = 11;
1955 static const int kExponentBias = 1023;
1956 static const int kExponentShift = 20;
1957 static const int kInfinityOrNanExponent =
1958 (kExponentMask >> kExponentShift) - kExponentBias;
1959 static const int kMantissaBitsInTopWord = 20;
1960 static const int kNonMantissaBitsInTopWord = 12;
1963 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
1967 class Float32x4: public HeapObject {
1969 typedef float32x4_value_t value_t;
1970 static const int kLanes = 4;
1971 static const int kValueSize = kFloat32x4Size;
1972 static const InstanceType kInstanceType = FLOAT32x4_TYPE;
1973 static inline const char* Name();
1974 static inline int kRuntimeAllocatorId();
1975 static inline int kMapRootIndex();
1977 // [value]: float32x4 value.
1978 inline float32x4_value_t value();
1979 inline void set_value(float32x4_value_t value);
1982 static inline Float32x4* cast(Object* obj);
1984 inline void Float32x4Print() {
1985 Float32x4Print(stdout);
1987 void Float32x4Print(FILE* out);
1988 void Float32x4Print(StringStream* accumulator);
1989 DECLARE_VERIFIER(Float32x4)
1991 inline float getAt(int index);
1992 inline float x() { return getAt(0); }
1993 inline float y() { return getAt(1); }
1994 inline float z() { return getAt(2); }
1995 inline float w() { return getAt(3); }
1997 // Layout description.
1998 static const int kValueOffset = HeapObject::kHeaderSize;
1999 static const int kSize = kValueOffset + kValueSize;
2002 DISALLOW_IMPLICIT_CONSTRUCTORS(Float32x4);
2006 class Int32x4: public HeapObject {
2008 typedef int32x4_value_t value_t;
2009 static const int kValueSize = kInt32x4Size;
2010 static const InstanceType kInstanceType = INT32x4_TYPE;
2011 static inline const char* Name();
2012 static inline int kRuntimeAllocatorId();
2013 static inline int kMapRootIndex();
2015 // [value]: int32x4 value.
2016 inline int32x4_value_t value();
2017 inline void set_value(int32x4_value_t value);
2020 static inline Int32x4* cast(Object* obj);
2022 inline void Int32x4Print() {
2023 Int32x4Print(stdout);
2025 void Int32x4Print(FILE* out);
2026 void Int32x4Print(StringStream* accumulator);
2027 DECLARE_VERIFIER(Int32x4)
2029 static const int kLanes = 4;
2030 inline int32_t getAt(int32_t index);
2031 inline int32_t x() { return getAt(0); }
2032 inline int32_t y() { return getAt(1); }
2033 inline int32_t z() { return getAt(2); }
2034 inline int32_t w() { return getAt(3); }
2036 // Layout description.
2037 static const int kValueOffset = HeapObject::kHeaderSize;
2038 static const int kSize = kValueOffset + kValueSize;
2041 DISALLOW_IMPLICIT_CONSTRUCTORS(Int32x4);
2045 enum EnsureElementsMode {
2046 DONT_ALLOW_DOUBLE_ELEMENTS,
2047 ALLOW_COPIED_DOUBLE_ELEMENTS,
2048 ALLOW_CONVERTED_DOUBLE_ELEMENTS
2052 // Indicates whether a property should be set or (re)defined. Setting of a
2053 // property causes attributes to remain unchanged, writability to be checked
2054 // and callbacks to be called. Defining of a property causes attributes to
2055 // be updated and callbacks to be overridden.
2056 enum SetPropertyMode {
2062 // Indicator for one component of an AccessorPair.
2063 enum AccessorComponent {
2069 // JSReceiver includes types on which properties can be defined, i.e.,
2070 // JSObject and JSProxy.
2071 class JSReceiver: public HeapObject {
2079 // A non-keyed store is of the form a.x = foo or a["x"] = foo whereas
2080 // a keyed store is of the form a[expression] = foo.
2081 enum StoreFromKeyed {
2082 MAY_BE_STORE_FROM_KEYED,
2083 CERTAINLY_NOT_STORE_FROM_KEYED
2086 // Internal properties (e.g. the hidden properties dictionary) might
2087 // be added even though the receiver is non-extensible.
2088 enum ExtensibilityCheck {
2089 PERFORM_EXTENSIBILITY_CHECK,
2090 OMIT_EXTENSIBILITY_CHECK
2094 static inline JSReceiver* cast(Object* obj);
2096 // Implementation of [[Put]], ECMA-262 5th edition, section 8.12.5.
2097 static Handle<Object> SetProperty(Handle<JSReceiver> object,
2099 Handle<Object> value,
2100 PropertyAttributes attributes,
2101 StrictModeFlag strict_mode,
2102 StoreFromKeyed store_mode =
2103 MAY_BE_STORE_FROM_KEYED);
2104 static Handle<Object> SetElement(Handle<JSReceiver> object,
2106 Handle<Object> value,
2107 PropertyAttributes attributes,
2108 StrictModeFlag strict_mode);
2110 // Implementation of [[HasProperty]], ECMA-262 5th edition, section 8.12.6.
2111 static inline bool HasProperty(Handle<JSReceiver> object, Handle<Name> name);
2112 static inline bool HasLocalProperty(Handle<JSReceiver>, Handle<Name> name);
2113 static inline bool HasElement(Handle<JSReceiver> object, uint32_t index);
2114 static inline bool HasLocalElement(Handle<JSReceiver> object, uint32_t index);
2116 // Implementation of [[Delete]], ECMA-262 5th edition, section 8.12.7.
2117 static Handle<Object> DeleteProperty(Handle<JSReceiver> object,
2119 DeleteMode mode = NORMAL_DELETION);
2120 static Handle<Object> DeleteElement(Handle<JSReceiver> object,
2122 DeleteMode mode = NORMAL_DELETION);
2124 // Tests for the fast common case for property enumeration.
2125 bool IsSimpleEnum();
2127 // Returns the class name ([[Class]] property in the specification).
2128 String* class_name();
2130 // Returns the constructor name (the name (possibly, inferred name) of the
2131 // function that was used to instantiate the object).
2132 String* constructor_name();
2134 inline PropertyAttributes GetPropertyAttribute(Name* name);
2135 PropertyAttributes GetPropertyAttributeWithReceiver(JSReceiver* receiver,
2137 PropertyAttributes GetLocalPropertyAttribute(Name* name);
2139 inline PropertyAttributes GetElementAttribute(uint32_t index);
2140 inline PropertyAttributes GetLocalElementAttribute(uint32_t index);
2142 // Return the object's prototype (might be Heap::null_value()).
2143 inline Object* GetPrototype();
2145 // Return the constructor function (may be Heap::null_value()).
2146 inline Object* GetConstructor();
2148 // Retrieves a permanent object identity hash code. The undefined value might
2149 // be returned in case no hash was created yet.
2150 inline Object* GetIdentityHash();
2152 // Retrieves a permanent object identity hash code. May create and store a
2153 // hash code if needed and none exists.
2154 inline static Handle<Object> GetOrCreateIdentityHash(
2155 Handle<JSReceiver> object);
2157 // Lookup a property. If found, the result is valid and has
2158 // detailed information.
2159 void LocalLookup(Name* name, LookupResult* result,
2160 bool search_hidden_prototypes = false);
2161 void Lookup(Name* name, LookupResult* result);
2164 Smi* GenerateIdentityHash();
2166 static Handle<Object> SetPropertyWithDefinedSetter(Handle<JSReceiver> object,
2167 Handle<JSReceiver> setter,
2168 Handle<Object> value);
2171 PropertyAttributes GetPropertyAttributeForResult(JSReceiver* receiver,
2172 LookupResult* result,
2174 bool continue_search);
2176 static Handle<Object> SetProperty(Handle<JSReceiver> receiver,
2177 LookupResult* result,
2179 Handle<Object> value,
2180 PropertyAttributes attributes,
2181 StrictModeFlag strict_mode,
2182 StoreFromKeyed store_from_keyed);
2184 DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
2187 // Forward declaration for JSObject::GetOrCreateHiddenPropertiesHashTable.
2188 class ObjectHashTable;
2190 // The JSObject describes real heap allocated JavaScript objects with
2192 // Note that the map of JSObject changes during execution to enable inline
2194 class JSObject: public JSReceiver {
2196 // [properties]: Backing storage for properties.
2197 // properties is a FixedArray in the fast case and a Dictionary in the
2199 DECL_ACCESSORS(properties, FixedArray) // Get and set fast properties.
2200 inline void initialize_properties();
2201 inline bool HasFastProperties();
2202 inline NameDictionary* property_dictionary(); // Gets slow properties.
2204 // [elements]: The elements (properties with names that are integers).
2206 // Elements can be in two general modes: fast and slow. Each mode
2207 // corrensponds to a set of object representations of elements that
2208 // have something in common.
2210 // In the fast mode elements is a FixedArray and so each element can
2211 // be quickly accessed. This fact is used in the generated code. The
2212 // elements array can have one of three maps in this mode:
2213 // fixed_array_map, non_strict_arguments_elements_map or
2214 // fixed_cow_array_map (for copy-on-write arrays). In the latter case
2215 // the elements array may be shared by a few objects and so before
2216 // writing to any element the array must be copied. Use
2217 // EnsureWritableFastElements in this case.
2219 // In the slow mode the elements is either a NumberDictionary, an
2220 // ExternalArray, or a FixedArray parameter map for a (non-strict)
2221 // arguments object.
2222 DECL_ACCESSORS(elements, FixedArrayBase)
2223 inline void initialize_elements();
2224 MUST_USE_RESULT inline MaybeObject* ResetElements();
2225 inline ElementsKind GetElementsKind();
2226 inline ElementsAccessor* GetElementsAccessor();
2227 // Returns true if an object has elements of FAST_SMI_ELEMENTS ElementsKind.
2228 inline bool HasFastSmiElements();
2229 // Returns true if an object has elements of FAST_ELEMENTS ElementsKind.
2230 inline bool HasFastObjectElements();
2231 // Returns true if an object has elements of FAST_ELEMENTS or
2232 // FAST_SMI_ONLY_ELEMENTS.
2233 inline bool HasFastSmiOrObjectElements();
2234 // Returns true if an object has any of the fast elements kinds.
2235 inline bool HasFastElements();
2236 // Returns true if an object has elements of FAST_DOUBLE_ELEMENTS
2238 inline bool HasFastDoubleElements();
2239 // Returns true if an object has elements of FAST_HOLEY_*_ELEMENTS
2241 inline bool HasFastHoleyElements();
2242 inline bool HasNonStrictArgumentsElements();
2243 inline bool HasDictionaryElements();
2245 inline bool HasExternalUint8ClampedElements();
2246 inline bool HasExternalArrayElements();
2247 inline bool HasExternalInt8Elements();
2248 inline bool HasExternalUint8Elements();
2249 inline bool HasExternalInt16Elements();
2250 inline bool HasExternalUint16Elements();
2251 inline bool HasExternalInt32Elements();
2252 inline bool HasExternalUint32Elements();
2253 inline bool HasExternalFloat32Elements();
2254 inline bool HasExternalFloat32x4Elements();
2255 inline bool HasExternalInt32x4Elements();
2256 inline bool HasExternalFloat64Elements();
2258 inline bool HasFixedTypedArrayElements();
2260 bool HasFastArgumentsElements();
2261 bool HasDictionaryArgumentsElements();
2262 inline SeededNumberDictionary* element_dictionary(); // Gets slow elements.
2264 inline void set_map_and_elements(
2266 FixedArrayBase* value,
2267 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
2269 // Requires: HasFastElements().
2270 static Handle<FixedArray> EnsureWritableFastElements(
2271 Handle<JSObject> object);
2272 MUST_USE_RESULT inline MaybeObject* EnsureWritableFastElements();
2274 // Collects elements starting at index 0.
2275 // Undefined values are placed after non-undefined values.
2276 // Returns the number of non-undefined values.
2277 static Handle<Object> PrepareElementsForSort(Handle<JSObject> object,
2279 // As PrepareElementsForSort, but only on objects where elements is
2280 // a dictionary, and it will stay a dictionary.
2281 static Handle<Object> PrepareSlowElementsForSort(Handle<JSObject> object,
2283 MUST_USE_RESULT MaybeObject* PrepareSlowElementsForSort(uint32_t limit);
2285 static Handle<Object> GetPropertyWithCallback(Handle<JSObject> object,
2286 Handle<Object> receiver,
2287 Handle<Object> structure,
2290 static Handle<Object> SetPropertyWithCallback(
2291 Handle<JSObject> object,
2292 Handle<Object> structure,
2294 Handle<Object> value,
2295 Handle<JSObject> holder,
2296 StrictModeFlag strict_mode);
2298 static Handle<Object> SetPropertyWithInterceptor(
2299 Handle<JSObject> object,
2301 Handle<Object> value,
2302 PropertyAttributes attributes,
2303 StrictModeFlag strict_mode);
2305 static Handle<Object> SetPropertyForResult(
2306 Handle<JSObject> object,
2307 LookupResult* result,
2309 Handle<Object> value,
2310 PropertyAttributes attributes,
2311 StrictModeFlag strict_mode,
2312 StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
2314 static Handle<Object> SetLocalPropertyIgnoreAttributes(
2315 Handle<JSObject> object,
2317 Handle<Object> value,
2318 PropertyAttributes attributes,
2319 ValueType value_type = OPTIMAL_REPRESENTATION,
2320 StoreMode mode = ALLOW_AS_CONSTANT,
2321 ExtensibilityCheck extensibility_check = PERFORM_EXTENSIBILITY_CHECK);
2323 static inline Handle<String> ExpectedTransitionKey(Handle<Map> map);
2324 static inline Handle<Map> ExpectedTransitionTarget(Handle<Map> map);
2326 // Try to follow an existing transition to a field with attributes NONE. The
2327 // return value indicates whether the transition was successful.
2328 static inline Handle<Map> FindTransitionToField(Handle<Map> map,
2331 // Extend the receiver with a single fast property appeared first in the
2332 // passed map. This also extends the property backing store if necessary.
2333 static void AllocateStorageForMap(Handle<JSObject> object, Handle<Map> map);
2335 // Migrates the given object to a map whose field representations are the
2336 // lowest upper bound of all known representations for that field.
2337 static void MigrateInstance(Handle<JSObject> instance);
2339 // Migrates the given object only if the target map is already available,
2340 // or returns an empty handle if such a map is not yet available.
2341 static Handle<Object> TryMigrateInstance(Handle<JSObject> instance);
2343 // Retrieve a value in a normalized object given a lookup result.
2344 // Handles the special representation of JS global objects.
2345 Object* GetNormalizedProperty(LookupResult* result);
2347 // Sets the property value in a normalized object given a lookup result.
2348 // Handles the special representation of JS global objects.
2349 static void SetNormalizedProperty(Handle<JSObject> object,
2350 LookupResult* result,
2351 Handle<Object> value);
2353 // Sets the property value in a normalized object given (key, value, details).
2354 // Handles the special representation of JS global objects.
2355 static void SetNormalizedProperty(Handle<JSObject> object,
2357 Handle<Object> value,
2358 PropertyDetails details);
2360 static void OptimizeAsPrototype(Handle<JSObject> object);
2362 // Retrieve interceptors.
2363 InterceptorInfo* GetNamedInterceptor();
2364 InterceptorInfo* GetIndexedInterceptor();
2366 // Used from JSReceiver.
2367 PropertyAttributes GetPropertyAttributePostInterceptor(JSObject* receiver,
2369 bool continue_search);
2370 PropertyAttributes GetPropertyAttributeWithInterceptor(JSObject* receiver,
2372 bool continue_search);
2373 PropertyAttributes GetPropertyAttributeWithFailedAccessCheck(
2375 LookupResult* result,
2377 bool continue_search);
2378 PropertyAttributes GetElementAttributeWithReceiver(JSReceiver* receiver,
2380 bool continue_search);
2382 // Retrieves an AccessorPair property from the given object. Might return
2383 // undefined if the property doesn't exist or is of a different kind.
2384 static Handle<Object> GetAccessor(Handle<JSObject> object,
2386 AccessorComponent component);
2388 // Defines an AccessorPair property on the given object.
2389 // TODO(mstarzinger): Rename to SetAccessor() and return empty handle on
2390 // exception instead of letting callers check for scheduled exception.
2391 static void DefineAccessor(Handle<JSObject> object,
2393 Handle<Object> getter,
2394 Handle<Object> setter,
2395 PropertyAttributes attributes,
2396 v8::AccessControl access_control = v8::DEFAULT);
2398 // Defines an AccessorInfo property on the given object.
2399 static Handle<Object> SetAccessor(Handle<JSObject> object,
2400 Handle<AccessorInfo> info);
2402 static Handle<Object> GetPropertyWithInterceptor(
2403 Handle<JSObject> object,
2404 Handle<Object> receiver,
2406 PropertyAttributes* attributes);
2407 static Handle<Object> GetPropertyPostInterceptor(
2408 Handle<JSObject> object,
2409 Handle<Object> receiver,
2411 PropertyAttributes* attributes);
2412 MUST_USE_RESULT MaybeObject* GetLocalPropertyPostInterceptor(
2415 PropertyAttributes* attributes);
2417 // Returns true if this is an instance of an api function and has
2418 // been modified since it was created. May give false positives.
2421 // If the receiver is a JSGlobalProxy this method will return its prototype,
2422 // otherwise the result is the receiver itself.
2423 inline Object* BypassGlobalProxy();
2425 // Accessors for hidden properties object.
2427 // Hidden properties are not local properties of the object itself.
2428 // Instead they are stored in an auxiliary structure kept as a local
2429 // property with a special name Heap::hidden_string(). But if the
2430 // receiver is a JSGlobalProxy then the auxiliary object is a property
2431 // of its prototype, and if it's a detached proxy, then you can't have
2432 // hidden properties.
2434 // Sets a hidden property on this object. Returns this object if successful,
2435 // undefined if called on a detached proxy.
2436 static Handle<Object> SetHiddenProperty(Handle<JSObject> object,
2438 Handle<Object> value);
2439 // Gets the value of a hidden property with the given key. Returns the hole
2440 // if the property doesn't exist (or if called on a detached proxy),
2441 // otherwise returns the value set for the key.
2442 Object* GetHiddenProperty(Name* key);
2443 // Deletes a hidden property. Deleting a non-existing property is
2444 // considered successful.
2445 static void DeleteHiddenProperty(Handle<JSObject> object,
2447 // Returns true if the object has a property with the hidden string as name.
2448 bool HasHiddenProperties();
2450 static void SetIdentityHash(Handle<JSObject> object, Handle<Smi> hash);
2452 inline void ValidateElements();
2454 // Makes sure that this object can contain HeapObject as elements.
2455 static inline void EnsureCanContainHeapObjectElements(Handle<JSObject> obj);
2457 // Makes sure that this object can contain the specified elements.
2458 MUST_USE_RESULT inline MaybeObject* EnsureCanContainElements(
2461 EnsureElementsMode mode);
2462 MUST_USE_RESULT inline MaybeObject* EnsureCanContainElements(
2463 FixedArrayBase* elements,
2465 EnsureElementsMode mode);
2466 MUST_USE_RESULT MaybeObject* EnsureCanContainElements(
2467 Arguments* arguments,
2470 EnsureElementsMode mode);
2472 // Do we want to keep the elements in fast case when increasing the
2474 bool ShouldConvertToSlowElements(int new_capacity);
2475 // Returns true if the backing storage for the slow-case elements of
2476 // this object takes up nearly as much space as a fast-case backing
2477 // storage would. In that case the JSObject should have fast
2479 bool ShouldConvertToFastElements();
2480 // Returns true if the elements of JSObject contains only values that can be
2481 // represented in a FixedDoubleArray and has at least one value that can only
2482 // be represented as a double and not a Smi.
2483 bool ShouldConvertToFastDoubleElements(bool* has_smi_only_elements);
2485 // Computes the new capacity when expanding the elements of a JSObject.
2486 static int NewElementsCapacity(int old_capacity) {
2487 // (old_capacity + 50%) + 16
2488 return old_capacity + (old_capacity >> 1) + 16;
2491 // These methods do not perform access checks!
2492 AccessorPair* GetLocalPropertyAccessorPair(Name* name);
2493 AccessorPair* GetLocalElementAccessorPair(uint32_t index);
2495 static Handle<Object> SetFastElement(Handle<JSObject> object, uint32_t index,
2496 Handle<Object> value,
2497 StrictModeFlag strict_mode,
2498 bool check_prototype);
2500 static Handle<Object> SetOwnElement(Handle<JSObject> object,
2502 Handle<Object> value,
2503 StrictModeFlag strict_mode);
2505 // Empty handle is returned if the element cannot be set to the given value.
2506 static Handle<Object> SetElement(
2507 Handle<JSObject> object,
2509 Handle<Object> value,
2510 PropertyAttributes attributes,
2511 StrictModeFlag strict_mode,
2512 bool check_prototype = true,
2513 SetPropertyMode set_mode = SET_PROPERTY);
2515 // Returns the index'th element.
2516 // The undefined object if index is out of bounds.
2517 MUST_USE_RESULT MaybeObject* GetElementWithInterceptor(Object* receiver,
2520 enum SetFastElementsCapacitySmiMode {
2523 kDontAllowSmiElements
2526 static Handle<FixedArray> SetFastElementsCapacityAndLength(
2527 Handle<JSObject> object,
2530 SetFastElementsCapacitySmiMode smi_mode);
2531 // Replace the elements' backing store with fast elements of the given
2532 // capacity. Update the length for JSArrays. Returns the new backing
2534 MUST_USE_RESULT MaybeObject* SetFastElementsCapacityAndLength(
2537 SetFastElementsCapacitySmiMode smi_mode);
2538 static void SetFastDoubleElementsCapacityAndLength(
2539 Handle<JSObject> object,
2542 MUST_USE_RESULT MaybeObject* SetFastDoubleElementsCapacityAndLength(
2546 // Lookup interceptors are used for handling properties controlled by host
2548 inline bool HasNamedInterceptor();
2549 inline bool HasIndexedInterceptor();
2551 // Support functions for v8 api (needed for correct interceptor behavior).
2552 static bool HasRealNamedProperty(Handle<JSObject> object,
2554 static bool HasRealElementProperty(Handle<JSObject> object, uint32_t index);
2555 static bool HasRealNamedCallbackProperty(Handle<JSObject> object,
2558 // Get the header size for a JSObject. Used to compute the index of
2559 // internal fields as well as the number of internal fields.
2560 inline int GetHeaderSize();
2562 inline int GetInternalFieldCount();
2563 inline int GetInternalFieldOffset(int index);
2564 inline Object* GetInternalField(int index);
2565 inline void SetInternalField(int index, Object* value);
2566 inline void SetInternalField(int index, Smi* value);
2568 // The following lookup functions skip interceptors.
2569 void LocalLookupRealNamedProperty(Name* name, LookupResult* result);
2570 void LookupRealNamedProperty(Name* name, LookupResult* result);
2571 void LookupRealNamedPropertyInPrototypes(Name* name, LookupResult* result);
2572 void LookupCallbackProperty(Name* name, LookupResult* result);
2574 // Returns the number of properties on this object filtering out properties
2575 // with the specified attributes (ignoring interceptors).
2576 int NumberOfLocalProperties(PropertyAttributes filter = NONE);
2577 // Fill in details for properties into storage starting at the specified
2579 void GetLocalPropertyNames(
2580 FixedArray* storage, int index, PropertyAttributes filter = NONE);
2582 // Returns the number of properties on this object filtering out properties
2583 // with the specified attributes (ignoring interceptors).
2584 int NumberOfLocalElements(PropertyAttributes filter);
2585 // Returns the number of enumerable elements (ignoring interceptors).
2586 int NumberOfEnumElements();
2587 // Returns the number of elements on this object filtering out elements
2588 // with the specified attributes (ignoring interceptors).
2589 int GetLocalElementKeys(FixedArray* storage, PropertyAttributes filter);
2590 // Count and fill in the enumerable elements into storage.
2591 // (storage->length() == NumberOfEnumElements()).
2592 // If storage is NULL, will count the elements without adding
2593 // them to any storage.
2594 // Returns the number of enumerable elements.
2595 int GetEnumElementKeys(FixedArray* storage);
2597 // Returns a new map with all transitions dropped from the object's current
2598 // map and the ElementsKind set.
2599 static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
2600 ElementsKind to_kind);
2601 inline MUST_USE_RESULT MaybeObject* GetElementsTransitionMap(
2603 ElementsKind elements_kind);
2604 MUST_USE_RESULT MaybeObject* GetElementsTransitionMapSlow(
2605 ElementsKind elements_kind);
2607 static void TransitionElementsKind(Handle<JSObject> object,
2608 ElementsKind to_kind);
2610 MUST_USE_RESULT MaybeObject* TransitionElementsKind(ElementsKind to_kind);
2612 // TODO(mstarzinger): Both public because of ConvertAnsSetLocalProperty().
2613 static void MigrateToMap(Handle<JSObject> object, Handle<Map> new_map);
2614 static void GeneralizeFieldRepresentation(Handle<JSObject> object,
2616 Representation new_representation,
2617 StoreMode store_mode);
2619 // Convert the object to use the canonical dictionary
2620 // representation. If the object is expected to have additional properties
2621 // added this number can be indicated to have the backing store allocated to
2622 // an initial capacity for holding these properties.
2623 static void NormalizeProperties(Handle<JSObject> object,
2624 PropertyNormalizationMode mode,
2625 int expected_additional_properties);
2627 // Convert and update the elements backing store to be a
2628 // SeededNumberDictionary dictionary. Returns the backing after conversion.
2629 static Handle<SeededNumberDictionary> NormalizeElements(
2630 Handle<JSObject> object);
2632 MUST_USE_RESULT MaybeObject* NormalizeElements();
2634 // Transform slow named properties to fast variants.
2635 static void TransformToFastProperties(Handle<JSObject> object,
2636 int unused_property_fields);
2638 // Access fast-case object properties at index.
2639 MUST_USE_RESULT inline MaybeObject* FastPropertyAt(
2640 Representation representation,
2642 inline Object* RawFastPropertyAt(int index);
2643 inline void FastPropertyAtPut(int index, Object* value);
2645 // Access to in object properties.
2646 inline int GetInObjectPropertyOffset(int index);
2647 inline Object* InObjectPropertyAt(int index);
2648 inline Object* InObjectPropertyAtPut(int index,
2650 WriteBarrierMode mode
2651 = UPDATE_WRITE_BARRIER);
2653 // Set the object's prototype (only JSReceiver and null are allowed values).
2654 static Handle<Object> SetPrototype(Handle<JSObject> object,
2655 Handle<Object> value,
2656 bool skip_hidden_prototypes = false);
2658 // Initializes the body after properties slot, properties slot is
2659 // initialized by set_properties. Fill the pre-allocated fields with
2660 // pre_allocated_value and the rest with filler_value.
2661 // Note: this call does not update write barrier, the caller is responsible
2662 // to ensure that |filler_value| can be collected without WB here.
2663 inline void InitializeBody(Map* map,
2664 Object* pre_allocated_value,
2665 Object* filler_value);
2667 // Check whether this object references another object
2668 bool ReferencesObject(Object* obj);
2670 // Disalow further properties to be added to the object.
2671 static Handle<Object> PreventExtensions(Handle<JSObject> object);
2673 // ES5 Object.freeze
2674 static Handle<Object> Freeze(Handle<JSObject> object);
2676 // Called the first time an object is observed with ES7 Object.observe.
2677 static void SetObserved(Handle<JSObject> object);
2680 enum DeepCopyHints {
2682 kObjectIsShallowArray = 1
2685 static Handle<JSObject> Copy(Handle<JSObject> object);
2686 static Handle<JSObject> DeepCopy(Handle<JSObject> object,
2687 AllocationSiteUsageContext* site_context,
2688 DeepCopyHints hints = kNoHints);
2689 static Handle<JSObject> DeepWalk(Handle<JSObject> object,
2690 AllocationSiteCreationContext* site_context);
2693 static inline JSObject* cast(Object* obj);
2695 // Dispatched behavior.
2696 void JSObjectShortPrint(StringStream* accumulator);
2697 DECLARE_PRINTER(JSObject)
2698 DECLARE_VERIFIER(JSObject)
2700 void PrintProperties(FILE* out = stdout);
2701 void PrintElements(FILE* out = stdout);
2702 void PrintTransitions(FILE* out = stdout);
2705 void PrintElementsTransition(
2706 FILE* file, ElementsKind from_kind, FixedArrayBase* from_elements,
2707 ElementsKind to_kind, FixedArrayBase* to_elements);
2709 void PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map);
2712 // Structure for collecting spill information about JSObjects.
2713 class SpillInformation {
2717 int number_of_objects_;
2718 int number_of_objects_with_fast_properties_;
2719 int number_of_objects_with_fast_elements_;
2720 int number_of_fast_used_fields_;
2721 int number_of_fast_unused_fields_;
2722 int number_of_slow_used_properties_;
2723 int number_of_slow_unused_properties_;
2724 int number_of_fast_used_elements_;
2725 int number_of_fast_unused_elements_;
2726 int number_of_slow_used_elements_;
2727 int number_of_slow_unused_elements_;
2730 void IncrementSpillStatistics(SpillInformation* info);
2734 // If a GC was caused while constructing this object, the elements pointer
2735 // may point to a one pointer filler map. The object won't be rooted, but
2736 // our heap verification code could stumble across it.
2737 bool ElementsAreSafeToExamine();
2740 Object* SlowReverseLookup(Object* value);
2742 // Maximal number of fast properties for the JSObject. Used to
2743 // restrict the number of map transitions to avoid an explosion in
2744 // the number of maps for objects used as dictionaries.
2745 inline bool TooManyFastProperties(
2746 StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
2748 // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2749 // Also maximal value of JSArray's length property.
2750 static const uint32_t kMaxElementCount = 0xffffffffu;
2752 // Constants for heuristics controlling conversion of fast elements
2753 // to slow elements.
2755 // Maximal gap that can be introduced by adding an element beyond
2756 // the current elements length.
2757 static const uint32_t kMaxGap = 1024;
2759 // Maximal length of fast elements array that won't be checked for
2760 // being dense enough on expansion.
2761 static const int kMaxUncheckedFastElementsLength = 5000;
2763 // Same as above but for old arrays. This limit is more strict. We
2764 // don't want to be wasteful with long lived objects.
2765 static const int kMaxUncheckedOldFastElementsLength = 500;
2767 // Note that Page::kMaxRegularHeapObjectSize puts a limit on
2768 // permissible values (see the ASSERT in heap.cc).
2769 static const int kInitialMaxFastElementArray = 100000;
2771 static const int kFastPropertiesSoftLimit = 12;
2772 static const int kMaxFastProperties = 64;
2773 static const int kMaxInstanceSize = 255 * kPointerSize;
2774 // When extending the backing storage for property values, we increase
2775 // its size by more than the 1 entry necessary, so sequentially adding fields
2776 // to the same object requires fewer allocations and copies.
2777 static const int kFieldsAdded = 3;
2779 // Layout description.
2780 static const int kPropertiesOffset = HeapObject::kHeaderSize;
2781 static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2782 static const int kHeaderSize = kElementsOffset + kPointerSize;
2784 STATIC_CHECK(kHeaderSize == Internals::kJSObjectHeaderSize);
2786 class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2788 static inline int SizeOf(Map* map, HeapObject* object);
2791 // Enqueue change record for Object.observe. May cause GC.
2792 static void EnqueueChangeRecord(Handle<JSObject> object,
2795 Handle<Object> old_value);
2798 friend class DictionaryElementsAccessor;
2799 friend class JSReceiver;
2800 friend class Object;
2802 static void UpdateAllocationSite(Handle<JSObject> object,
2803 ElementsKind to_kind);
2804 MUST_USE_RESULT MaybeObject* UpdateAllocationSite(ElementsKind to_kind);
2806 // Used from Object::GetProperty().
2807 static Handle<Object> GetPropertyWithFailedAccessCheck(
2808 Handle<JSObject> object,
2809 Handle<Object> receiver,
2810 LookupResult* result,
2812 PropertyAttributes* attributes);
2814 MUST_USE_RESULT MaybeObject* GetElementWithCallback(Object* receiver,
2818 MUST_USE_RESULT PropertyAttributes GetElementAttributeWithInterceptor(
2819 JSReceiver* receiver,
2821 bool continue_search);
2822 MUST_USE_RESULT PropertyAttributes GetElementAttributeWithoutInterceptor(
2823 JSReceiver* receiver,
2825 bool continue_search);
2826 static Handle<Object> SetElementWithCallback(
2827 Handle<JSObject> object,
2828 Handle<Object> structure,
2830 Handle<Object> value,
2831 Handle<JSObject> holder,
2832 StrictModeFlag strict_mode);
2833 static Handle<Object> SetElementWithInterceptor(
2834 Handle<JSObject> object,
2836 Handle<Object> value,
2837 PropertyAttributes attributes,
2838 StrictModeFlag strict_mode,
2839 bool check_prototype,
2840 SetPropertyMode set_mode);
2841 static Handle<Object> SetElementWithoutInterceptor(
2842 Handle<JSObject> object,
2844 Handle<Object> value,
2845 PropertyAttributes attributes,
2846 StrictModeFlag strict_mode,
2847 bool check_prototype,
2848 SetPropertyMode set_mode);
2849 static Handle<Object> SetElementWithCallbackSetterInPrototypes(
2850 Handle<JSObject> object,
2852 Handle<Object> value,
2854 StrictModeFlag strict_mode);
2855 static Handle<Object> SetDictionaryElement(
2856 Handle<JSObject> object,
2858 Handle<Object> value,
2859 PropertyAttributes attributes,
2860 StrictModeFlag strict_mode,
2861 bool check_prototype,
2862 SetPropertyMode set_mode = SET_PROPERTY);
2863 static Handle<Object> SetFastDoubleElement(
2864 Handle<JSObject> object,
2866 Handle<Object> value,
2867 StrictModeFlag strict_mode,
2868 bool check_prototype = true);
2870 // Searches the prototype chain for property 'name'. If it is found and
2871 // has a setter, invoke it and set '*done' to true. If it is found and is
2872 // read-only, reject and set '*done' to true. Otherwise, set '*done' to
2873 // false. Can throw and return an empty handle with '*done==true'.
2874 static Handle<Object> SetPropertyViaPrototypes(
2875 Handle<JSObject> object,
2877 Handle<Object> value,
2878 PropertyAttributes attributes,
2879 StrictModeFlag strict_mode,
2881 static Handle<Object> SetPropertyPostInterceptor(
2882 Handle<JSObject> object,
2884 Handle<Object> value,
2885 PropertyAttributes attributes,
2886 StrictModeFlag strict_mode);
2887 static Handle<Object> SetPropertyUsingTransition(
2888 Handle<JSObject> object,
2889 LookupResult* lookup,
2891 Handle<Object> value,
2892 PropertyAttributes attributes);
2893 static Handle<Object> SetPropertyWithFailedAccessCheck(
2894 Handle<JSObject> object,
2895 LookupResult* result,
2897 Handle<Object> value,
2898 bool check_prototype,
2899 StrictModeFlag strict_mode);
2901 // Add a property to an object.
2902 static Handle<Object> AddProperty(
2903 Handle<JSObject> object,
2905 Handle<Object> value,
2906 PropertyAttributes attributes,
2907 StrictModeFlag strict_mode,
2908 StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED,
2909 ExtensibilityCheck extensibility_check = PERFORM_EXTENSIBILITY_CHECK,
2910 ValueType value_type = OPTIMAL_REPRESENTATION,
2911 StoreMode mode = ALLOW_AS_CONSTANT,
2912 TransitionFlag flag = INSERT_TRANSITION);
2914 // Add a constant function property to a fast-case object.
2915 // This leaves a CONSTANT_TRANSITION in the old map, and
2916 // if it is called on a second object with this map, a
2917 // normal property is added instead, with a map transition.
2918 // This avoids the creation of many maps with the same constant
2919 // function, all orphaned.
2920 static void AddConstantProperty(Handle<JSObject> object,
2922 Handle<Object> constant,
2923 PropertyAttributes attributes,
2924 TransitionFlag flag);
2926 // Add a property to a fast-case object.
2927 static void AddFastProperty(Handle<JSObject> object,
2929 Handle<Object> value,
2930 PropertyAttributes attributes,
2931 StoreFromKeyed store_mode,
2932 ValueType value_type,
2933 TransitionFlag flag);
2935 // Add a property to a fast-case object using a map transition to
2937 static void AddFastPropertyUsingMap(Handle<JSObject> object,
2938 Handle<Map> new_map,
2940 Handle<Object> value,
2942 Representation representation);
2944 // Add a property to a slow-case object.
2945 static void AddSlowProperty(Handle<JSObject> object,
2947 Handle<Object> value,
2948 PropertyAttributes attributes);
2950 static Handle<Object> DeleteProperty(Handle<JSObject> object,
2953 static Handle<Object> DeletePropertyPostInterceptor(Handle<JSObject> object,
2956 static Handle<Object> DeletePropertyWithInterceptor(Handle<JSObject> object,
2959 // Deletes the named property in a normalized object.
2960 static Handle<Object> DeleteNormalizedProperty(Handle<JSObject> object,
2964 static Handle<Object> DeleteElement(Handle<JSObject> object,
2967 static Handle<Object> DeleteElementWithInterceptor(Handle<JSObject> object,
2970 bool ReferencesObjectFromElements(FixedArray* elements,
2974 // Returns true if most of the elements backing storage is used.
2975 bool HasDenseElements();
2977 // Gets the current elements capacity and the number of used elements.
2978 void GetElementsCapacityAndUsage(int* capacity, int* used);
2980 bool CanSetCallback(Name* name);
2981 static void SetElementCallback(Handle<JSObject> object,
2983 Handle<Object> structure,
2984 PropertyAttributes attributes);
2985 static void SetPropertyCallback(Handle<JSObject> object,
2987 Handle<Object> structure,
2988 PropertyAttributes attributes);
2989 static void DefineElementAccessor(Handle<JSObject> object,
2991 Handle<Object> getter,
2992 Handle<Object> setter,
2993 PropertyAttributes attributes,
2994 v8::AccessControl access_control);
2995 static Handle<AccessorPair> CreateAccessorPairFor(Handle<JSObject> object,
2997 static void DefinePropertyAccessor(Handle<JSObject> object,
2999 Handle<Object> getter,
3000 Handle<Object> setter,
3001 PropertyAttributes attributes,
3002 v8::AccessControl access_control);
3004 // Try to define a single accessor paying attention to map transitions.
3005 // Returns false if this was not possible and we have to use the slow case.
3006 static bool DefineFastAccessor(Handle<JSObject> object,
3008 AccessorComponent component,
3009 Handle<Object> accessor,
3010 PropertyAttributes attributes);
3013 // Return the hash table backing store or the inline stored identity hash,
3014 // whatever is found.
3015 MUST_USE_RESULT Object* GetHiddenPropertiesHashTable();
3017 // Return the hash table backing store for hidden properties. If there is no
3018 // backing store, allocate one.
3019 static Handle<ObjectHashTable> GetOrCreateHiddenPropertiesHashtable(
3020 Handle<JSObject> object);
3022 // Set the hidden property backing store to either a hash table or
3023 // the inline-stored identity hash.
3024 static Handle<Object> SetHiddenPropertiesHashTable(
3025 Handle<JSObject> object,
3026 Handle<Object> value);
3028 MUST_USE_RESULT Object* GetIdentityHash();
3030 static Handle<Object> GetOrCreateIdentityHash(Handle<JSObject> object);
3032 DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
3036 // Common superclass for FixedArrays that allow implementations to share
3037 // common accessors and some code paths.
3038 class FixedArrayBase: public HeapObject {
3040 // [length]: length of the array.
3041 inline int length();
3042 inline void set_length(int value);
3044 inline static FixedArrayBase* cast(Object* object);
3046 // Layout description.
3047 // Length is smi tagged when it is stored.
3048 static const int kLengthOffset = HeapObject::kHeaderSize;
3049 static const int kHeaderSize = kLengthOffset + kPointerSize;
3053 class FixedDoubleArray;
3054 class IncrementalMarking;
3057 // FixedArray describes fixed-sized arrays with element type Object*.
3058 class FixedArray: public FixedArrayBase {
3060 // Setter and getter for elements.
3061 inline Object* get(int index);
3062 // Setter that uses write barrier.
3063 inline void set(int index, Object* value);
3064 inline bool is_the_hole(int index);
3066 // Setter that doesn't need write barrier.
3067 inline void set(int index, Smi* value);
3068 // Setter with explicit barrier mode.
3069 inline void set(int index, Object* value, WriteBarrierMode mode);
3071 // Setters for frequently used oddballs located in old space.
3072 inline void set_undefined(int index);
3073 inline void set_null(int index);
3074 inline void set_the_hole(int index);
3076 inline Object** GetFirstElementAddress();
3077 inline bool ContainsOnlySmisOrHoles();
3079 // Gives access to raw memory which stores the array's data.
3080 inline Object** data_start();
3082 // Shrink length and insert filler objects.
3083 void Shrink(int length);
3086 MUST_USE_RESULT inline MaybeObject* Copy();
3087 MUST_USE_RESULT MaybeObject* CopySize(int new_length,
3088 PretenureFlag pretenure = NOT_TENURED);
3090 // Add the elements of a JSArray to this FixedArray.
3091 MUST_USE_RESULT MaybeObject* AddKeysFromJSArray(JSArray* array);
3093 // Compute the union of this and other.
3094 MUST_USE_RESULT MaybeObject* UnionOfKeys(FixedArray* other);
3096 // Copy a sub array from the receiver to dest.
3097 void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
3099 // Garbage collection support.
3100 static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
3102 // Code Generation support.
3103 static int OffsetOfElementAt(int index) { return SizeFor(index); }
3105 // Garbage collection support.
3106 Object** RawFieldOfElementAt(int index) {
3107 return HeapObject::RawField(this, OffsetOfElementAt(index));
3111 static inline FixedArray* cast(Object* obj);
3113 // Maximal allowed size, in bytes, of a single FixedArray.
3114 // Prevents overflowing size computations, as well as extreme memory
3116 static const int kMaxSize = 128 * MB * kPointerSize;
3117 // Maximally allowed length of a FixedArray.
3118 static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
3120 // Dispatched behavior.
3121 DECLARE_PRINTER(FixedArray)
3122 DECLARE_VERIFIER(FixedArray)
3124 // Checks if two FixedArrays have identical contents.
3125 bool IsEqualTo(FixedArray* other);
3128 // Swap two elements in a pair of arrays. If this array and the
3129 // numbers array are the same object, the elements are only swapped
3131 void SwapPairs(FixedArray* numbers, int i, int j);
3133 // Sort prefix of this array and the numbers array as pairs wrt. the
3134 // numbers. If the numbers array and the this array are the same
3135 // object, the prefix of this array is sorted.
3136 void SortPairs(FixedArray* numbers, uint32_t len);
3138 class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
3140 static inline int SizeOf(Map* map, HeapObject* object) {
3141 return SizeFor(reinterpret_cast<FixedArray*>(object)->length());
3146 // Set operation on FixedArray without using write barriers. Can
3147 // only be used for storing old space objects or smis.
3148 static inline void NoWriteBarrierSet(FixedArray* array,
3152 // Set operation on FixedArray without incremental write barrier. Can
3153 // only be used if the object is guaranteed to be white (whiteness witness
3155 static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
3160 STATIC_CHECK(kHeaderSize == Internals::kFixedArrayHeaderSize);
3162 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
3166 // FixedDoubleArray describes fixed-sized arrays with element type double.
3167 class FixedDoubleArray: public FixedArrayBase {
3169 // Setter and getter for elements.
3170 inline double get_scalar(int index);
3171 inline int64_t get_representation(int index);
3172 MUST_USE_RESULT inline MaybeObject* get(int index);
3173 inline void set(int index, double value);
3174 inline void set_the_hole(int index);
3176 // Checking for the hole.
3177 inline bool is_the_hole(int index);
3180 MUST_USE_RESULT inline MaybeObject* Copy();
3182 // Garbage collection support.
3183 inline static int SizeFor(int length) {
3184 return kHeaderSize + length * kDoubleSize;
3187 // Gives access to raw memory which stores the array's data.
3188 inline double* data_start();
3190 // Code Generation support.
3191 static int OffsetOfElementAt(int index) { return SizeFor(index); }
3193 inline static bool is_the_hole_nan(double value);
3194 inline static double hole_nan_as_double();
3195 inline static double canonical_not_the_hole_nan_as_double();
3198 static inline FixedDoubleArray* cast(Object* obj);
3200 // Maximal allowed size, in bytes, of a single FixedDoubleArray.
3201 // Prevents overflowing size computations, as well as extreme memory
3203 static const int kMaxSize = 512 * MB;
3204 // Maximally allowed length of a FixedArray.
3205 static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
3207 // Dispatched behavior.
3208 DECLARE_PRINTER(FixedDoubleArray)
3209 DECLARE_VERIFIER(FixedDoubleArray)
3212 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
3216 // ConstantPoolArray describes a fixed-sized array containing constant pool
3218 // The format of the pool is:
3219 // [0]: Field holding the first index which is a pointer entry
3220 // [1]: Field holding the first index which is a int32 entry
3221 // [2] ... [first_ptr_index() - 1]: 64 bit entries
3222 // [first_ptr_index()] ... [first_int32_index() - 1]: pointer entries
3223 // [first_int32_index()] ... [length - 1]: 32 bit entries
3224 class ConstantPoolArray: public FixedArrayBase {
3226 // Getters for the field storing the first index for different type entries.
3227 inline int first_ptr_index();
3228 inline int first_int64_index();
3229 inline int first_int32_index();
3231 // Getters for counts of different type entries.
3232 inline int count_of_ptr_entries();
3233 inline int count_of_int64_entries();
3234 inline int count_of_int32_entries();
3236 // Setter and getter for pool elements.
3237 inline Object* get_ptr_entry(int index);
3238 inline int64_t get_int64_entry(int index);
3239 inline int32_t get_int32_entry(int index);
3240 inline double get_int64_entry_as_double(int index);
3242 inline void set(int index, Object* value);
3243 inline void set(int index, int64_t value);
3244 inline void set(int index, double value);
3245 inline void set(int index, int32_t value);
3247 // Set up initial state.
3248 inline void SetEntryCounts(int number_of_int64_entries,
3249 int number_of_ptr_entries,
3250 int number_of_int32_entries);
3253 MUST_USE_RESULT inline MaybeObject* Copy();
3255 // Garbage collection support.
3256 inline static int SizeFor(int number_of_int64_entries,
3257 int number_of_ptr_entries,
3258 int number_of_int32_entries) {
3259 return RoundUp(OffsetAt(number_of_int64_entries,
3260 number_of_ptr_entries,
3261 number_of_int32_entries),
3265 // Code Generation support.
3266 inline int OffsetOfElementAt(int index) {
3267 ASSERT(index < length());
3268 if (index >= first_int32_index()) {
3269 return OffsetAt(count_of_int64_entries(), count_of_ptr_entries(),
3270 index - first_int32_index());
3271 } else if (index >= first_ptr_index()) {
3272 return OffsetAt(count_of_int64_entries(), index - first_ptr_index(), 0);
3274 return OffsetAt(index, 0, 0);
3279 static inline ConstantPoolArray* cast(Object* obj);
3281 // Layout description.
3282 static const int kFirstPointerIndexOffset = FixedArray::kHeaderSize;
3283 static const int kFirstInt32IndexOffset =
3284 kFirstPointerIndexOffset + kPointerSize;
3285 static const int kFirstOffset = kFirstInt32IndexOffset + kPointerSize;
3287 // Dispatched behavior.
3288 void ConstantPoolIterateBody(ObjectVisitor* v);
3290 DECLARE_PRINTER(ConstantPoolArray)
3291 DECLARE_VERIFIER(ConstantPoolArray)
3294 inline void set_first_ptr_index(int value);
3295 inline void set_first_int32_index(int value);
3297 inline static int OffsetAt(int number_of_int64_entries,
3298 int number_of_ptr_entries,
3299 int number_of_int32_entries) {
3301 + (number_of_int64_entries * kInt64Size)
3302 + (number_of_ptr_entries * kPointerSize)
3303 + (number_of_int32_entries * kInt32Size);
3306 DISALLOW_IMPLICIT_CONSTRUCTORS(ConstantPoolArray);
3310 // DescriptorArrays are fixed arrays used to hold instance descriptors.
3311 // The format of the these objects is:
3312 // [0]: Number of descriptors
3313 // [1]: Either Smi(0) if uninitialized, or a pointer to small fixed array:
3314 // [0]: pointer to fixed array with enum cache
3315 // [1]: either Smi(0) or pointer to fixed array with indices
3317 // [2 + number of descriptors * kDescriptorSize]: start of slack
3318 class DescriptorArray: public FixedArray {
3320 // WhitenessWitness is used to prove that a descriptor array is white
3321 // (unmarked), so incremental write barriers can be skipped because the
3322 // marking invariant cannot be broken and slots pointing into evacuation
3323 // candidates will be discovered when the object is scanned. A witness is
3324 // always stack-allocated right after creating an array. By allocating a
3325 // witness, incremental marking is globally disabled. The witness is then
3326 // passed along wherever needed to statically prove that the array is known to
3328 class WhitenessWitness {
3330 inline explicit WhitenessWitness(FixedArray* array);
3331 inline ~WhitenessWitness();
3334 IncrementalMarking* marking_;
3337 // Returns true for both shared empty_descriptor_array and for smis, which the
3338 // map uses to encode additional bit fields when the descriptor array is not
3340 inline bool IsEmpty();
3342 // Returns the number of descriptors in the array.
3343 int number_of_descriptors() {
3344 ASSERT(length() >= kFirstIndex || IsEmpty());
3346 return len == 0 ? 0 : Smi::cast(get(kDescriptorLengthIndex))->value();
3349 int number_of_descriptors_storage() {
3351 return len == 0 ? 0 : (len - kFirstIndex) / kDescriptorSize;
3354 int NumberOfSlackDescriptors() {
3355 return number_of_descriptors_storage() - number_of_descriptors();
3358 inline void SetNumberOfDescriptors(int number_of_descriptors);
3359 inline int number_of_entries() { return number_of_descriptors(); }
3361 bool HasEnumCache() {
3362 return !IsEmpty() && !get(kEnumCacheIndex)->IsSmi();
3365 void CopyEnumCacheFrom(DescriptorArray* array) {
3366 set(kEnumCacheIndex, array->get(kEnumCacheIndex));
3369 FixedArray* GetEnumCache() {
3370 ASSERT(HasEnumCache());
3371 FixedArray* bridge = FixedArray::cast(get(kEnumCacheIndex));
3372 return FixedArray::cast(bridge->get(kEnumCacheBridgeCacheIndex));
3375 bool HasEnumIndicesCache() {
3376 if (IsEmpty()) return false;
3377 Object* object = get(kEnumCacheIndex);
3378 if (object->IsSmi()) return false;
3379 FixedArray* bridge = FixedArray::cast(object);
3380 return !bridge->get(kEnumCacheBridgeIndicesCacheIndex)->IsSmi();
3383 FixedArray* GetEnumIndicesCache() {
3384 ASSERT(HasEnumIndicesCache());
3385 FixedArray* bridge = FixedArray::cast(get(kEnumCacheIndex));
3386 return FixedArray::cast(bridge->get(kEnumCacheBridgeIndicesCacheIndex));
3389 Object** GetEnumCacheSlot() {
3390 ASSERT(HasEnumCache());
3391 return HeapObject::RawField(reinterpret_cast<HeapObject*>(this),
3395 void ClearEnumCache();
3397 // Initialize or change the enum cache,
3398 // using the supplied storage for the small "bridge".
3399 void SetEnumCache(FixedArray* bridge_storage,
3400 FixedArray* new_cache,
3401 Object* new_index_cache);
3403 // Accessors for fetching instance descriptor at descriptor number.
3404 inline Name* GetKey(int descriptor_number);
3405 inline Object** GetKeySlot(int descriptor_number);
3406 inline Object* GetValue(int descriptor_number);
3407 inline Object** GetValueSlot(int descriptor_number);
3408 inline Object** GetDescriptorStartSlot(int descriptor_number);
3409 inline Object** GetDescriptorEndSlot(int descriptor_number);
3410 inline PropertyDetails GetDetails(int descriptor_number);
3411 inline PropertyType GetType(int descriptor_number);
3412 inline int GetFieldIndex(int descriptor_number);
3413 inline Object* GetConstant(int descriptor_number);
3414 inline Object* GetCallbacksObject(int descriptor_number);
3415 inline AccessorDescriptor* GetCallbacks(int descriptor_number);
3417 inline Name* GetSortedKey(int descriptor_number);
3418 inline int GetSortedKeyIndex(int descriptor_number);
3419 inline void SetSortedKey(int pointer, int descriptor_number);
3420 inline void InitializeRepresentations(Representation representation);
3421 inline void SetRepresentation(int descriptor_number,
3422 Representation representation);
3424 // Accessor for complete descriptor.
3425 inline void Get(int descriptor_number, Descriptor* desc);
3426 inline void Set(int descriptor_number,
3428 const WhitenessWitness&);
3429 inline void Set(int descriptor_number, Descriptor* desc);
3431 // Append automatically sets the enumeration index. This should only be used
3432 // to add descriptors in bulk at the end, followed by sorting the descriptor
3434 inline void Append(Descriptor* desc, const WhitenessWitness&);
3435 inline void Append(Descriptor* desc);
3437 // Transfer a complete descriptor from the src descriptor array to this
3438 // descriptor array.
3439 void CopyFrom(int dst_index,
3440 DescriptorArray* src,
3442 const WhitenessWitness&);
3443 static Handle<DescriptorArray> Merge(Handle<DescriptorArray> desc,
3448 StoreMode store_mode,
3449 Handle<DescriptorArray> other);
3450 MUST_USE_RESULT MaybeObject* Merge(int verbatim,
3454 StoreMode store_mode,
3455 DescriptorArray* other);
3457 bool IsMoreGeneralThan(int verbatim,
3460 DescriptorArray* other);
3462 MUST_USE_RESULT MaybeObject* CopyUpTo(int enumeration_index) {
3463 return CopyUpToAddAttributes(enumeration_index, NONE);
3466 static Handle<DescriptorArray> CopyUpToAddAttributes(
3467 Handle<DescriptorArray> desc,
3468 int enumeration_index,
3469 PropertyAttributes attributes);
3470 MUST_USE_RESULT MaybeObject* CopyUpToAddAttributes(
3471 int enumeration_index,
3472 PropertyAttributes attributes);
3474 // Sort the instance descriptors by the hash codes of their keys.
3477 // Search the instance descriptors for given name.
3478 INLINE(int Search(Name* name, int number_of_own_descriptors));
3480 // As the above, but uses DescriptorLookupCache and updates it when
3482 INLINE(int SearchWithCache(Name* name, Map* map));
3484 // Allocates a DescriptorArray, but returns the singleton
3485 // empty descriptor array object if number_of_descriptors is 0.
3486 MUST_USE_RESULT static MaybeObject* Allocate(Isolate* isolate,
3487 int number_of_descriptors,
3491 static inline DescriptorArray* cast(Object* obj);
3493 // Constant for denoting key was not found.
3494 static const int kNotFound = -1;
3496 static const int kDescriptorLengthIndex = 0;
3497 static const int kEnumCacheIndex = 1;
3498 static const int kFirstIndex = 2;
3500 // The length of the "bridge" to the enum cache.
3501 static const int kEnumCacheBridgeLength = 2;
3502 static const int kEnumCacheBridgeCacheIndex = 0;
3503 static const int kEnumCacheBridgeIndicesCacheIndex = 1;
3505 // Layout description.
3506 static const int kDescriptorLengthOffset = FixedArray::kHeaderSize;
3507 static const int kEnumCacheOffset = kDescriptorLengthOffset + kPointerSize;
3508 static const int kFirstOffset = kEnumCacheOffset + kPointerSize;
3510 // Layout description for the bridge array.
3511 static const int kEnumCacheBridgeCacheOffset = FixedArray::kHeaderSize;
3513 // Layout of descriptor.
3514 static const int kDescriptorKey = 0;
3515 static const int kDescriptorDetails = 1;
3516 static const int kDescriptorValue = 2;
3517 static const int kDescriptorSize = 3;
3520 // Print all the descriptors.
3521 void PrintDescriptors(FILE* out = stdout);
3525 // Is the descriptor array sorted and without duplicates?
3526 bool IsSortedNoDuplicates(int valid_descriptors = -1);
3528 // Is the descriptor array consistent with the back pointers in targets?
3529 bool IsConsistentWithBackPointers(Map* current_map);
3531 // Are two DescriptorArrays equal?
3532 bool IsEqualTo(DescriptorArray* other);
3535 // Returns the fixed array length required to hold number_of_descriptors
3537 static int LengthFor(int number_of_descriptors) {
3538 return ToKeyIndex(number_of_descriptors);
3542 // An entry in a DescriptorArray, represented as an (array, index) pair.
3545 inline explicit Entry(DescriptorArray* descs, int index) :
3546 descs_(descs), index_(index) { }
3548 inline PropertyType type() { return descs_->GetType(index_); }
3549 inline Object* GetCallbackObject() { return descs_->GetValue(index_); }
3552 DescriptorArray* descs_;
3556 // Conversion from descriptor number to array indices.
3557 static int ToKeyIndex(int descriptor_number) {
3558 return kFirstIndex +
3559 (descriptor_number * kDescriptorSize) +
3563 static int ToDetailsIndex(int descriptor_number) {
3564 return kFirstIndex +
3565 (descriptor_number * kDescriptorSize) +
3569 static int ToValueIndex(int descriptor_number) {
3570 return kFirstIndex +
3571 (descriptor_number * kDescriptorSize) +
3575 // Swap first and second descriptor.
3576 inline void SwapSortedKeys(int first, int second);
3578 DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
3582 enum SearchMode { ALL_ENTRIES, VALID_ENTRIES };
3584 template<SearchMode search_mode, typename T>
3585 inline int LinearSearch(T* array, Name* name, int len, int valid_entries);
3588 template<SearchMode search_mode, typename T>
3589 inline int Search(T* array, Name* name, int valid_entries = 0);
3592 // HashTable is a subclass of FixedArray that implements a hash table
3593 // that uses open addressing and quadratic probing.
3595 // In order for the quadratic probing to work, elements that have not
3596 // yet been used and elements that have been deleted are
3597 // distinguished. Probing continues when deleted elements are
3598 // encountered and stops when unused elements are encountered.
3600 // - Elements with key == undefined have not been used yet.
3601 // - Elements with key == the_hole have been deleted.
3603 // The hash table class is parameterized with a Shape and a Key.
3604 // Shape must be a class with the following interface:
3605 // class ExampleShape {
3607 // // Tells whether key matches other.
3608 // static bool IsMatch(Key key, Object* other);
3609 // // Returns the hash value for key.
3610 // static uint32_t Hash(Key key);
3611 // // Returns the hash value for object.
3612 // static uint32_t HashForObject(Key key, Object* object);
3613 // // Convert key to an object.
3614 // static inline Object* AsObject(Heap* heap, Key key);
3615 // // The prefix size indicates number of elements in the beginning
3616 // // of the backing storage.
3617 // static const int kPrefixSize = ..;
3618 // // The Element size indicates number of elements per entry.
3619 // static const int kEntrySize = ..;
3621 // The prefix size indicates an amount of memory in the
3622 // beginning of the backing storage that can be used for non-element
3623 // information by subclasses.
3625 template<typename Key>
3628 static const bool UsesSeed = false;
3629 static uint32_t Hash(Key key) { return 0; }
3630 static uint32_t SeededHash(Key key, uint32_t seed) {
3634 static uint32_t HashForObject(Key key, Object* object) { return 0; }
3635 static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
3637 return HashForObject(key, object);
3641 template<typename Shape, typename Key>
3642 class HashTable: public FixedArray {
3645 inline uint32_t Hash(Key key) {
3646 if (Shape::UsesSeed) {
3647 return Shape::SeededHash(key,
3648 GetHeap()->HashSeed());
3650 return Shape::Hash(key);
3654 inline uint32_t HashForObject(Key key, Object* object) {
3655 if (Shape::UsesSeed) {
3656 return Shape::SeededHashForObject(key,
3657 GetHeap()->HashSeed(), object);
3659 return Shape::HashForObject(key, object);
3663 // Returns the number of elements in the hash table.
3664 int NumberOfElements() {
3665 return Smi::cast(get(kNumberOfElementsIndex))->value();
3668 // Returns the number of deleted elements in the hash table.
3669 int NumberOfDeletedElements() {
3670 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3673 // Returns the capacity of the hash table.
3675 return Smi::cast(get(kCapacityIndex))->value();
3678 // ElementAdded should be called whenever an element is added to a
3680 void ElementAdded() { SetNumberOfElements(NumberOfElements() + 1); }
3682 // ElementRemoved should be called whenever an element is removed from
3684 void ElementRemoved() {
3685 SetNumberOfElements(NumberOfElements() - 1);
3686 SetNumberOfDeletedElements(NumberOfDeletedElements() + 1);
3688 void ElementsRemoved(int n) {
3689 SetNumberOfElements(NumberOfElements() - n);
3690 SetNumberOfDeletedElements(NumberOfDeletedElements() + n);
3693 // Returns a new HashTable object. Might return Failure.
3694 MUST_USE_RESULT static MaybeObject* Allocate(
3696 int at_least_space_for,
3697 MinimumCapacity capacity_option = USE_DEFAULT_MINIMUM_CAPACITY,
3698 PretenureFlag pretenure = NOT_TENURED);
3700 // Computes the required capacity for a table holding the given
3701 // number of elements. May be more than HashTable::kMaxCapacity.
3702 static int ComputeCapacity(int at_least_space_for);
3704 // Returns the key at entry.
3705 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3707 // Tells whether k is a real key. The hole and undefined are not allowed
3708 // as keys and can be used to indicate missing or deleted elements.
3709 bool IsKey(Object* k) {
3710 return !k->IsTheHole() && !k->IsUndefined();
3713 // Garbage collection support.
3714 void IteratePrefix(ObjectVisitor* visitor);
3715 void IterateElements(ObjectVisitor* visitor);
3718 static inline HashTable* cast(Object* obj);
3720 // Compute the probe offset (quadratic probing).
3721 INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
3722 return (n + n * n) >> 1;
3725 static const int kNumberOfElementsIndex = 0;
3726 static const int kNumberOfDeletedElementsIndex = 1;
3727 static const int kCapacityIndex = 2;
3728 static const int kPrefixStartIndex = 3;
3729 static const int kElementsStartIndex =
3730 kPrefixStartIndex + Shape::kPrefixSize;
3731 static const int kEntrySize = Shape::kEntrySize;
3732 static const int kElementsStartOffset =
3733 kHeaderSize + kElementsStartIndex * kPointerSize;
3734 static const int kCapacityOffset =
3735 kHeaderSize + kCapacityIndex * kPointerSize;
3737 // Constant used for denoting a absent entry.
3738 static const int kNotFound = -1;
3740 // Maximal capacity of HashTable. Based on maximal length of underlying
3741 // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
3743 static const int kMaxCapacity =
3744 (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
3746 // Find entry for key otherwise return kNotFound.
3747 inline int FindEntry(Key key);
3748 int FindEntry(Isolate* isolate, Key key);
3750 // Rehashes the table in-place.
3751 void Rehash(Key key);
3754 friend class ObjectHashSet;
3755 friend class ObjectHashTable;
3757 // Find the entry at which to insert element with the given key that
3758 // has the given hash value.
3759 uint32_t FindInsertionEntry(uint32_t hash);
3761 // Returns the index for an entry (of the key)
3762 static inline int EntryToIndex(int entry) {
3763 return (entry * kEntrySize) + kElementsStartIndex;
3766 // Update the number of elements in the hash table.
3767 void SetNumberOfElements(int nof) {
3768 set(kNumberOfElementsIndex, Smi::FromInt(nof));
3771 // Update the number of deleted elements in the hash table.
3772 void SetNumberOfDeletedElements(int nod) {
3773 set(kNumberOfDeletedElementsIndex, Smi::FromInt(nod));
3776 // Sets the capacity of the hash table.
3777 void SetCapacity(int capacity) {
3778 // To scale a computed hash code to fit within the hash table, we
3779 // use bit-wise AND with a mask, so the capacity must be positive
3781 ASSERT(capacity > 0);
3782 ASSERT(capacity <= kMaxCapacity);
3783 set(kCapacityIndex, Smi::FromInt(capacity));
3787 // Returns probe entry.
3788 static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
3789 ASSERT(IsPowerOf2(size));
3790 return (hash + GetProbeOffset(number)) & (size - 1);
3793 inline static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
3794 return hash & (size - 1);
3797 inline static uint32_t NextProbe(
3798 uint32_t last, uint32_t number, uint32_t size) {
3799 return (last + number) & (size - 1);
3802 // Returns _expected_ if one of entries given by the first _probe_ probes is
3803 // equal to _expected_. Otherwise, returns the entry given by the probe
3805 uint32_t EntryForProbe(Key key, Object* k, int probe, uint32_t expected);
3807 void Swap(uint32_t entry1, uint32_t entry2, WriteBarrierMode mode);
3809 // Rehashes this hash-table into the new table.
3810 MUST_USE_RESULT MaybeObject* Rehash(HashTable* new_table, Key key);
3812 // Attempt to shrink hash table after removal of key.
3813 MUST_USE_RESULT MaybeObject* Shrink(Key key);
3815 // Ensure enough space for n additional elements.
3816 MUST_USE_RESULT MaybeObject* EnsureCapacity(
3819 PretenureFlag pretenure = NOT_TENURED);
3823 // HashTableKey is an abstract superclass for virtual key behavior.
3824 class HashTableKey {
3826 // Returns whether the other object matches this key.
3827 virtual bool IsMatch(Object* other) = 0;
3828 // Returns the hash value for this key.
3829 virtual uint32_t Hash() = 0;
3830 // Returns the hash value for object.
3831 virtual uint32_t HashForObject(Object* key) = 0;
3832 // Returns the key object for storing into the hash table.
3833 // If allocations fails a failure object is returned.
3834 MUST_USE_RESULT virtual MaybeObject* AsObject(Heap* heap) = 0;
3836 virtual ~HashTableKey() {}
3840 class StringTableShape : public BaseShape<HashTableKey*> {
3842 static inline bool IsMatch(HashTableKey* key, Object* value) {
3843 return key->IsMatch(value);
3845 static inline uint32_t Hash(HashTableKey* key) {
3848 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3849 return key->HashForObject(object);
3851 MUST_USE_RESULT static inline MaybeObject* AsObject(Heap* heap,
3852 HashTableKey* key) {
3853 return key->AsObject(heap);
3856 static const int kPrefixSize = 0;
3857 static const int kEntrySize = 1;
3860 class SeqOneByteString;
3864 // No special elements in the prefix and the element size is 1
3865 // because only the string itself (the key) needs to be stored.
3866 class StringTable: public HashTable<StringTableShape, HashTableKey*> {
3868 // Find string in the string table. If it is not there yet, it is
3869 // added. The return value is the string table which might have
3870 // been enlarged. If the return value is not a failure, the string
3871 // pointer *s is set to the string found.
3872 MUST_USE_RESULT MaybeObject* LookupString(String* key, Object** s);
3873 MUST_USE_RESULT MaybeObject* LookupKey(HashTableKey* key, Object** s);
3875 // Looks up a string that is equal to the given string and returns
3876 // true if it is found, assigning the string to the given output
3878 bool LookupStringIfExists(String* str, String** result);
3879 bool LookupTwoCharsStringIfExists(uint16_t c1, uint16_t c2, String** result);
3882 static inline StringTable* cast(Object* obj);
3885 template <bool seq_ascii> friend class JsonParser;
3887 DISALLOW_IMPLICIT_CONSTRUCTORS(StringTable);
3891 class MapCacheShape : public BaseShape<HashTableKey*> {
3893 static inline bool IsMatch(HashTableKey* key, Object* value) {
3894 return key->IsMatch(value);
3896 static inline uint32_t Hash(HashTableKey* key) {
3900 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3901 return key->HashForObject(object);
3904 MUST_USE_RESULT static inline MaybeObject* AsObject(Heap* heap,
3905 HashTableKey* key) {
3906 return key->AsObject(heap);
3909 static const int kPrefixSize = 0;
3910 static const int kEntrySize = 2;
3916 // Maps keys that are a fixed array of unique names to a map.
3917 // Used for canonicalize maps for object literals.
3918 class MapCache: public HashTable<MapCacheShape, HashTableKey*> {
3920 // Find cached value for a name key, otherwise return null.
3921 Object* Lookup(FixedArray* key);
3922 MUST_USE_RESULT MaybeObject* Put(FixedArray* key, Map* value);
3923 static inline MapCache* cast(Object* obj);
3926 DISALLOW_IMPLICIT_CONSTRUCTORS(MapCache);
3930 template <typename Shape, typename Key>
3931 class Dictionary: public HashTable<Shape, Key> {
3933 static inline Dictionary<Shape, Key>* cast(Object* obj) {
3934 return reinterpret_cast<Dictionary<Shape, Key>*>(obj);
3937 // Returns the value at entry.
3938 Object* ValueAt(int entry) {
3939 return this->get(HashTable<Shape, Key>::EntryToIndex(entry) + 1);
3942 // Set the value for entry.
3943 void ValueAtPut(int entry, Object* value) {
3944 this->set(HashTable<Shape, Key>::EntryToIndex(entry) + 1, value);
3947 // Returns the property details for the property at entry.
3948 PropertyDetails DetailsAt(int entry) {
3949 ASSERT(entry >= 0); // Not found is -1, which is not caught by get().
3950 return PropertyDetails(
3951 Smi::cast(this->get(HashTable<Shape, Key>::EntryToIndex(entry) + 2)));
3954 // Set the details for entry.
3955 void DetailsAtPut(int entry, PropertyDetails value) {
3956 this->set(HashTable<Shape, Key>::EntryToIndex(entry) + 2, value.AsSmi());
3960 void CopyValuesTo(FixedArray* elements);
3962 // Delete a property from the dictionary.
3963 Object* DeleteProperty(int entry, JSObject::DeleteMode mode);
3965 // Attempt to shrink the dictionary after deletion of key.
3966 MUST_USE_RESULT MaybeObject* Shrink(Key key);
3968 // Returns the number of elements in the dictionary filtering out properties
3969 // with the specified attributes.
3970 int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3972 // Returns the number of enumerable elements in the dictionary.
3973 int NumberOfEnumElements();
3975 enum SortMode { UNSORTED, SORTED };
3976 // Copies keys to preallocated fixed array.
3977 void CopyKeysTo(FixedArray* storage,
3978 PropertyAttributes filter,
3979 SortMode sort_mode);
3980 // Fill in details for properties into storage.
3981 void CopyKeysTo(FixedArray* storage,
3983 PropertyAttributes filter,
3984 SortMode sort_mode);
3986 // Accessors for next enumeration index.
3987 void SetNextEnumerationIndex(int index) {
3989 this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
3992 int NextEnumerationIndex() {
3993 return Smi::cast(FixedArray::get(kNextEnumerationIndexIndex))->value();
3996 // Returns a new array for dictionary usage. Might return Failure.
3997 MUST_USE_RESULT static MaybeObject* Allocate(
3999 int at_least_space_for,
4000 PretenureFlag pretenure = NOT_TENURED);
4002 // Ensure enough space for n additional elements.
4003 MUST_USE_RESULT MaybeObject* EnsureCapacity(int n, Key key);
4006 void Print(FILE* out = stdout);
4008 // Returns the key (slow).
4009 Object* SlowReverseLookup(Object* value);
4011 // Sets the entry to (key, value) pair.
4012 inline void SetEntry(int entry,
4015 inline void SetEntry(int entry,
4018 PropertyDetails details);
4020 MUST_USE_RESULT MaybeObject* Add(Key key,
4022 PropertyDetails details);
4025 // Generic at put operation.
4026 MUST_USE_RESULT MaybeObject* AtPut(Key key, Object* value);
4028 // Add entry to dictionary.
4029 MUST_USE_RESULT MaybeObject* AddEntry(Key key,
4031 PropertyDetails details,
4034 // Generate new enumeration indices to avoid enumeration index overflow.
4035 MUST_USE_RESULT MaybeObject* GenerateNewEnumerationIndices();
4036 static const int kMaxNumberKeyIndex =
4037 HashTable<Shape, Key>::kPrefixStartIndex;
4038 static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
4042 class NameDictionaryShape : public BaseShape<Name*> {
4044 static inline bool IsMatch(Name* key, Object* other);
4045 static inline uint32_t Hash(Name* key);
4046 static inline uint32_t HashForObject(Name* key, Object* object);
4047 MUST_USE_RESULT static inline MaybeObject* AsObject(Heap* heap,
4049 static const int kPrefixSize = 2;
4050 static const int kEntrySize = 3;
4051 static const bool kIsEnumerable = true;
4055 class NameDictionary: public Dictionary<NameDictionaryShape, Name*> {
4057 static inline NameDictionary* cast(Object* obj) {
4058 ASSERT(obj->IsDictionary());
4059 return reinterpret_cast<NameDictionary*>(obj);
4062 // Copies enumerable keys to preallocated fixed array.
4063 FixedArray* CopyEnumKeysTo(FixedArray* storage);
4064 static void DoGenerateNewEnumerationIndices(
4065 Handle<NameDictionary> dictionary);
4067 // For transforming properties of a JSObject.
4068 MUST_USE_RESULT MaybeObject* TransformPropertiesToFastFor(
4070 int unused_property_fields);
4072 // Find entry for key, otherwise return kNotFound. Optimized version of
4073 // HashTable::FindEntry.
4074 int FindEntry(Name* key);
4078 class NumberDictionaryShape : public BaseShape<uint32_t> {
4080 static inline bool IsMatch(uint32_t key, Object* other);
4081 MUST_USE_RESULT static inline MaybeObject* AsObject(Heap* heap,
4083 static const int kEntrySize = 3;
4084 static const bool kIsEnumerable = false;
4088 class SeededNumberDictionaryShape : public NumberDictionaryShape {
4090 static const bool UsesSeed = true;
4091 static const int kPrefixSize = 2;
4093 static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
4094 static inline uint32_t SeededHashForObject(uint32_t key,
4100 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
4102 static const int kPrefixSize = 0;
4104 static inline uint32_t Hash(uint32_t key);
4105 static inline uint32_t HashForObject(uint32_t key, Object* object);
4109 class SeededNumberDictionary
4110 : public Dictionary<SeededNumberDictionaryShape, uint32_t> {
4112 static SeededNumberDictionary* cast(Object* obj) {
4113 ASSERT(obj->IsDictionary());
4114 return reinterpret_cast<SeededNumberDictionary*>(obj);
4117 // Type specific at put (default NONE attributes is used when adding).
4118 MUST_USE_RESULT MaybeObject* AtNumberPut(uint32_t key, Object* value);
4119 MUST_USE_RESULT static Handle<SeededNumberDictionary> AddNumberEntry(
4120 Handle<SeededNumberDictionary> dictionary,
4122 Handle<Object> value,
4123 PropertyDetails details);
4124 MUST_USE_RESULT MaybeObject* AddNumberEntry(uint32_t key,
4126 PropertyDetails details);
4128 // Set an existing entry or add a new one if needed.
4129 // Return the updated dictionary.
4130 MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
4131 Handle<SeededNumberDictionary> dictionary,
4133 Handle<Object> value,
4134 PropertyDetails details);
4136 MUST_USE_RESULT MaybeObject* Set(uint32_t key,
4138 PropertyDetails details);
4140 void UpdateMaxNumberKey(uint32_t key);
4142 // If slow elements are required we will never go back to fast-case
4143 // for the elements kept in this dictionary. We require slow
4144 // elements if an element has been added at an index larger than
4145 // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
4146 // when defining a getter or setter with a number key.
4147 inline bool requires_slow_elements();
4148 inline void set_requires_slow_elements();
4150 // Get the value of the max number key that has been added to this
4151 // dictionary. max_number_key can only be called if
4152 // requires_slow_elements returns false.
4153 inline uint32_t max_number_key();
4156 static const int kRequiresSlowElementsMask = 1;
4157 static const int kRequiresSlowElementsTagSize = 1;
4158 static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
4162 class UnseededNumberDictionary
4163 : public Dictionary<UnseededNumberDictionaryShape, uint32_t> {
4165 static UnseededNumberDictionary* cast(Object* obj) {
4166 ASSERT(obj->IsDictionary());
4167 return reinterpret_cast<UnseededNumberDictionary*>(obj);
4170 // Type specific at put (default NONE attributes is used when adding).
4171 MUST_USE_RESULT MaybeObject* AtNumberPut(uint32_t key, Object* value);
4172 MUST_USE_RESULT MaybeObject* AddNumberEntry(uint32_t key, Object* value);
4174 // Set an existing entry or add a new one if needed.
4175 // Return the updated dictionary.
4176 MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
4177 Handle<UnseededNumberDictionary> dictionary,
4179 Handle<Object> value);
4181 MUST_USE_RESULT MaybeObject* Set(uint32_t key, Object* value);
4185 template <int entrysize>
4186 class ObjectHashTableShape : public BaseShape<Object*> {
4188 static inline bool IsMatch(Object* key, Object* other);
4189 static inline uint32_t Hash(Object* key);
4190 static inline uint32_t HashForObject(Object* key, Object* object);
4191 MUST_USE_RESULT static inline MaybeObject* AsObject(Heap* heap,
4193 static const int kPrefixSize = 0;
4194 static const int kEntrySize = entrysize;
4198 // ObjectHashSet holds keys that are arbitrary objects by using the identity
4199 // hash of the key for hashing purposes.
4200 class ObjectHashSet: public HashTable<ObjectHashTableShape<1>, Object*> {
4202 static inline ObjectHashSet* cast(Object* obj) {
4203 ASSERT(obj->IsHashTable());
4204 return reinterpret_cast<ObjectHashSet*>(obj);
4207 // Looks up whether the given key is part of this hash set.
4208 bool Contains(Object* key);
4210 static Handle<ObjectHashSet> EnsureCapacity(
4211 Handle<ObjectHashSet> table,
4214 PretenureFlag pretenure = NOT_TENURED);
4216 // Attempt to shrink hash table after removal of key.
4217 static Handle<ObjectHashSet> Shrink(Handle<ObjectHashSet> table,
4218 Handle<Object> key);
4220 // Adds the given key to this hash set.
4221 static Handle<ObjectHashSet> Add(Handle<ObjectHashSet> table,
4222 Handle<Object> key);
4224 // Removes the given key from this hash set.
4225 static Handle<ObjectHashSet> Remove(Handle<ObjectHashSet> table,
4226 Handle<Object> key);
4230 // ObjectHashTable maps keys that are arbitrary objects to object values by
4231 // using the identity hash of the key for hashing purposes.
4232 class ObjectHashTable: public HashTable<ObjectHashTableShape<2>, Object*> {
4234 static inline ObjectHashTable* cast(Object* obj) {
4235 ASSERT(obj->IsHashTable());
4236 return reinterpret_cast<ObjectHashTable*>(obj);
4239 static Handle<ObjectHashTable> EnsureCapacity(
4240 Handle<ObjectHashTable> table,
4243 PretenureFlag pretenure = NOT_TENURED);
4245 // Attempt to shrink hash table after removal of key.
4246 static Handle<ObjectHashTable> Shrink(Handle<ObjectHashTable> table,
4247 Handle<Object> key);
4249 // Looks up the value associated with the given key. The hole value is
4250 // returned in case the key is not present.
4251 Object* Lookup(Object* key);
4253 // Adds (or overwrites) the value associated with the given key. Mapping a
4254 // key to the hole value causes removal of the whole entry.
4255 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
4257 Handle<Object> value);
4260 friend class MarkCompactCollector;
4262 void AddEntry(int entry, Object* key, Object* value);
4263 void RemoveEntry(int entry);
4265 // Returns the index to the value of an entry.
4266 static inline int EntryToValueIndex(int entry) {
4267 return EntryToIndex(entry) + 1;
4272 template <int entrysize>
4273 class WeakHashTableShape : public BaseShape<Object*> {
4275 static inline bool IsMatch(Object* key, Object* other);
4276 static inline uint32_t Hash(Object* key);
4277 static inline uint32_t HashForObject(Object* key, Object* object);
4278 MUST_USE_RESULT static inline MaybeObject* AsObject(Heap* heap,
4280 static const int kPrefixSize = 0;
4281 static const int kEntrySize = entrysize;
4285 // WeakHashTable maps keys that are arbitrary objects to object values.
4286 // It is used for the global weak hash table that maps objects
4287 // embedded in optimized code to dependent code lists.
4288 class WeakHashTable: public HashTable<WeakHashTableShape<2>, Object*> {
4290 static inline WeakHashTable* cast(Object* obj) {
4291 ASSERT(obj->IsHashTable());
4292 return reinterpret_cast<WeakHashTable*>(obj);
4295 // Looks up the value associated with the given key. The hole value is
4296 // returned in case the key is not present.
4297 Object* Lookup(Object* key);
4299 // Adds (or overwrites) the value associated with the given key. Mapping a
4300 // key to the hole value causes removal of the whole entry.
4301 MUST_USE_RESULT MaybeObject* Put(Object* key, Object* value);
4303 // This function is called when heap verification is turned on.
4304 void Zap(Object* value) {
4305 int capacity = Capacity();
4306 for (int i = 0; i < capacity; i++) {
4307 set(EntryToIndex(i), value);
4308 set(EntryToValueIndex(i), value);
4313 friend class MarkCompactCollector;
4315 void AddEntry(int entry, Object* key, Object* value);
4317 // Returns the index to the value of an entry.
4318 static inline int EntryToValueIndex(int entry) {
4319 return EntryToIndex(entry) + 1;
4324 // JSFunctionResultCache caches results of some JSFunction invocation.
4325 // It is a fixed array with fixed structure:
4326 // [0]: factory function
4327 // [1]: finger index
4328 // [2]: current cache size
4329 // [3]: dummy field.
4330 // The rest of array are key/value pairs.
4331 class JSFunctionResultCache: public FixedArray {
4333 static const int kFactoryIndex = 0;
4334 static const int kFingerIndex = kFactoryIndex + 1;
4335 static const int kCacheSizeIndex = kFingerIndex + 1;
4336 static const int kDummyIndex = kCacheSizeIndex + 1;
4337 static const int kEntriesIndex = kDummyIndex + 1;
4339 static const int kEntrySize = 2; // key + value
4341 static const int kFactoryOffset = kHeaderSize;
4342 static const int kFingerOffset = kFactoryOffset + kPointerSize;
4343 static const int kCacheSizeOffset = kFingerOffset + kPointerSize;
4345 inline void MakeZeroSize();
4346 inline void Clear();
4349 inline void set_size(int size);
4350 inline int finger_index();
4351 inline void set_finger_index(int finger_index);
4354 static inline JSFunctionResultCache* cast(Object* obj);
4356 DECLARE_VERIFIER(JSFunctionResultCache)
4360 // ScopeInfo represents information about different scopes of a source
4361 // program and the allocation of the scope's variables. Scope information
4362 // is stored in a compressed form in ScopeInfo objects and is used
4363 // at runtime (stack dumps, deoptimization, etc.).
4365 // This object provides quick access to scope info details for runtime
4367 class ScopeInfo : public FixedArray {
4369 static inline ScopeInfo* cast(Object* object);
4371 // Return the type of this scope.
4372 ScopeType scope_type();
4374 // Does this scope call eval?
4377 // Return the language mode of this scope.
4378 LanguageMode language_mode();
4380 // Does this scope make a non-strict eval call?
4381 bool CallsNonStrictEval() {
4382 return CallsEval() && (language_mode() == CLASSIC_MODE);
4385 // Return the total number of locals allocated on the stack and in the
4386 // context. This includes the parameters that are allocated in the context.
4389 // Return the number of stack slots for code. This number consists of two
4391 // 1. One stack slot per stack allocated local.
4392 // 2. One stack slot for the function name if it is stack allocated.
4393 int StackSlotCount();
4395 // Return the number of context slots for code if a context is allocated. This
4396 // number consists of three parts:
4397 // 1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
4398 // 2. One context slot per context allocated local.
4399 // 3. One context slot for the function name if it is context allocated.
4400 // Parameters allocated in the context count as context allocated locals. If
4401 // no contexts are allocated for this scope ContextLength returns 0.
4402 int ContextLength();
4404 // Is this scope the scope of a named function expression?
4405 bool HasFunctionName();
4407 // Return if this has context allocated locals.
4408 bool HasHeapAllocatedLocals();
4410 // Return if contexts are allocated for this scope.
4413 // Return the function_name if present.
4414 String* FunctionName();
4416 // Return the name of the given parameter.
4417 String* ParameterName(int var);
4419 // Return the name of the given local.
4420 String* LocalName(int var);
4422 // Return the name of the given stack local.
4423 String* StackLocalName(int var);
4425 // Return the name of the given context local.
4426 String* ContextLocalName(int var);
4428 // Return the mode of the given context local.
4429 VariableMode ContextLocalMode(int var);
4431 // Return the initialization flag of the given context local.
4432 InitializationFlag ContextLocalInitFlag(int var);
4434 // Lookup support for serialized scope info. Returns the
4435 // the stack slot index for a given slot name if the slot is
4436 // present; otherwise returns a value < 0. The name must be an internalized
4438 int StackSlotIndex(String* name);
4440 // Lookup support for serialized scope info. Returns the
4441 // context slot index for a given slot name if the slot is present; otherwise
4442 // returns a value < 0. The name must be an internalized string.
4443 // If the slot is present and mode != NULL, sets *mode to the corresponding
4444 // mode for that variable.
4445 int ContextSlotIndex(String* name,
4447 InitializationFlag* init_flag);
4449 // Lookup support for serialized scope info. Returns the
4450 // parameter index for a given parameter name if the parameter is present;
4451 // otherwise returns a value < 0. The name must be an internalized string.
4452 int ParameterIndex(String* name);
4454 // Lookup support for serialized scope info. Returns the function context
4455 // slot index if the function name is present and context-allocated (named
4456 // function expressions, only), otherwise returns a value < 0. The name
4457 // must be an internalized string.
4458 int FunctionContextSlotIndex(String* name, VariableMode* mode);
4461 // Copies all the context locals into an object used to materialize a scope.
4462 static bool CopyContextLocalsToScopeObject(Handle<ScopeInfo> scope_info,
4463 Handle<Context> context,
4464 Handle<JSObject> scope_object);
4467 static Handle<ScopeInfo> Create(Scope* scope, Zone* zone);
4469 // Serializes empty scope info.
4470 static ScopeInfo* Empty(Isolate* isolate);
4476 // The layout of the static part of a ScopeInfo is as follows. Each entry is
4477 // numeric and occupies one array slot.
4478 // 1. A set of properties of the scope
4479 // 2. The number of parameters. This only applies to function scopes. For
4480 // non-function scopes this is 0.
4481 // 3. The number of non-parameter variables allocated on the stack.
4482 // 4. The number of non-parameter and parameter variables allocated in the
4484 #define FOR_EACH_NUMERIC_FIELD(V) \
4487 V(StackLocalCount) \
4488 V(ContextLocalCount)
4490 #define FIELD_ACCESSORS(name) \
4491 void Set##name(int value) { \
4492 set(k##name, Smi::FromInt(value)); \
4495 if (length() > 0) { \
4496 return Smi::cast(get(k##name))->value(); \
4501 FOR_EACH_NUMERIC_FIELD(FIELD_ACCESSORS)
4502 #undef FIELD_ACCESSORS
4506 #define DECL_INDEX(name) k##name,
4507 FOR_EACH_NUMERIC_FIELD(DECL_INDEX)
4509 #undef FOR_EACH_NUMERIC_FIELD
4513 // The layout of the variable part of a ScopeInfo is as follows:
4514 // 1. ParameterEntries:
4515 // This part stores the names of the parameters for function scopes. One
4516 // slot is used per parameter, so in total this part occupies
4517 // ParameterCount() slots in the array. For other scopes than function
4518 // scopes ParameterCount() is 0.
4519 // 2. StackLocalEntries:
4520 // Contains the names of local variables that are allocated on the stack,
4521 // in increasing order of the stack slot index. One slot is used per stack
4522 // local, so in total this part occupies StackLocalCount() slots in the
4524 // 3. ContextLocalNameEntries:
4525 // Contains the names of local variables and parameters that are allocated
4526 // in the context. They are stored in increasing order of the context slot
4527 // index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
4528 // context local, so in total this part occupies ContextLocalCount() slots
4530 // 4. ContextLocalInfoEntries:
4531 // Contains the variable modes and initialization flags corresponding to
4532 // the context locals in ContextLocalNameEntries. One slot is used per
4533 // context local, so in total this part occupies ContextLocalCount()
4534 // slots in the array.
4535 // 5. FunctionNameEntryIndex:
4536 // If the scope belongs to a named function expression this part contains
4537 // information about the function variable. It always occupies two array
4538 // slots: a. The name of the function variable.
4539 // b. The context or stack slot index for the variable.
4540 int ParameterEntriesIndex();
4541 int StackLocalEntriesIndex();
4542 int ContextLocalNameEntriesIndex();
4543 int ContextLocalInfoEntriesIndex();
4544 int FunctionNameEntryIndex();
4546 // Location of the function variable for named function expressions.
4547 enum FunctionVariableInfo {
4548 NONE, // No function name present.
4554 // Properties of scopes.
4555 class ScopeTypeField: public BitField<ScopeType, 0, 3> {};
4556 class CallsEvalField: public BitField<bool, 3, 1> {};
4557 class LanguageModeField: public BitField<LanguageMode, 4, 2> {};
4558 class FunctionVariableField: public BitField<FunctionVariableInfo, 6, 2> {};
4559 class FunctionVariableMode: public BitField<VariableMode, 8, 3> {};
4561 // BitFields representing the encoded information for context locals in the
4562 // ContextLocalInfoEntries part.
4563 class ContextLocalMode: public BitField<VariableMode, 0, 3> {};
4564 class ContextLocalInitFlag: public BitField<InitializationFlag, 3, 1> {};
4568 // The cache for maps used by normalized (dictionary mode) objects.
4569 // Such maps do not have property descriptors, so a typical program
4570 // needs very limited number of distinct normalized maps.
4571 class NormalizedMapCache: public FixedArray {
4573 static const int kEntries = 64;
4575 static Handle<Map> Get(Handle<NormalizedMapCache> cache,
4576 Handle<JSObject> object,
4577 PropertyNormalizationMode mode);
4582 static inline NormalizedMapCache* cast(Object* obj);
4584 DECLARE_VERIFIER(NormalizedMapCache)
4588 // ByteArray represents fixed sized byte arrays. Used for the relocation info
4589 // that is attached to code objects.
4590 class ByteArray: public FixedArrayBase {
4592 inline int Size() { return RoundUp(length() + kHeaderSize, kPointerSize); }
4594 // Setter and getter.
4595 inline byte get(int index);
4596 inline void set(int index, byte value);
4598 // Treat contents as an int array.
4599 inline int get_int(int index);
4601 static int SizeFor(int length) {
4602 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4604 // We use byte arrays for free blocks in the heap. Given a desired size in
4605 // bytes that is a multiple of the word size and big enough to hold a byte
4606 // array, this function returns the number of elements a byte array should
4608 static int LengthFor(int size_in_bytes) {
4609 ASSERT(IsAligned(size_in_bytes, kPointerSize));
4610 ASSERT(size_in_bytes >= kHeaderSize);
4611 return size_in_bytes - kHeaderSize;
4614 // Returns data start address.
4615 inline Address GetDataStartAddress();
4617 // Returns a pointer to the ByteArray object for a given data start address.
4618 static inline ByteArray* FromDataStartAddress(Address address);
4621 static inline ByteArray* cast(Object* obj);
4623 // Dispatched behavior.
4624 inline int ByteArraySize() {
4625 return SizeFor(this->length());
4627 DECLARE_PRINTER(ByteArray)
4628 DECLARE_VERIFIER(ByteArray)
4630 // Layout description.
4631 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4633 // Maximal memory consumption for a single ByteArray.
4634 static const int kMaxSize = 512 * MB;
4635 // Maximal length of a single ByteArray.
4636 static const int kMaxLength = kMaxSize - kHeaderSize;
4639 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4643 // FreeSpace represents fixed sized areas of the heap that are not currently in
4644 // use. Used by the heap and GC.
4645 class FreeSpace: public HeapObject {
4647 // [size]: size of the free space including the header.
4649 inline void set_size(int value);
4651 inline int Size() { return size(); }
4654 static inline FreeSpace* cast(Object* obj);
4656 // Dispatched behavior.
4657 DECLARE_PRINTER(FreeSpace)
4658 DECLARE_VERIFIER(FreeSpace)
4660 // Layout description.
4661 // Size is smi tagged when it is stored.
4662 static const int kSizeOffset = HeapObject::kHeaderSize;
4663 static const int kHeaderSize = kSizeOffset + kPointerSize;
4665 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4668 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
4672 // V has parameters (Type, type, TYPE, C type, element_size)
4673 #define TYPED_ARRAYS(V) \
4674 V(Uint8, uint8, UINT8, uint8_t, 1) \
4675 V(Int8, int8, INT8, int8_t, 1) \
4676 V(Uint16, uint16, UINT16, uint16_t, 2) \
4677 V(Int16, int16, INT16, int16_t, 2) \
4678 V(Uint32, uint32, UINT32, uint32_t, 4) \
4679 V(Int32, int32, INT32, int32_t, 4) \
4680 V(Float32, float32, FLOAT32, float, 4) \
4681 V(Float64, float64, FLOAT64, double, 8) \
4682 V(Float32x4, float32x4, FLOAT32x4, v8::internal::float32x4_value_t, 16) \
4683 V(Int32x4, int32x4, INT32x4, v8::internal::int32x4_value_t, 16) \
4684 V(Uint8Clamped, uint8_clamped, UINT8_CLAMPED, uint8_t, 1)
4688 // An ExternalArray represents a fixed-size array of primitive values
4689 // which live outside the JavaScript heap. Its subclasses are used to
4690 // implement the CanvasArray types being defined in the WebGL
4691 // specification. As of this writing the first public draft is not yet
4692 // available, but Khronos members can access the draft at:
4693 // https://cvs.khronos.org/svn/repos/3dweb/trunk/doc/spec/WebGL-spec.html
4695 // The semantics of these arrays differ from CanvasPixelArray.
4696 // Out-of-range values passed to the setter are converted via a C
4697 // cast, not clamping. Out-of-range indices cause exceptions to be
4698 // raised rather than being silently ignored.
4699 class ExternalArray: public FixedArrayBase {
4701 inline bool is_the_hole(int index) { return false; }
4703 // [external_pointer]: The pointer to the external memory area backing this
4705 DECL_ACCESSORS(external_pointer, void) // Pointer to the data store.
4708 static inline ExternalArray* cast(Object* obj);
4710 // Maximal acceptable length for an external array.
4711 static const int kMaxLength = 0x3fffffff;
4713 // ExternalArray headers are not quadword aligned.
4714 static const int kExternalPointerOffset =
4715 POINTER_SIZE_ALIGN(FixedArrayBase::kLengthOffset + kPointerSize);
4716 static const int kHeaderSize = kExternalPointerOffset + kPointerSize;
4717 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4720 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalArray);
4724 // A ExternalUint8ClampedArray represents a fixed-size byte array with special
4725 // semantics used for implementing the CanvasPixelArray object. Please see the
4726 // specification at:
4728 // http://www.whatwg.org/specs/web-apps/current-work/
4729 // multipage/the-canvas-element.html#canvaspixelarray
4730 // In particular, write access clamps the value written to 0 or 255 if the
4731 // value written is outside this range.
4732 class ExternalUint8ClampedArray: public ExternalArray {
4734 inline uint8_t* external_uint8_clamped_pointer();
4736 // Setter and getter.
4737 inline uint8_t get_scalar(int index);
4738 MUST_USE_RESULT inline MaybeObject* get(int index);
4739 inline void set(int index, uint8_t value);
4741 // This accessor applies the correct conversion from Smi, HeapNumber and
4742 // undefined and clamps the converted value between 0 and 255.
4743 Object* SetValue(uint32_t index, Object* value);
4745 static Handle<Object> SetValue(Handle<ExternalUint8ClampedArray> array,
4747 Handle<Object> value);
4750 static inline ExternalUint8ClampedArray* cast(Object* obj);
4752 // Dispatched behavior.
4753 DECLARE_PRINTER(ExternalUint8ClampedArray)
4754 DECLARE_VERIFIER(ExternalUint8ClampedArray)
4757 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint8ClampedArray);
4761 class ExternalInt8Array: public ExternalArray {
4763 // Setter and getter.
4764 inline int8_t get_scalar(int index);
4765 MUST_USE_RESULT inline MaybeObject* get(int index);
4766 inline void set(int index, int8_t value);
4768 static Handle<Object> SetValue(Handle<ExternalInt8Array> array,
4770 Handle<Object> value);
4772 // This accessor applies the correct conversion from Smi, HeapNumber
4774 MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
4777 static inline ExternalInt8Array* cast(Object* obj);
4779 // Dispatched behavior.
4780 DECLARE_PRINTER(ExternalInt8Array)
4781 DECLARE_VERIFIER(ExternalInt8Array)
4784 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt8Array);
4788 class ExternalUint8Array: public ExternalArray {
4790 // Setter and getter.
4791 inline uint8_t get_scalar(int index);
4792 MUST_USE_RESULT inline MaybeObject* get(int index);
4793 inline void set(int index, uint8_t value);
4795 static Handle<Object> SetValue(Handle<ExternalUint8Array> array,
4797 Handle<Object> value);
4799 // This accessor applies the correct conversion from Smi, HeapNumber
4801 MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
4804 static inline ExternalUint8Array* cast(Object* obj);
4806 // Dispatched behavior.
4807 DECLARE_PRINTER(ExternalUint8Array)
4808 DECLARE_VERIFIER(ExternalUint8Array)
4811 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint8Array);
4815 class ExternalInt16Array: public ExternalArray {
4817 // Setter and getter.
4818 inline int16_t get_scalar(int index);
4819 MUST_USE_RESULT inline MaybeObject* get(int index);
4820 inline void set(int index, int16_t value);
4822 static Handle<Object> SetValue(Handle<ExternalInt16Array> array,
4824 Handle<Object> value);
4826 // This accessor applies the correct conversion from Smi, HeapNumber
4828 MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
4831 static inline ExternalInt16Array* cast(Object* obj);
4833 // Dispatched behavior.
4834 DECLARE_PRINTER(ExternalInt16Array)
4835 DECLARE_VERIFIER(ExternalInt16Array)
4838 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt16Array);
4842 class ExternalUint16Array: public ExternalArray {
4844 // Setter and getter.
4845 inline uint16_t get_scalar(int index);
4846 MUST_USE_RESULT inline MaybeObject* get(int index);
4847 inline void set(int index, uint16_t value);
4849 static Handle<Object> SetValue(Handle<ExternalUint16Array> array,
4851 Handle<Object> value);
4853 // This accessor applies the correct conversion from Smi, HeapNumber
4855 MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
4858 static inline ExternalUint16Array* cast(Object* obj);
4860 // Dispatched behavior.
4861 DECLARE_PRINTER(ExternalUint16Array)
4862 DECLARE_VERIFIER(ExternalUint16Array)
4865 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint16Array);
4869 class ExternalInt32Array: public ExternalArray {
4871 // Setter and getter.
4872 inline int32_t get_scalar(int index);
4873 MUST_USE_RESULT inline MaybeObject* get(int index);
4874 inline void set(int index, int32_t value);
4876 static Handle<Object> SetValue(Handle<ExternalInt32Array> array,
4878 Handle<Object> value);
4880 // This accessor applies the correct conversion from Smi, HeapNumber
4882 MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
4885 static inline ExternalInt32Array* cast(Object* obj);
4887 // Dispatched behavior.
4888 DECLARE_PRINTER(ExternalInt32Array)
4889 DECLARE_VERIFIER(ExternalInt32Array)
4892 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt32Array);
4896 class ExternalUint32Array: public ExternalArray {
4898 // Setter and getter.
4899 inline uint32_t get_scalar(int index);
4900 MUST_USE_RESULT inline MaybeObject* get(int index);
4901 inline void set(int index, uint32_t value);
4903 static Handle<Object> SetValue(Handle<ExternalUint32Array> array,
4905 Handle<Object> value);
4907 // This accessor applies the correct conversion from Smi, HeapNumber
4909 MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
4912 static inline ExternalUint32Array* cast(Object* obj);
4914 // Dispatched behavior.
4915 DECLARE_PRINTER(ExternalUint32Array)
4916 DECLARE_VERIFIER(ExternalUint32Array)
4919 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint32Array);
4923 class ExternalFloat32Array: public ExternalArray {
4925 // Setter and getter.
4926 inline float get_scalar(int index);
4927 MUST_USE_RESULT inline MaybeObject* get(int index);
4928 inline void set(int index, float value);
4930 static Handle<Object> SetValue(Handle<ExternalFloat32Array> array,
4932 Handle<Object> value);
4934 // This accessor applies the correct conversion from Smi, HeapNumber
4936 MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
4939 static inline ExternalFloat32Array* cast(Object* obj);
4941 // Dispatched behavior.
4942 DECLARE_PRINTER(ExternalFloat32Array)
4943 DECLARE_VERIFIER(ExternalFloat32Array)
4946 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalFloat32Array);
4950 class ExternalFloat32x4Array: public ExternalArray {
4952 // Setter and getter.
4953 inline float32x4_value_t get_scalar(int index);
4954 MUST_USE_RESULT inline MaybeObject* get(int index);
4955 inline void set(int index, const float32x4_value_t& value);
4957 static Handle<Object> SetValue(Handle<ExternalFloat32x4Array> array,
4959 Handle<Object> value);
4961 // This accessor applies the correct conversion from Smi, HeapNumber
4963 MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
4966 static inline ExternalFloat32x4Array* cast(Object* obj);
4968 // Dispatched behavior.
4969 DECLARE_PRINTER(ExternalFloat32x4Array)
4970 DECLARE_VERIFIER(ExternalFloat32x4Array)
4973 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalFloat32x4Array);
4977 class ExternalInt32x4Array: public ExternalArray {
4979 // Setter and getter.
4980 inline int32x4_value_t get_scalar(int index);
4981 MUST_USE_RESULT inline MaybeObject* get(int index);
4982 inline void set(int index, const int32x4_value_t& value);
4984 static Handle<Object> SetValue(Handle<ExternalInt32x4Array> array,
4986 Handle<Object> value);
4987 // This accessor applies the correct conversion from Smi, HeapNumber
4989 MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
4992 static inline ExternalInt32x4Array* cast(Object* obj);
4994 // Dispatched behavior.
4995 DECLARE_PRINTER(ExternalInt32x4Array)
4996 DECLARE_VERIFIER(ExternalInt32x4Array)
4999 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt32x4Array);
5003 class ExternalFloat64Array: public ExternalArray {
5005 // Setter and getter.
5006 inline double get_scalar(int index);
5007 MUST_USE_RESULT inline MaybeObject* get(int index);
5008 inline void set(int index, double value);
5010 static Handle<Object> SetValue(Handle<ExternalFloat64Array> array,
5012 Handle<Object> value);
5014 // This accessor applies the correct conversion from Smi, HeapNumber
5016 MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
5019 static inline ExternalFloat64Array* cast(Object* obj);
5021 // Dispatched behavior.
5022 DECLARE_PRINTER(ExternalFloat64Array)
5023 DECLARE_VERIFIER(ExternalFloat64Array)
5026 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalFloat64Array);
5030 class FixedTypedArrayBase: public FixedArrayBase {
5033 static inline FixedTypedArrayBase* cast(Object* obj);
5035 static const int kDataOffset = kHeaderSize;
5040 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
5044 template <class Traits>
5045 class FixedTypedArray: public FixedTypedArrayBase {
5047 typedef typename Traits::ElementType ElementType;
5048 static const InstanceType kInstanceType = Traits::kInstanceType;
5051 static inline FixedTypedArray<Traits>* cast(Object* obj);
5053 static inline int ElementOffset(int index) {
5054 return kDataOffset + index * sizeof(ElementType);
5057 static inline int SizeFor(int length) {
5058 return ElementOffset(length);
5061 inline ElementType get_scalar(int index);
5062 MUST_USE_RESULT inline MaybeObject* get(int index);
5063 inline void set(int index, ElementType value);
5065 // This accessor applies the correct conversion from Smi, HeapNumber
5067 MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
5069 static Handle<Object> SetValue(Handle<FixedTypedArray<Traits> > array,
5071 Handle<Object> value);
5073 DECLARE_PRINTER(FixedTypedArray)
5074 DECLARE_VERIFIER(FixedTypedArray)
5077 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
5080 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size) \
5081 class Type##ArrayTraits { \
5083 typedef elementType ElementType; \
5084 static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE; \
5085 static const char* Designator() { return #type " array"; } \
5086 static inline MaybeObject* ToObject(Heap* heap, elementType scalar); \
5087 static elementType defaultValue() { return elementType(); } \
5090 typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
5092 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
5094 #undef FIXED_TYPED_ARRAY_TRAITS
5096 // DeoptimizationInputData is a fixed array used to hold the deoptimization
5097 // data for code generated by the Hydrogen/Lithium compiler. It also
5098 // contains information about functions that were inlined. If N different
5099 // functions were inlined then first N elements of the literal array will
5100 // contain these functions.
5103 class DeoptimizationInputData: public FixedArray {
5105 // Layout description. Indices in the array.
5106 static const int kTranslationByteArrayIndex = 0;
5107 static const int kInlinedFunctionCountIndex = 1;
5108 static const int kLiteralArrayIndex = 2;
5109 static const int kOsrAstIdIndex = 3;
5110 static const int kOsrPcOffsetIndex = 4;
5111 static const int kFirstDeoptEntryIndex = 5;
5113 // Offsets of deopt entry elements relative to the start of the entry.
5114 static const int kAstIdRawOffset = 0;
5115 static const int kTranslationIndexOffset = 1;
5116 static const int kArgumentsStackHeightOffset = 2;
5117 static const int kPcOffset = 3;
5118 static const int kDeoptEntrySize = 4;
5120 // Simple element accessors.
5121 #define DEFINE_ELEMENT_ACCESSORS(name, type) \
5123 return type::cast(get(k##name##Index)); \
5125 void Set##name(type* value) { \
5126 set(k##name##Index, value); \
5129 DEFINE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
5130 DEFINE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
5131 DEFINE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
5132 DEFINE_ELEMENT_ACCESSORS(OsrAstId, Smi)
5133 DEFINE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
5135 #undef DEFINE_ELEMENT_ACCESSORS
5137 // Accessors for elements of the ith deoptimization entry.
5138 #define DEFINE_ENTRY_ACCESSORS(name, type) \
5139 type* name(int i) { \
5140 return type::cast(get(IndexForEntry(i) + k##name##Offset)); \
5142 void Set##name(int i, type* value) { \
5143 set(IndexForEntry(i) + k##name##Offset, value); \
5146 DEFINE_ENTRY_ACCESSORS(AstIdRaw, Smi)
5147 DEFINE_ENTRY_ACCESSORS(TranslationIndex, Smi)
5148 DEFINE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
5149 DEFINE_ENTRY_ACCESSORS(Pc, Smi)
5151 #undef DEFINE_ENTRY_ACCESSORS
5153 BailoutId AstId(int i) {
5154 return BailoutId(AstIdRaw(i)->value());
5157 void SetAstId(int i, BailoutId value) {
5158 SetAstIdRaw(i, Smi::FromInt(value.ToInt()));
5162 return (length() - kFirstDeoptEntryIndex) / kDeoptEntrySize;
5165 // Allocates a DeoptimizationInputData.
5166 MUST_USE_RESULT static MaybeObject* Allocate(Isolate* isolate,
5167 int deopt_entry_count,
5168 PretenureFlag pretenure);
5171 static inline DeoptimizationInputData* cast(Object* obj);
5173 #ifdef ENABLE_DISASSEMBLER
5174 void DeoptimizationInputDataPrint(FILE* out);
5178 static int IndexForEntry(int i) {
5179 return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
5182 static int LengthFor(int entry_count) {
5183 return IndexForEntry(entry_count);
5188 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
5189 // data for code generated by the full compiler.
5190 // The format of the these objects is
5191 // [i * 2]: Ast ID for ith deoptimization.
5192 // [i * 2 + 1]: PC and state of ith deoptimization
5193 class DeoptimizationOutputData: public FixedArray {
5195 int DeoptPoints() { return length() / 2; }
5197 BailoutId AstId(int index) {
5198 return BailoutId(Smi::cast(get(index * 2))->value());
5201 void SetAstId(int index, BailoutId id) {
5202 set(index * 2, Smi::FromInt(id.ToInt()));
5205 Smi* PcAndState(int index) { return Smi::cast(get(1 + index * 2)); }
5206 void SetPcAndState(int index, Smi* offset) { set(1 + index * 2, offset); }
5208 static int LengthOfFixedArray(int deopt_points) {
5209 return deopt_points * 2;
5212 // Allocates a DeoptimizationOutputData.
5213 MUST_USE_RESULT static MaybeObject* Allocate(Isolate* isolate,
5214 int number_of_deopt_points,
5215 PretenureFlag pretenure);
5218 static inline DeoptimizationOutputData* cast(Object* obj);
5220 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
5221 void DeoptimizationOutputDataPrint(FILE* out);
5226 // Forward declaration.
5230 // TypeFeedbackCells is a fixed array used to hold the association between
5231 // cache cells and AST ids for code generated by the full compiler.
5232 // The format of the these objects is
5233 // [i * 2]: Global property cell of ith cache cell.
5234 // [i * 2 + 1]: Ast ID for ith cache cell.
5235 class TypeFeedbackCells: public FixedArray {
5237 int CellCount() { return length() / 2; }
5238 static int LengthOfFixedArray(int cell_count) { return cell_count * 2; }
5240 // Accessors for AST ids associated with cache values.
5241 inline TypeFeedbackId AstId(int index);
5242 inline void SetAstId(int index, TypeFeedbackId id);
5244 // Accessors for global property cells holding the cache values.
5245 inline Cell* GetCell(int index);
5246 inline void SetCell(int index, Cell* cell);
5248 // The object that indicates an uninitialized cache.
5249 static inline Handle<Object> UninitializedSentinel(Isolate* isolate);
5251 // The object that indicates a megamorphic state.
5252 static inline Handle<Object> MegamorphicSentinel(Isolate* isolate);
5254 // The object that indicates a monomorphic state of Array with
5256 static inline Handle<Object> MonomorphicArraySentinel(Isolate* isolate,
5257 ElementsKind elements_kind);
5259 // A raw version of the uninitialized sentinel that's safe to read during
5260 // garbage collection (e.g., for patching the cache).
5261 static inline Object* RawUninitializedSentinel(Heap* heap);
5264 static inline TypeFeedbackCells* cast(Object* obj);
5266 static const int kForInFastCaseMarker = 0;
5267 static const int kForInSlowCaseMarker = 1;
5271 // Forward declaration.
5272 class SafepointEntry;
5273 class TypeFeedbackInfo;
5275 // Code describes objects with on-the-fly generated machine code.
5276 class Code: public HeapObject {
5278 // Opaque data type for encapsulating code flags like kind, inline
5279 // cache state, and arguments count.
5280 typedef uint32_t Flags;
5282 #define NON_IC_KIND_LIST(V) \
5284 V(OPTIMIZED_FUNCTION) \
5290 #define IC_KIND_LIST(V) \
5300 #define CODE_KIND_LIST(V) \
5301 NON_IC_KIND_LIST(V) \
5305 #define DEFINE_CODE_KIND_ENUM(name) name,
5306 CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
5307 #undef DEFINE_CODE_KIND_ENUM
5311 // No more than 16 kinds. The value is currently encoded in four bits in
5313 STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
5315 static const char* Kind2String(Kind kind);
5323 static const int kPrologueOffsetNotSet = -1;
5325 #ifdef ENABLE_DISASSEMBLER
5327 static const char* ICState2String(InlineCacheState state);
5328 static const char* StubType2String(StubType type);
5329 static void PrintExtraICState(FILE* out, Kind kind, ExtraICState extra);
5330 void Disassemble(const char* name, FILE* out = stdout);
5331 #endif // ENABLE_DISASSEMBLER
5333 // [instruction_size]: Size of the native instructions
5334 inline int instruction_size();
5335 inline void set_instruction_size(int value);
5337 // [relocation_info]: Code relocation information
5338 DECL_ACCESSORS(relocation_info, ByteArray)
5339 void InvalidateRelocation();
5340 void InvalidateEmbeddedObjects();
5342 // [handler_table]: Fixed array containing offsets of exception handlers.
5343 DECL_ACCESSORS(handler_table, FixedArray)
5345 // [deoptimization_data]: Array containing data for deopt.
5346 DECL_ACCESSORS(deoptimization_data, FixedArray)
5348 // [raw_type_feedback_info]: This field stores various things, depending on
5349 // the kind of the code object.
5350 // FUNCTION => type feedback information.
5351 // STUB => various things, e.g. a SMI
5352 // OPTIMIZED_FUNCTION => the next_code_link for optimized code list.
5353 DECL_ACCESSORS(raw_type_feedback_info, Object)
5354 inline Object* type_feedback_info();
5355 inline void set_type_feedback_info(
5356 Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5357 inline int stub_info();
5358 inline void set_stub_info(int info);
5360 // [next_code_link]: Link for lists of optimized or deoptimized code.
5361 // Note that storage for this field is overlapped with typefeedback_info.
5362 DECL_ACCESSORS(next_code_link, Object)
5364 // [gc_metadata]: Field used to hold GC related metadata. The contents of this
5365 // field does not have to be traced during garbage collection since
5366 // it is only used by the garbage collector itself.
5367 DECL_ACCESSORS(gc_metadata, Object)
5369 // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
5370 // at the moment when this object was created.
5371 inline void set_ic_age(int count);
5372 inline int ic_age();
5374 // [prologue_offset]: Offset of the function prologue, used for aging
5375 // FUNCTIONs and OPTIMIZED_FUNCTIONs.
5376 inline int prologue_offset();
5377 inline void set_prologue_offset(int offset);
5379 // Unchecked accessors to be used during GC.
5380 inline ByteArray* unchecked_relocation_info();
5382 inline int relocation_size();
5384 // [flags]: Various code flags.
5385 inline Flags flags();
5386 inline void set_flags(Flags flags);
5388 // [flags]: Access to specific code flags.
5390 inline Kind handler_kind() {
5391 return static_cast<Kind>(arguments_count());
5393 inline InlineCacheState ic_state(); // Only valid for IC stubs.
5394 inline ExtraICState extra_ic_state(); // Only valid for IC stubs.
5396 inline ExtraICState extended_extra_ic_state(); // Only valid for
5397 // non-call IC stubs.
5398 static bool needs_extended_extra_ic_state(Kind kind) {
5399 // TODO(danno): This is a bit of a hack right now since there are still
5400 // clients of this API that pass "extra" values in for argc. These clients
5401 // should be retrofitted to used ExtendedExtraICState.
5402 return kind == COMPARE_NIL_IC || kind == TO_BOOLEAN_IC ||
5403 kind == BINARY_OP_IC;
5406 inline StubType type(); // Only valid for monomorphic IC stubs.
5407 inline int arguments_count(); // Only valid for call IC stubs.
5409 // Testers for IC stub kinds.
5410 inline bool is_inline_cache_stub();
5411 inline bool is_debug_stub();
5412 inline bool is_handler() { return kind() == HANDLER; }
5413 inline bool is_load_stub() { return kind() == LOAD_IC; }
5414 inline bool is_keyed_load_stub() { return kind() == KEYED_LOAD_IC; }
5415 inline bool is_store_stub() { return kind() == STORE_IC; }
5416 inline bool is_keyed_store_stub() { return kind() == KEYED_STORE_IC; }
5417 inline bool is_binary_op_stub() { return kind() == BINARY_OP_IC; }
5418 inline bool is_compare_ic_stub() { return kind() == COMPARE_IC; }
5419 inline bool is_compare_nil_ic_stub() { return kind() == COMPARE_NIL_IC; }
5420 inline bool is_to_boolean_ic_stub() { return kind() == TO_BOOLEAN_IC; }
5421 inline bool is_keyed_stub();
5423 inline void set_raw_kind_specific_flags1(int value);
5424 inline void set_raw_kind_specific_flags2(int value);
5426 // [major_key]: For kind STUB or BINARY_OP_IC, the major key.
5427 inline int major_key();
5428 inline void set_major_key(int value);
5429 inline bool has_major_key();
5431 // For kind STUB or ICs, tells whether or not a code object was generated by
5432 // the optimizing compiler (but it may not be an optimized function).
5433 bool is_crankshafted();
5434 inline void set_is_crankshafted(bool value);
5436 // [optimizable]: For FUNCTION kind, tells if it is optimizable.
5437 inline bool optimizable();
5438 inline void set_optimizable(bool value);
5440 // [has_deoptimization_support]: For FUNCTION kind, tells if it has
5441 // deoptimization support.
5442 inline bool has_deoptimization_support();
5443 inline void set_has_deoptimization_support(bool value);
5445 // [has_debug_break_slots]: For FUNCTION kind, tells if it has
5446 // been compiled with debug break slots.
5447 inline bool has_debug_break_slots();
5448 inline void set_has_debug_break_slots(bool value);
5450 // [compiled_with_optimizing]: For FUNCTION kind, tells if it has
5451 // been compiled with IsOptimizing set to true.
5452 inline bool is_compiled_optimizable();
5453 inline void set_compiled_optimizable(bool value);
5455 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
5456 // how long the function has been marked for OSR and therefore which
5457 // level of loop nesting we are willing to do on-stack replacement
5459 inline void set_allow_osr_at_loop_nesting_level(int level);
5460 inline int allow_osr_at_loop_nesting_level();
5462 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
5463 // the code object was seen on the stack with no IC patching going on.
5464 inline int profiler_ticks();
5465 inline void set_profiler_ticks(int ticks);
5467 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
5468 // reserved in the code prologue.
5469 inline unsigned stack_slots();
5470 inline void set_stack_slots(unsigned slots);
5472 // [safepoint_table_start]: For kind OPTIMIZED_CODE, the offset in
5473 // the instruction stream where the safepoint table starts.
5474 inline unsigned safepoint_table_offset();
5475 inline void set_safepoint_table_offset(unsigned offset);
5477 // [back_edge_table_start]: For kind FUNCTION, the offset in the
5478 // instruction stream where the back edge table starts.
5479 inline unsigned back_edge_table_offset();
5480 inline void set_back_edge_table_offset(unsigned offset);
5482 inline bool back_edges_patched_for_osr();
5483 inline void set_back_edges_patched_for_osr(bool value);
5485 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
5486 inline byte to_boolean_state();
5488 // [has_function_cache]: For kind STUB tells whether there is a function
5489 // cache is passed to the stub.
5490 inline bool has_function_cache();
5491 inline void set_has_function_cache(bool flag);
5494 // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
5495 // the code is going to be deoptimized because of dead embedded maps.
5496 inline bool marked_for_deoptimization();
5497 inline void set_marked_for_deoptimization(bool flag);
5499 // [constant_pool]: The constant pool for this function.
5500 inline ConstantPoolArray* constant_pool();
5501 inline void set_constant_pool(Object* constant_pool);
5503 // Get the safepoint entry for the given pc.
5504 SafepointEntry GetSafepointEntry(Address pc);
5506 // Find an object in a stub with a specified map
5507 Object* FindNthObject(int n, Map* match_map);
5508 void ReplaceNthObject(int n, Map* match_map, Object* replace_with);
5510 // Find the first allocation site in an IC stub.
5511 AllocationSite* FindFirstAllocationSite();
5513 // Find the first map in an IC stub.
5514 Map* FindFirstMap();
5515 void FindAllMaps(MapHandleList* maps);
5516 void FindAllTypes(TypeHandleList* types);
5517 void ReplaceFirstMap(Map* replace);
5519 // Find the first handler in an IC stub.
5520 Code* FindFirstHandler();
5522 // Find |length| handlers and put them into |code_list|. Returns false if not
5523 // enough handlers can be found.
5524 bool FindHandlers(CodeHandleList* code_list, int length = -1);
5526 // Find the first name in an IC stub.
5527 Name* FindFirstName();
5529 void ReplaceNthCell(int n, Cell* replace_with);
5531 // The entire code object including its header is copied verbatim to the
5532 // snapshot so that it can be written in one, fast, memcpy during
5533 // deserialization. The deserializer will overwrite some pointers, rather
5534 // like a runtime linker, but the random allocation addresses used in the
5535 // mksnapshot process would still be present in the unlinked snapshot data,
5536 // which would make snapshot production non-reproducible. This method wipes
5537 // out the to-be-overwritten header data for reproducible snapshots.
5538 inline void WipeOutHeader();
5540 // Flags operations.
5541 static inline Flags ComputeFlags(
5543 InlineCacheState ic_state = UNINITIALIZED,
5544 ExtraICState extra_ic_state = kNoExtraICState,
5545 StubType type = NORMAL,
5547 InlineCacheHolderFlag holder = OWN_MAP);
5549 static inline Flags ComputeMonomorphicFlags(
5551 ExtraICState extra_ic_state = kNoExtraICState,
5552 InlineCacheHolderFlag holder = OWN_MAP,
5553 StubType type = NORMAL,
5556 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
5557 static inline StubType ExtractTypeFromFlags(Flags flags);
5558 static inline Kind ExtractKindFromFlags(Flags flags);
5559 static inline InlineCacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
5560 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
5561 static inline ExtraICState ExtractExtendedExtraICStateFromFlags(Flags flags);
5562 static inline int ExtractArgumentsCountFromFlags(Flags flags);
5564 static inline Flags RemoveTypeFromFlags(Flags flags);
5566 // Convert a target address into a code object.
5567 static inline Code* GetCodeFromTargetAddress(Address address);
5569 // Convert an entry address into an object.
5570 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
5572 // Returns the address of the first instruction.
5573 inline byte* instruction_start();
5575 // Returns the address right after the last instruction.
5576 inline byte* instruction_end();
5578 // Returns the size of the instructions, padding, and relocation information.
5579 inline int body_size();
5581 // Returns the address of the first relocation info (read backwards!).
5582 inline byte* relocation_start();
5584 // Code entry point.
5585 inline byte* entry();
5587 // Returns true if pc is inside this object's instructions.
5588 inline bool contains(byte* pc);
5590 // Relocate the code by delta bytes. Called to signal that this code
5591 // object has been moved by delta bytes.
5592 void Relocate(intptr_t delta);
5594 // Migrate code described by desc.
5595 void CopyFrom(const CodeDesc& desc);
5597 // Returns the object size for a given body (used for allocation).
5598 static int SizeFor(int body_size) {
5599 ASSERT_SIZE_TAG_ALIGNED(body_size);
5600 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
5603 // Calculate the size of the code object to report for log events. This takes
5604 // the layout of the code object into account.
5605 int ExecutableSize() {
5606 // Check that the assumptions about the layout of the code object holds.
5607 ASSERT_EQ(static_cast<int>(instruction_start() - address()),
5609 return instruction_size() + Code::kHeaderSize;
5612 // Locating source position.
5613 int SourcePosition(Address pc);
5614 int SourceStatementPosition(Address pc);
5617 static inline Code* cast(Object* obj);
5619 // Dispatched behavior.
5620 int CodeSize() { return SizeFor(body_size()); }
5621 inline void CodeIterateBody(ObjectVisitor* v);
5623 template<typename StaticVisitor>
5624 inline void CodeIterateBody(Heap* heap);
5626 DECLARE_PRINTER(Code)
5627 DECLARE_VERIFIER(Code)
5629 void ClearInlineCaches();
5630 void ClearInlineCaches(Kind kind);
5632 void ClearTypeFeedbackCells(Heap* heap);
5634 BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
5635 uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
5637 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
5639 kNotExecutedCodeAge = -2,
5640 kExecutedOnceCodeAge = -1,
5642 CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
5644 kFirstCodeAge = kNotExecutedCodeAge,
5645 kLastCodeAge = kAfterLastCodeAge - 1,
5646 kCodeAgeCount = kAfterLastCodeAge - kNotExecutedCodeAge - 1,
5647 kIsOldCodeAge = kSexagenarianCodeAge,
5648 kPreAgedCodeAge = kIsOldCodeAge - 1
5650 #undef DECLARE_CODE_AGE_ENUM
5652 // Code aging. Indicates how many full GCs this code has survived without
5653 // being entered through the prologue. Used to determine when it is
5654 // relatively safe to flush this code object and replace it with the lazy
5655 // compilation stub.
5656 static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
5657 static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
5658 void MakeOlder(MarkingParity);
5659 static bool IsYoungSequence(byte* sequence);
5662 // Gets the raw code age, including psuedo code-age values such as
5663 // kNotExecutedCodeAge and kExecutedOnceCodeAge.
5665 static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
5666 return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
5669 void PrintDeoptLocation(FILE* out, int bailout_id);
5670 bool CanDeoptAt(Address pc);
5673 void VerifyEmbeddedObjectsDependency();
5676 static bool IsWeakEmbeddedObject(Kind kind, Object* object);
5678 // Max loop nesting marker used to postpose OSR. We don't take loop
5679 // nesting that is deeper than 5 levels into account.
5680 static const int kMaxLoopNestingMarker = 6;
5682 // Layout description.
5683 static const int kInstructionSizeOffset = HeapObject::kHeaderSize;
5684 static const int kRelocationInfoOffset = kInstructionSizeOffset + kIntSize;
5685 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
5686 static const int kDeoptimizationDataOffset =
5687 kHandlerTableOffset + kPointerSize;
5688 static const int kTypeFeedbackInfoOffset =
5689 kDeoptimizationDataOffset + kPointerSize;
5690 static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset; // Shared.
5691 static const int kGCMetadataOffset = kTypeFeedbackInfoOffset + kPointerSize;
5692 static const int kICAgeOffset =
5693 kGCMetadataOffset + kPointerSize;
5694 static const int kFlagsOffset = kICAgeOffset + kIntSize;
5695 static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
5696 static const int kKindSpecificFlags2Offset =
5697 kKindSpecificFlags1Offset + kIntSize;
5698 // Note: We might be able to squeeze this into the flags above.
5699 static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
5700 static const int kConstantPoolOffset = kPrologueOffset + kPointerSize;
5702 static const int kHeaderPaddingStart = kConstantPoolOffset + kIntSize;
5704 // Add padding to align the instruction start following right after
5705 // the Code object header.
5706 static const int kHeaderSize =
5707 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
5709 // Byte offsets within kKindSpecificFlags1Offset.
5710 static const int kOptimizableOffset = kKindSpecificFlags1Offset;
5712 static const int kFullCodeFlags = kOptimizableOffset + 1;
5713 class FullCodeFlagsHasDeoptimizationSupportField:
5714 public BitField<bool, 0, 1> {}; // NOLINT
5715 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
5716 class FullCodeFlagsIsCompiledOptimizable: public BitField<bool, 2, 1> {};
5718 static const int kAllowOSRAtLoopNestingLevelOffset = kFullCodeFlags + 1;
5719 static const int kProfilerTicksOffset = kAllowOSRAtLoopNestingLevelOffset + 1;
5721 // Flags layout. BitField<type, shift, size>.
5722 class ICStateField: public BitField<InlineCacheState, 0, 3> {};
5723 class TypeField: public BitField<StubType, 3, 1> {};
5724 class CacheHolderField: public BitField<InlineCacheHolderFlag, 5, 1> {};
5725 class KindField: public BitField<Kind, 6, 4> {};
5726 // TODO(bmeurer): Bit 10 is available for free use. :-)
5727 class ExtraICStateField: public BitField<ExtraICState, 11, 6> {};
5728 class ExtendedExtraICStateField: public BitField<ExtraICState, 11,
5729 PlatformSmiTagging::kSmiValueSize - 11 + 1> {}; // NOLINT
5730 STATIC_ASSERT(ExtraICStateField::kShift == ExtendedExtraICStateField::kShift);
5732 // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
5733 static const int kStackSlotsFirstBit = 0;
5734 static const int kStackSlotsBitCount = 24;
5735 static const int kHasFunctionCacheFirstBit =
5736 kStackSlotsFirstBit + kStackSlotsBitCount;
5737 static const int kHasFunctionCacheBitCount = 1;
5738 static const int kMarkedForDeoptimizationFirstBit =
5739 kStackSlotsFirstBit + kStackSlotsBitCount + 1;
5740 static const int kMarkedForDeoptimizationBitCount = 1;
5742 STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
5743 STATIC_ASSERT(kHasFunctionCacheFirstBit + kHasFunctionCacheBitCount <= 32);
5744 STATIC_ASSERT(kMarkedForDeoptimizationFirstBit +
5745 kMarkedForDeoptimizationBitCount <= 32);
5747 class StackSlotsField: public BitField<int,
5748 kStackSlotsFirstBit, kStackSlotsBitCount> {}; // NOLINT
5749 class HasFunctionCacheField: public BitField<bool,
5750 kHasFunctionCacheFirstBit, kHasFunctionCacheBitCount> {}; // NOLINT
5751 class MarkedForDeoptimizationField: public BitField<bool,
5752 kMarkedForDeoptimizationFirstBit,
5753 kMarkedForDeoptimizationBitCount> {}; // NOLINT
5755 // KindSpecificFlags2 layout (ALL)
5756 static const int kIsCrankshaftedBit = 0;
5757 class IsCrankshaftedField: public BitField<bool,
5758 kIsCrankshaftedBit, 1> {}; // NOLINT
5760 // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
5761 static const int kStubMajorKeyFirstBit = kIsCrankshaftedBit + 1;
5762 static const int kSafepointTableOffsetFirstBit =
5763 kStubMajorKeyFirstBit + kStubMajorKeyBits;
5764 static const int kSafepointTableOffsetBitCount = 24;
5766 STATIC_ASSERT(kStubMajorKeyFirstBit + kStubMajorKeyBits <= 32);
5767 STATIC_ASSERT(kSafepointTableOffsetFirstBit +
5768 kSafepointTableOffsetBitCount <= 32);
5769 STATIC_ASSERT(1 + kStubMajorKeyBits +
5770 kSafepointTableOffsetBitCount <= 32);
5772 class SafepointTableOffsetField: public BitField<int,
5773 kSafepointTableOffsetFirstBit,
5774 kSafepointTableOffsetBitCount> {}; // NOLINT
5775 class StubMajorKeyField: public BitField<int,
5776 kStubMajorKeyFirstBit, kStubMajorKeyBits> {}; // NOLINT
5778 // KindSpecificFlags2 layout (FUNCTION)
5779 class BackEdgeTableOffsetField: public BitField<int,
5780 kIsCrankshaftedBit + 1, 29> {}; // NOLINT
5781 class BackEdgesPatchedForOSRField: public BitField<bool,
5782 kIsCrankshaftedBit + 1 + 29, 1> {}; // NOLINT
5784 // Signed field cannot be encoded using the BitField class.
5785 static const int kArgumentsCountShift = 17;
5786 static const int kArgumentsCountMask = ~((1 << kArgumentsCountShift) - 1);
5787 static const int kArgumentsBits =
5788 PlatformSmiTagging::kSmiValueSize - Code::kArgumentsCountShift + 1;
5789 static const int kMaxArguments = (1 << kArgumentsBits) - 1;
5791 // ICs can use either argument count or ExtendedExtraIC, since their storage
5793 STATIC_ASSERT(ExtraICStateField::kShift +
5794 ExtraICStateField::kSize + kArgumentsBits ==
5795 ExtendedExtraICStateField::kShift +
5796 ExtendedExtraICStateField::kSize);
5798 // This constant should be encodable in an ARM instruction.
5799 static const int kFlagsNotUsedInLookup =
5800 TypeField::kMask | CacheHolderField::kMask;
5803 friend class RelocIterator;
5805 void ClearInlineCaches(Kind* kind);
5808 byte* FindCodeAgeSequence();
5809 static void GetCodeAgeAndParity(Code* code, Age* age,
5810 MarkingParity* parity);
5811 static void GetCodeAgeAndParity(byte* sequence, Age* age,
5812 MarkingParity* parity);
5813 static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
5815 // Code aging -- platform-specific
5816 static void PatchPlatformCodeAge(Isolate* isolate,
5817 byte* sequence, Age age,
5818 MarkingParity parity);
5820 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5824 class CompilationInfo;
5826 // This class describes the layout of dependent codes array of a map. The
5827 // array is partitioned into several groups of dependent codes. Each group
5828 // contains codes with the same dependency on the map. The array has the
5829 // following layout for n dependency groups:
5831 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5832 // | C1 | C2 | ... | Cn | group 1 | group 2 | ... | group n | undefined |
5833 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5835 // The first n elements are Smis, each of them specifies the number of codes
5836 // in the corresponding group. The subsequent elements contain grouped code
5837 // objects. The suffix of the array can be filled with the undefined value if
5838 // the number of codes is less than the length of the array. The order of the
5839 // code objects within a group is not preserved.
5841 // All code indexes used in the class are counted starting from the first
5842 // code object of the first group. In other words, code index 0 corresponds
5843 // to array index n = kCodesStartIndex.
5845 class DependentCode: public FixedArray {
5847 enum DependencyGroup {
5848 // Group of code that weakly embed this map and depend on being
5849 // deoptimized when the map is garbage collected.
5850 kWeaklyEmbeddedGroup,
5851 // Group of code that embed a transition to this map, and depend on being
5852 // deoptimized when the transition is replaced by a new version.
5854 // Group of code that omit run-time prototype checks for prototypes
5855 // described by this map. The group is deoptimized whenever an object
5856 // described by this map changes shape (and transitions to a new map),
5857 // possibly invalidating the assumptions embedded in the code.
5858 kPrototypeCheckGroup,
5859 // Group of code that depends on elements not being added to objects with
5861 kElementsCantBeAddedGroup,
5862 // Group of code that depends on global property values in property cells
5863 // not being changed.
5864 kPropertyCellChangedGroup,
5865 // Group of code that depends on tenuring information in AllocationSites
5866 // not being changed.
5867 kAllocationSiteTenuringChangedGroup,
5868 // Group of code that depends on element transition information in
5869 // AllocationSites not being changed.
5870 kAllocationSiteTransitionChangedGroup,
5871 kGroupCount = kAllocationSiteTransitionChangedGroup + 1
5874 // Array for holding the index of the first code object of each group.
5875 // The last element stores the total number of code objects.
5876 class GroupStartIndexes {
5878 explicit GroupStartIndexes(DependentCode* entries);
5879 void Recompute(DependentCode* entries);
5880 int at(int i) { return start_indexes_[i]; }
5881 int number_of_entries() { return start_indexes_[kGroupCount]; }
5883 int start_indexes_[kGroupCount + 1];
5886 bool Contains(DependencyGroup group, Code* code);
5887 static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5888 DependencyGroup group,
5889 Handle<Object> object);
5890 void UpdateToFinishedCode(DependencyGroup group,
5891 CompilationInfo* info,
5893 void RemoveCompilationInfo(DependentCode::DependencyGroup group,
5894 CompilationInfo* info);
5896 void DeoptimizeDependentCodeGroup(Isolate* isolate,
5897 DependentCode::DependencyGroup group);
5899 bool MarkCodeForDeoptimization(Isolate* isolate,
5900 DependentCode::DependencyGroup group);
5902 // The following low-level accessors should only be used by this class
5903 // and the mark compact collector.
5904 inline int number_of_entries(DependencyGroup group);
5905 inline void set_number_of_entries(DependencyGroup group, int value);
5906 inline bool is_code_at(int i);
5907 inline Code* code_at(int i);
5908 inline CompilationInfo* compilation_info_at(int i);
5909 inline void set_object_at(int i, Object* object);
5910 inline Object** slot_at(int i);
5911 inline Object* object_at(int i);
5912 inline void clear_at(int i);
5913 inline void copy(int from, int to);
5914 static inline DependentCode* cast(Object* object);
5916 static DependentCode* ForObject(Handle<HeapObject> object,
5917 DependencyGroup group);
5920 // Make a room at the end of the given group by moving out the first
5921 // code objects of the subsequent groups.
5922 inline void ExtendGroup(DependencyGroup group);
5923 static const int kCodesStartIndex = kGroupCount;
5927 // All heap objects have a Map that describes their structure.
5928 // A Map contains information about:
5929 // - Size information about the object
5930 // - How to iterate over an object (for garbage collection)
5931 class Map: public HeapObject {
5934 // Size in bytes or kVariableSizeSentinel if instances do not have
5936 inline int instance_size();
5937 inline void set_instance_size(int value);
5939 // Count of properties allocated in the object.
5940 inline int inobject_properties();
5941 inline void set_inobject_properties(int value);
5943 // Count of property fields pre-allocated in the object when first allocated.
5944 inline int pre_allocated_property_fields();
5945 inline void set_pre_allocated_property_fields(int value);
5948 inline InstanceType instance_type();
5949 inline void set_instance_type(InstanceType value);
5951 // Tells how many unused property fields are available in the
5952 // instance (only used for JSObject in fast mode).
5953 inline int unused_property_fields();
5954 inline void set_unused_property_fields(int value);
5957 inline byte bit_field();
5958 inline void set_bit_field(byte value);
5961 inline byte bit_field2();
5962 inline void set_bit_field2(byte value);
5965 inline uint32_t bit_field3();
5966 inline void set_bit_field3(uint32_t bits);
5968 class EnumLengthBits: public BitField<int,
5969 0, kDescriptorIndexBitCount> {}; // NOLINT
5970 class NumberOfOwnDescriptorsBits: public BitField<int,
5971 kDescriptorIndexBitCount, kDescriptorIndexBitCount> {}; // NOLINT
5972 STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
5973 class IsShared: public BitField<bool, 20, 1> {};
5974 class FunctionWithPrototype: public BitField<bool, 21, 1> {};
5975 class DictionaryMap: public BitField<bool, 22, 1> {};
5976 class OwnsDescriptors: public BitField<bool, 23, 1> {};
5977 class HasInstanceCallHandler: public BitField<bool, 24, 1> {};
5978 class Deprecated: public BitField<bool, 25, 1> {};
5979 class IsFrozen: public BitField<bool, 26, 1> {};
5980 class IsUnstable: public BitField<bool, 27, 1> {};
5981 class IsMigrationTarget: public BitField<bool, 28, 1> {};
5983 // Tells whether the object in the prototype property will be used
5984 // for instances created from this function. If the prototype
5985 // property is set to a value that is not a JSObject, the prototype
5986 // property will not be used to create instances of the function.
5987 // See ECMA-262, 13.2.2.
5988 inline void set_non_instance_prototype(bool value);
5989 inline bool has_non_instance_prototype();
5991 // Tells whether function has special prototype property. If not, prototype
5992 // property will not be created when accessed (will return undefined),
5993 // and construction from this function will not be allowed.
5994 inline void set_function_with_prototype(bool value);
5995 inline bool function_with_prototype();
5997 // Tells whether the instance with this map should be ignored by the
5998 // Object.getPrototypeOf() function and the __proto__ accessor.
5999 inline void set_is_hidden_prototype() {
6000 set_bit_field(bit_field() | (1 << kIsHiddenPrototype));
6003 inline bool is_hidden_prototype() {
6004 return ((1 << kIsHiddenPrototype) & bit_field()) != 0;
6007 // Records and queries whether the instance has a named interceptor.
6008 inline void set_has_named_interceptor() {
6009 set_bit_field(bit_field() | (1 << kHasNamedInterceptor));
6012 inline bool has_named_interceptor() {
6013 return ((1 << kHasNamedInterceptor) & bit_field()) != 0;
6016 // Records and queries whether the instance has an indexed interceptor.
6017 inline void set_has_indexed_interceptor() {
6018 set_bit_field(bit_field() | (1 << kHasIndexedInterceptor));
6021 inline bool has_indexed_interceptor() {
6022 return ((1 << kHasIndexedInterceptor) & bit_field()) != 0;
6025 // Tells whether the instance is undetectable.
6026 // An undetectable object is a special class of JSObject: 'typeof' operator
6027 // returns undefined, ToBoolean returns false. Otherwise it behaves like
6028 // a normal JS object. It is useful for implementing undetectable
6029 // document.all in Firefox & Safari.
6030 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
6031 inline void set_is_undetectable() {
6032 set_bit_field(bit_field() | (1 << kIsUndetectable));
6035 inline bool is_undetectable() {
6036 return ((1 << kIsUndetectable) & bit_field()) != 0;
6039 // Tells whether the instance has a call-as-function handler.
6040 inline void set_is_observed() {
6041 set_bit_field(bit_field() | (1 << kIsObserved));
6044 inline bool is_observed() {
6045 return ((1 << kIsObserved) & bit_field()) != 0;
6048 inline void set_is_extensible(bool value);
6049 inline bool is_extensible();
6051 inline void set_elements_kind(ElementsKind elements_kind) {
6052 ASSERT(elements_kind < kElementsKindCount);
6053 ASSERT(kElementsKindCount <= (1 << kElementsKindBitCount));
6054 set_bit_field2((bit_field2() & ~kElementsKindMask) |
6055 (elements_kind << kElementsKindShift));
6056 ASSERT(this->elements_kind() == elements_kind);
6059 inline ElementsKind elements_kind() {
6060 return static_cast<ElementsKind>(
6061 (bit_field2() & kElementsKindMask) >> kElementsKindShift);
6064 // Tells whether the instance has fast elements that are only Smis.
6065 inline bool has_fast_smi_elements() {
6066 return IsFastSmiElementsKind(elements_kind());
6069 // Tells whether the instance has fast elements.
6070 inline bool has_fast_object_elements() {
6071 return IsFastObjectElementsKind(elements_kind());
6074 inline bool has_fast_smi_or_object_elements() {
6075 return IsFastSmiOrObjectElementsKind(elements_kind());
6078 inline bool has_fast_double_elements() {
6079 return IsFastDoubleElementsKind(elements_kind());
6082 inline bool has_fast_elements() {
6083 return IsFastElementsKind(elements_kind());
6086 inline bool has_non_strict_arguments_elements() {
6087 return elements_kind() == NON_STRICT_ARGUMENTS_ELEMENTS;
6090 inline bool has_external_array_elements() {
6091 return IsExternalArrayElementsKind(elements_kind());
6094 inline bool has_fixed_typed_array_elements() {
6095 return IsFixedTypedArrayElementsKind(elements_kind());
6098 inline bool has_dictionary_elements() {
6099 return IsDictionaryElementsKind(elements_kind());
6102 inline bool has_slow_elements_kind() {
6103 return elements_kind() == DICTIONARY_ELEMENTS
6104 || elements_kind() == NON_STRICT_ARGUMENTS_ELEMENTS;
6107 static bool IsValidElementsTransition(ElementsKind from_kind,
6108 ElementsKind to_kind);
6110 // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
6111 // map with DICTIONARY_ELEMENTS was found in the prototype chain.
6112 bool DictionaryElementsInPrototypeChainOnly();
6114 inline bool HasTransitionArray();
6115 inline bool HasElementsTransition();
6116 inline Map* elements_transition_map();
6117 MUST_USE_RESULT inline MaybeObject* set_elements_transition_map(
6118 Map* transitioned_map);
6119 inline void SetTransition(int transition_index, Map* target);
6120 inline Map* GetTransition(int transition_index);
6122 static Handle<TransitionArray> AddTransition(Handle<Map> map,
6125 SimpleTransitionFlag flag);
6127 MUST_USE_RESULT inline MaybeObject* AddTransition(Name* key,
6129 SimpleTransitionFlag flag);
6130 DECL_ACCESSORS(transitions, TransitionArray)
6131 inline void ClearTransitions(Heap* heap,
6132 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
6134 void DeprecateTransitionTree();
6135 void DeprecateTarget(Name* key, DescriptorArray* new_descriptors);
6138 Map* FindUpdatedMap(int verbatim, int length, DescriptorArray* descriptors);
6139 Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
6141 inline int GetInObjectPropertyOffset(int index);
6143 int NumberOfFields();
6145 bool InstancesNeedRewriting(Map* target,
6146 int target_number_of_fields,
6147 int target_inobject,
6149 static Handle<Map> GeneralizeAllFieldRepresentations(
6151 Representation new_representation);
6152 static Handle<Map> GeneralizeRepresentation(
6155 Representation new_representation,
6156 StoreMode store_mode);
6157 static Handle<Map> CopyGeneralizeAllRepresentations(
6160 StoreMode store_mode,
6161 PropertyAttributes attributes,
6162 const char* reason);
6164 void PrintGeneralization(FILE* file,
6169 bool constant_to_field,
6170 Representation old_representation,
6171 Representation new_representation);
6173 // Returns the constructor name (the name (possibly, inferred name) of the
6174 // function that was used to instantiate the object).
6175 String* constructor_name();
6177 // Tells whether the map is attached to SharedFunctionInfo
6178 // (for inobject slack tracking).
6179 inline void set_attached_to_shared_function_info(bool value);
6181 inline bool attached_to_shared_function_info();
6183 // Tells whether the map is shared between objects that may have different
6184 // behavior. If true, the map should never be modified, instead a clone
6185 // should be created and modified.
6186 inline void set_is_shared(bool value);
6187 inline bool is_shared();
6189 // Tells whether the map is used for JSObjects in dictionary mode (ie
6190 // normalized objects, ie objects for which HasFastProperties returns false).
6191 // A map can never be used for both dictionary mode and fast mode JSObjects.
6192 // False by default and for HeapObjects that are not JSObjects.
6193 inline void set_dictionary_map(bool value);
6194 inline bool is_dictionary_map();
6196 // Tells whether the instance needs security checks when accessing its
6198 inline void set_is_access_check_needed(bool access_check_needed);
6199 inline bool is_access_check_needed();
6201 // Returns true if map has a non-empty stub code cache.
6202 inline bool has_code_cache();
6204 // [prototype]: implicit prototype object.
6205 DECL_ACCESSORS(prototype, Object)
6207 // [constructor]: points back to the function responsible for this map.
6208 DECL_ACCESSORS(constructor, Object)
6210 // [instance descriptors]: describes the object.
6211 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
6212 inline void InitializeDescriptors(DescriptorArray* descriptors);
6214 // [stub cache]: contains stubs compiled for this map.
6215 DECL_ACCESSORS(code_cache, Object)
6217 // [dependent code]: list of optimized codes that have this map embedded.
6218 DECL_ACCESSORS(dependent_code, DependentCode)
6220 // [back pointer]: points back to the parent map from which a transition
6221 // leads to this map. The field overlaps with prototype transitions and the
6222 // back pointer will be moved into the prototype transitions array if
6224 inline Object* GetBackPointer();
6225 inline void SetBackPointer(Object* value,
6226 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
6227 inline void init_back_pointer(Object* undefined);
6229 // [prototype transitions]: cache of prototype transitions.
6230 // Prototype transition is a transition that happens
6231 // when we change object's prototype to a new one.
6233 // 0: finger - index of the first free cell in the cache
6234 // 1: back pointer that overlaps with prototype transitions field.
6235 // 2 + 2 * i: prototype
6236 // 3 + 2 * i: target map
6237 inline FixedArray* GetPrototypeTransitions();
6238 MUST_USE_RESULT inline MaybeObject* SetPrototypeTransitions(
6239 FixedArray* prototype_transitions);
6240 inline bool HasPrototypeTransitions();
6242 inline HeapObject* UncheckedPrototypeTransitions();
6243 inline TransitionArray* unchecked_transition_array();
6245 static const int kProtoTransitionHeaderSize = 1;
6246 static const int kProtoTransitionNumberOfEntriesOffset = 0;
6247 static const int kProtoTransitionElementsPerEntry = 2;
6248 static const int kProtoTransitionPrototypeOffset = 0;
6249 static const int kProtoTransitionMapOffset = 1;
6251 inline int NumberOfProtoTransitions() {
6252 FixedArray* cache = GetPrototypeTransitions();
6253 if (cache->length() == 0) return 0;
6255 Smi::cast(cache->get(kProtoTransitionNumberOfEntriesOffset))->value();
6258 inline void SetNumberOfProtoTransitions(int value) {
6259 FixedArray* cache = GetPrototypeTransitions();
6260 ASSERT(cache->length() != 0);
6261 cache->set(kProtoTransitionNumberOfEntriesOffset, Smi::FromInt(value));
6264 // Lookup in the map's instance descriptors and fill out the result
6265 // with the given holder if the name is found. The holder may be
6266 // NULL when this function is used from the compiler.
6267 inline void LookupDescriptor(JSObject* holder,
6269 LookupResult* result);
6271 inline void LookupTransition(JSObject* holder,
6273 LookupResult* result);
6275 inline PropertyDetails GetLastDescriptorDetails();
6277 // The size of transition arrays are limited so they do not end up in large
6278 // object space. Otherwise ClearNonLiveTransitions would leak memory while
6279 // applying in-place right trimming.
6280 inline bool CanHaveMoreTransitions();
6283 int number_of_own_descriptors = NumberOfOwnDescriptors();
6284 ASSERT(number_of_own_descriptors > 0);
6285 return number_of_own_descriptors - 1;
6288 int NumberOfOwnDescriptors() {
6289 return NumberOfOwnDescriptorsBits::decode(bit_field3());
6292 void SetNumberOfOwnDescriptors(int number) {
6293 ASSERT(number <= instance_descriptors()->number_of_descriptors());
6294 set_bit_field3(NumberOfOwnDescriptorsBits::update(bit_field3(), number));
6297 inline Cell* RetrieveDescriptorsPointer();
6300 return EnumLengthBits::decode(bit_field3());
6303 void SetEnumLength(int length) {
6304 if (length != kInvalidEnumCacheSentinel) {
6305 ASSERT(length >= 0);
6306 ASSERT(length == 0 || instance_descriptors()->HasEnumCache());
6307 ASSERT(length <= NumberOfOwnDescriptors());
6309 set_bit_field3(EnumLengthBits::update(bit_field3(), length));
6312 inline bool owns_descriptors();
6313 inline void set_owns_descriptors(bool is_shared);
6314 inline bool has_instance_call_handler();
6315 inline void set_has_instance_call_handler();
6316 inline void freeze();
6317 inline bool is_frozen();
6318 inline void mark_unstable();
6319 inline bool is_stable();
6320 inline void set_migration_target(bool value);
6321 inline bool is_migration_target();
6322 inline void deprecate();
6323 inline bool is_deprecated();
6324 inline bool CanBeDeprecated();
6325 // Returns a non-deprecated version of the input. If the input was not
6326 // deprecated, it is directly returned. Otherwise, the non-deprecated version
6327 // is found by re-transitioning from the root of the transition tree using the
6328 // descriptor array of the map. Returns NULL if no updated map is found.
6329 // This method also applies any pending migrations along the prototype chain.
6330 static Handle<Map> CurrentMapForDeprecated(Handle<Map> map);
6331 // Same as above, but does not touch the prototype chain.
6332 static Handle<Map> CurrentMapForDeprecatedInternal(Handle<Map> map);
6334 static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
6335 MUST_USE_RESULT MaybeObject* RawCopy(int instance_size);
6336 MUST_USE_RESULT MaybeObject* CopyWithPreallocatedFieldDescriptors();
6337 static Handle<Map> CopyDropDescriptors(Handle<Map> map);
6338 MUST_USE_RESULT MaybeObject* CopyDropDescriptors();
6339 static Handle<Map> CopyReplaceDescriptors(Handle<Map> map,
6340 Handle<DescriptorArray> descriptors,
6341 TransitionFlag flag,
6343 MUST_USE_RESULT MaybeObject* CopyReplaceDescriptors(
6344 DescriptorArray* descriptors,
6345 TransitionFlag flag,
6347 SimpleTransitionFlag simple_flag = FULL_TRANSITION);
6348 static Handle<Map> CopyInstallDescriptors(
6351 Handle<DescriptorArray> descriptors);
6352 MUST_USE_RESULT MaybeObject* ShareDescriptor(DescriptorArray* descriptors,
6353 Descriptor* descriptor);
6354 MUST_USE_RESULT MaybeObject* CopyAddDescriptor(Descriptor* descriptor,
6355 TransitionFlag flag);
6356 MUST_USE_RESULT MaybeObject* CopyInsertDescriptor(Descriptor* descriptor,
6357 TransitionFlag flag);
6358 MUST_USE_RESULT MaybeObject* CopyReplaceDescriptor(
6359 DescriptorArray* descriptors,
6360 Descriptor* descriptor,
6362 TransitionFlag flag);
6363 MUST_USE_RESULT MaybeObject* AsElementsKind(ElementsKind kind);
6365 MUST_USE_RESULT MaybeObject* CopyAsElementsKind(ElementsKind kind,
6366 TransitionFlag flag);
6368 static Handle<Map> CopyForObserved(Handle<Map> map);
6370 static Handle<Map> CopyNormalized(Handle<Map> map,
6371 PropertyNormalizationMode mode,
6372 NormalizedMapSharingMode sharing);
6374 inline void AppendDescriptor(Descriptor* desc,
6375 const DescriptorArray::WhitenessWitness&);
6377 // Returns a copy of the map, with all transitions dropped from the
6378 // instance descriptors.
6379 static Handle<Map> Copy(Handle<Map> map);
6380 MUST_USE_RESULT MaybeObject* Copy();
6382 // Returns the next free property index (only valid for FAST MODE).
6383 int NextFreePropertyIndex();
6385 // Returns the number of properties described in instance_descriptors
6386 // filtering out properties with the specified attributes.
6387 int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
6388 PropertyAttributes filter = NONE);
6390 // Returns the number of slots allocated for the initial properties
6391 // backing storage for instances of this map.
6392 int InitialPropertiesLength() {
6393 return pre_allocated_property_fields() + unused_property_fields() -
6394 inobject_properties();
6398 static inline Map* cast(Object* obj);
6400 // Locate an accessor in the instance descriptor.
6401 AccessorDescriptor* FindAccessor(Name* name);
6403 // Code cache operations.
6405 // Clears the code cache.
6406 inline void ClearCodeCache(Heap* heap);
6408 // Update code cache.
6409 static void UpdateCodeCache(Handle<Map> map,
6412 MUST_USE_RESULT MaybeObject* UpdateCodeCache(Name* name, Code* code);
6414 // Extend the descriptor array of the map with the list of descriptors.
6415 // In case of duplicates, the latest descriptor is used.
6416 static void AppendCallbackDescriptors(Handle<Map> map,
6417 Handle<Object> descriptors);
6419 static void EnsureDescriptorSlack(Handle<Map> map, int slack);
6421 // Returns the found code or undefined if absent.
6422 Object* FindInCodeCache(Name* name, Code::Flags flags);
6424 // Returns the non-negative index of the code object if it is in the
6425 // cache and -1 otherwise.
6426 int IndexInCodeCache(Object* name, Code* code);
6428 // Removes a code object from the code cache at the given index.
6429 void RemoveFromCodeCache(Name* name, Code* code, int index);
6431 // Set all map transitions from this map to dead maps to null. Also clear
6432 // back pointers in transition targets so that we do not process this map
6433 // again while following back pointers.
6434 void ClearNonLiveTransitions(Heap* heap);
6436 // Computes a hash value for this map, to be used in HashTables and such.
6439 bool EquivalentToForTransition(Map* other);
6441 // Compares this map to another to see if they describe equivalent objects.
6442 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
6443 // it had exactly zero inobject properties.
6444 // The "shared" flags of both this map and |other| are ignored.
6445 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
6447 // Returns the map that this map transitions to if its elements_kind
6448 // is changed to |elements_kind|, or NULL if no such map is cached yet.
6449 // |safe_to_add_transitions| is set to false if adding transitions is not
6451 Map* LookupElementsTransitionMap(ElementsKind elements_kind);
6453 // Returns the transitioned map for this map with the most generic
6454 // elements_kind that's found in |candidates|, or null handle if no match is
6456 Handle<Map> FindTransitionedMap(MapHandleList* candidates);
6457 Map* FindTransitionedMap(MapList* candidates);
6459 // Zaps the contents of backing data structures. Note that the
6460 // heap verifier (i.e. VerifyMarkingVisitor) relies on zapping of objects
6461 // holding weak references when incremental marking is used, because it also
6462 // iterates over objects that are otherwise unreachable.
6463 // In general we only want to call these functions in release mode when
6464 // heap verification is turned on.
6465 void ZapPrototypeTransitions();
6466 void ZapTransitions();
6468 bool CanTransition() {
6469 // Only JSObject and subtypes have map transitions and back pointers.
6470 STATIC_ASSERT(LAST_TYPE == LAST_JS_OBJECT_TYPE);
6471 return instance_type() >= FIRST_JS_OBJECT_TYPE;
6474 bool IsJSObjectMap() {
6475 return instance_type() >= FIRST_JS_OBJECT_TYPE;
6477 bool IsJSGlobalProxyMap() {
6478 return instance_type() == JS_GLOBAL_PROXY_TYPE;
6480 bool IsJSGlobalObjectMap() {
6481 return instance_type() == JS_GLOBAL_OBJECT_TYPE;
6483 bool IsGlobalObjectMap() {
6484 const InstanceType type = instance_type();
6485 return type == JS_GLOBAL_OBJECT_TYPE || type == JS_BUILTINS_OBJECT_TYPE;
6488 // Fires when the layout of an object with a leaf map changes.
6489 // This includes adding transitions to the leaf map or changing
6490 // the descriptor array.
6491 inline void NotifyLeafMapLayoutChange();
6493 inline bool CanOmitMapChecks();
6495 void AddDependentCompilationInfo(DependentCode::DependencyGroup group,
6496 CompilationInfo* info);
6498 void AddDependentCode(DependentCode::DependencyGroup group,
6501 bool IsMapInArrayPrototypeChain();
6503 // Dispatched behavior.
6504 DECLARE_PRINTER(Map)
6505 DECLARE_VERIFIER(Map)
6508 void SharedMapVerify();
6509 void VerifyOmittedMapChecks();
6512 inline int visitor_id();
6513 inline void set_visitor_id(int visitor_id);
6515 typedef void (*TraverseCallback)(Map* map, void* data);
6517 void TraverseTransitionTree(TraverseCallback callback, void* data);
6519 // When you set the prototype of an object using the __proto__ accessor you
6520 // need a new map for the object (the prototype is stored in the map). In
6521 // order not to multiply maps unnecessarily we store these as transitions in
6522 // the original map. That way we can transition to the same map if the same
6523 // prototype is set, rather than creating a new map every time. The
6524 // transitions are in the form of a map where the keys are prototype objects
6525 // and the values are the maps the are transitioned to.
6526 static const int kMaxCachedPrototypeTransitions = 256;
6527 static Handle<Map> GetPrototypeTransition(Handle<Map> map,
6528 Handle<Object> prototype);
6529 static Handle<Map> PutPrototypeTransition(Handle<Map> map,
6530 Handle<Object> prototype,
6531 Handle<Map> target_map);
6533 static const int kMaxPreAllocatedPropertyFields = 255;
6535 // Layout description.
6536 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
6537 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
6538 static const int kPrototypeOffset = kInstanceAttributesOffset + kIntSize;
6539 static const int kConstructorOffset = kPrototypeOffset + kPointerSize;
6540 // Storage for the transition array is overloaded to directly contain a back
6541 // pointer if unused. When the map has transitions, the back pointer is
6542 // transferred to the transition array and accessed through an extra
6544 static const int kTransitionsOrBackPointerOffset =
6545 kConstructorOffset + kPointerSize;
6546 static const int kDescriptorsOffset =
6547 kTransitionsOrBackPointerOffset + kPointerSize;
6548 static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
6549 static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
6550 static const int kBitField3Offset = kDependentCodeOffset + kPointerSize;
6551 static const int kSize = kBitField3Offset + kPointerSize;
6553 // Layout of pointer fields. Heap iteration code relies on them
6554 // being continuously allocated.
6555 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
6556 static const int kPointerFieldsEndOffset = kBitField3Offset + kPointerSize;
6558 // Byte offsets within kInstanceSizesOffset.
6559 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
6560 static const int kInObjectPropertiesByte = 1;
6561 static const int kInObjectPropertiesOffset =
6562 kInstanceSizesOffset + kInObjectPropertiesByte;
6563 static const int kPreAllocatedPropertyFieldsByte = 2;
6564 static const int kPreAllocatedPropertyFieldsOffset =
6565 kInstanceSizesOffset + kPreAllocatedPropertyFieldsByte;
6566 static const int kVisitorIdByte = 3;
6567 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
6569 // Byte offsets within kInstanceAttributesOffset attributes.
6570 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
6571 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 1;
6572 static const int kBitFieldOffset = kInstanceAttributesOffset + 2;
6573 static const int kBitField2Offset = kInstanceAttributesOffset + 3;
6575 STATIC_CHECK(kInstanceTypeOffset == Internals::kMapInstanceTypeOffset);
6577 // Bit positions for bit field.
6578 static const int kUnused = 0; // To be used for marking recently used maps.
6579 static const int kHasNonInstancePrototype = 1;
6580 static const int kIsHiddenPrototype = 2;
6581 static const int kHasNamedInterceptor = 3;
6582 static const int kHasIndexedInterceptor = 4;
6583 static const int kIsUndetectable = 5;
6584 static const int kIsObserved = 6;
6585 static const int kIsAccessCheckNeeded = 7;
6587 // Bit positions for bit field 2
6588 static const int kIsExtensible = 0;
6589 static const int kStringWrapperSafeForDefaultValueOf = 1;
6590 static const int kAttachedToSharedFunctionInfo = 2;
6591 // No bits can be used after kElementsKindFirstBit, they are all reserved for
6592 // storing ElementKind.
6593 static const int kElementsKindShift = 3;
6594 static const int kElementsKindBitCount = 5;
6596 // Derived values from bit field 2
6597 static const int kElementsKindMask = (-1 << kElementsKindShift) &
6598 ((1 << (kElementsKindShift + kElementsKindBitCount)) - 1);
6599 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
6600 (FAST_ELEMENTS + 1) << Map::kElementsKindShift) - 1;
6601 static const int8_t kMaximumBitField2FastSmiElementValue =
6602 static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
6603 Map::kElementsKindShift) - 1;
6604 static const int8_t kMaximumBitField2FastHoleyElementValue =
6605 static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
6606 Map::kElementsKindShift) - 1;
6607 static const int8_t kMaximumBitField2FastHoleySmiElementValue =
6608 static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
6609 Map::kElementsKindShift) - 1;
6611 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
6612 kPointerFieldsEndOffset,
6613 kSize> BodyDescriptor;
6616 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
6620 // An abstract superclass, a marker class really, for simple structure classes.
6621 // It doesn't carry much functionality but allows struct classes to be
6622 // identified in the type system.
6623 class Struct: public HeapObject {
6625 inline void InitializeBody(int object_size);
6626 static inline Struct* cast(Object* that);
6630 // A simple one-element struct, useful where smis need to be boxed.
6631 class Box : public Struct {
6633 // [value]: the boxed contents.
6634 DECL_ACCESSORS(value, Object)
6636 static inline Box* cast(Object* obj);
6638 // Dispatched behavior.
6639 DECLARE_PRINTER(Box)
6640 DECLARE_VERIFIER(Box)
6642 static const int kValueOffset = HeapObject::kHeaderSize;
6643 static const int kSize = kValueOffset + kPointerSize;
6646 DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
6650 // Script describes a script which has been added to the VM.
6651 class Script: public Struct {
6660 // Script compilation types.
6661 enum CompilationType {
6662 COMPILATION_TYPE_HOST = 0,
6663 COMPILATION_TYPE_EVAL = 1
6666 // Script compilation state.
6667 enum CompilationState {
6668 COMPILATION_STATE_INITIAL = 0,
6669 COMPILATION_STATE_COMPILED = 1
6672 // [source]: the script source.
6673 DECL_ACCESSORS(source, Object)
6675 // [name]: the script name.
6676 DECL_ACCESSORS(name, Object)
6678 // [id]: the script id.
6679 DECL_ACCESSORS(id, Smi)
6681 // [line_offset]: script line offset in resource from where it was extracted.
6682 DECL_ACCESSORS(line_offset, Smi)
6684 // [column_offset]: script column offset in resource from where it was
6686 DECL_ACCESSORS(column_offset, Smi)
6688 // [data]: additional data associated with this script.
6689 DECL_ACCESSORS(data, Object)
6691 // [context_data]: context data for the context this script was compiled in.
6692 DECL_ACCESSORS(context_data, Object)
6694 // [wrapper]: the wrapper cache.
6695 DECL_ACCESSORS(wrapper, Foreign)
6697 // [type]: the script type.
6698 DECL_ACCESSORS(type, Smi)
6700 // [line_ends]: FixedArray of line ends positions.
6701 DECL_ACCESSORS(line_ends, Object)
6703 // [eval_from_shared]: for eval scripts the shared funcion info for the
6704 // function from which eval was called.
6705 DECL_ACCESSORS(eval_from_shared, Object)
6707 // [eval_from_instructions_offset]: the instruction offset in the code for the
6708 // function from which eval was called where eval was called.
6709 DECL_ACCESSORS(eval_from_instructions_offset, Smi)
6711 // [flags]: Holds an exciting bitfield.
6712 DECL_ACCESSORS(flags, Smi)
6714 // [compilation_type]: how the the script was compiled. Encoded in the
6716 inline CompilationType compilation_type();
6717 inline void set_compilation_type(CompilationType type);
6719 // [compilation_state]: determines whether the script has already been
6720 // compiled. Encoded in the 'flags' field.
6721 inline CompilationState compilation_state();
6722 inline void set_compilation_state(CompilationState state);
6724 // [is_shared_cross_origin]: An opaque boolean set by the embedder via
6725 // ScriptOrigin, and used by the embedder to make decisions about the
6726 // script's level of privilege. V8 just passes this through. Encoded in
6727 // the 'flags' field.
6728 DECL_BOOLEAN_ACCESSORS(is_shared_cross_origin)
6730 static inline Script* cast(Object* obj);
6732 // If script source is an external string, check that the underlying
6733 // resource is accessible. Otherwise, always return true.
6734 inline bool HasValidSource();
6736 // Dispatched behavior.
6737 DECLARE_PRINTER(Script)
6738 DECLARE_VERIFIER(Script)
6740 static const int kSourceOffset = HeapObject::kHeaderSize;
6741 static const int kNameOffset = kSourceOffset + kPointerSize;
6742 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
6743 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
6744 static const int kDataOffset = kColumnOffsetOffset + kPointerSize;
6745 static const int kContextOffset = kDataOffset + kPointerSize;
6746 static const int kWrapperOffset = kContextOffset + kPointerSize;
6747 static const int kTypeOffset = kWrapperOffset + kPointerSize;
6748 static const int kLineEndsOffset = kTypeOffset + kPointerSize;
6749 static const int kIdOffset = kLineEndsOffset + kPointerSize;
6750 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
6751 static const int kEvalFrominstructionsOffsetOffset =
6752 kEvalFromSharedOffset + kPointerSize;
6753 static const int kFlagsOffset =
6754 kEvalFrominstructionsOffsetOffset + kPointerSize;
6755 static const int kSize = kFlagsOffset + kPointerSize;
6758 // Bit positions in the flags field.
6759 static const int kCompilationTypeBit = 0;
6760 static const int kCompilationStateBit = 1;
6761 static const int kIsSharedCrossOriginBit = 2;
6763 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6767 // List of builtin functions we want to identify to improve code
6770 // Each entry has a name of a global object property holding an object
6771 // optionally followed by ".prototype", a name of a builtin function
6772 // on the object (the one the id is set for), and a label.
6774 // Installation of ids for the selected builtin functions is handled
6775 // by the bootstrapper.
6776 #define FUNCTIONS_WITH_ID_LIST(V) \
6777 V(Array.prototype, push, ArrayPush) \
6778 V(Array.prototype, pop, ArrayPop) \
6779 V(Function.prototype, apply, FunctionApply) \
6780 V(String.prototype, charCodeAt, StringCharCodeAt) \
6781 V(String.prototype, charAt, StringCharAt) \
6782 V(String, fromCharCode, StringFromCharCode) \
6783 V(Math, floor, MathFloor) \
6784 V(Math, round, MathRound) \
6785 V(Math, ceil, MathCeil) \
6786 V(Math, abs, MathAbs) \
6787 V(Math, log, MathLog) \
6788 V(Math, exp, MathExp) \
6789 V(Math, sqrt, MathSqrt) \
6790 V(Math, pow, MathPow) \
6791 V(Math, max, MathMax) \
6792 V(Math, min, MathMin) \
6793 V(Math, imul, MathImul)
6795 #define SIMD_NULLARY_OPERATIONS(V) \
6796 V(SIMD.float32x4, zero, Float32x4Zero, Float32x4) \
6797 V(SIMD.int32x4, zero, Int32x4Zero, Int32x4)
6799 #define SIMD_UNARY_OPERATIONS(V) \
6800 V(SIMD.float32x4, abs, Float32x4Abs, Float32x4, Float32x4) \
6801 V(SIMD.float32x4, bitsToInt32x4, Float32x4BitsToInt32x4, Int32x4, Float32x4) \
6802 V(SIMD.float32x4, neg, Float32x4Neg, Float32x4, Float32x4) \
6803 V(SIMD.float32x4, reciprocal, Float32x4Reciprocal, Float32x4, Float32x4) \
6804 V(SIMD.float32x4, reciprocalSqrt, Float32x4ReciprocalSqrt, \
6805 Float32x4, Float32x4) \
6806 V(SIMD.float32x4, splat, Float32x4Splat, Float32x4, Double) \
6807 V(SIMD.float32x4, sqrt, Float32x4Sqrt, Float32x4, Float32x4) \
6808 V(SIMD.float32x4, toInt32x4, Float32x4ToInt32x4, Int32x4, Float32x4) \
6809 V(SIMD.int32x4, bitsToFloat32x4, Int32x4BitsToFloat32x4, Float32x4, Int32x4) \
6810 V(SIMD.int32x4, neg, Int32x4Neg, Int32x4, Int32x4) \
6811 V(SIMD.int32x4, not, Int32x4Not, Int32x4, Int32x4) \
6812 V(SIMD.int32x4, splat, Int32x4Splat, Int32x4, Integer32) \
6813 V(SIMD.int32x4, toFloat32x4, Int32x4ToFloat32x4, Float32x4, Int32x4)
6815 // Do not need to install them in InstallExperimentalSIMDBuiltinFunctionIds.
6816 #define SIMD_UNARY_OPERATIONS_FOR_PROPERTY_ACCESS(V) \
6817 V(SIMD.float32x4.prototype, signMask, Float32x4GetSignMask, Integer32, \
6819 V(SIMD.float32x4.prototype, x, Float32x4GetX, Double, Float32x4) \
6820 V(SIMD.float32x4.prototype, y, Float32x4GetY, Double, Float32x4) \
6821 V(SIMD.float32x4.prototype, z, Float32x4GetZ, Double, Float32x4) \
6822 V(SIMD.float32x4.prototype, w, Float32x4GetW, Double, Float32x4) \
6823 V(SIMD.int32x4.prototype, signMask, Int32x4GetSignMask, Integer32, Int32x4) \
6824 V(SIMD.int32x4.prototype, x, Int32x4GetX, Integer32, Int32x4) \
6825 V(SIMD.int32x4.prototype, y, Int32x4GetY, Integer32, Int32x4) \
6826 V(SIMD.int32x4.prototype, z, Int32x4GetZ, Integer32, Int32x4) \
6827 V(SIMD.int32x4.prototype, w, Int32x4GetW, Integer32, Int32x4) \
6828 V(SIMD.int32x4.prototype, flagX, Int32x4GetFlagX, Tagged, Int32x4) \
6829 V(SIMD.int32x4.prototype, flagY, Int32x4GetFlagY, Tagged, Int32x4) \
6830 V(SIMD.int32x4.prototype, flagZ, Int32x4GetFlagZ, Tagged, Int32x4) \
6831 V(SIMD.int32x4.prototype, flagW, Int32x4GetFlagW, Tagged, Int32x4)
6833 #define SIMD_BINARY_OPERATIONS(V) \
6834 V(SIMD.float32x4, add, Float32x4Add, Float32x4, Float32x4, Float32x4) \
6835 V(SIMD.float32x4, div, Float32x4Div, Float32x4, Float32x4, Float32x4) \
6836 V(SIMD.float32x4, max, Float32x4Max, Float32x4, Float32x4, Float32x4) \
6837 V(SIMD.float32x4, min, Float32x4Min, Float32x4, Float32x4, Float32x4) \
6838 V(SIMD.float32x4, mul, Float32x4Mul, Float32x4, Float32x4, Float32x4) \
6839 V(SIMD.float32x4, sub, Float32x4Sub, Float32x4, Float32x4, Float32x4) \
6840 V(SIMD.float32x4, equal, Float32x4Equal, Int32x4, Float32x4, Float32x4) \
6841 V(SIMD.float32x4, notEqual, Float32x4NotEqual, Int32x4, Float32x4, \
6843 V(SIMD.float32x4, greaterThan, Float32x4GreaterThan, Int32x4, Float32x4, \
6845 V(SIMD.float32x4, greaterThanOrEqual, Float32x4GreaterThanOrEqual, Int32x4, \
6846 Float32x4, Float32x4) \
6847 V(SIMD.float32x4, lessThan, Float32x4LessThan, Int32x4, Float32x4, \
6849 V(SIMD.float32x4, lessThanOrEqual, Float32x4LessThanOrEqual, Int32x4, \
6850 Float32x4, Float32x4) \
6851 V(SIMD.float32x4, shuffle, Float32x4Shuffle, Float32x4, Float32x4, \
6853 V(SIMD.float32x4, scale, Float32x4Scale, Float32x4, Float32x4, Double) \
6854 V(SIMD.float32x4, withX, Float32x4WithX, Float32x4, Float32x4, Double) \
6855 V(SIMD.float32x4, withY, Float32x4WithY, Float32x4, Float32x4, Double) \
6856 V(SIMD.float32x4, withZ, Float32x4WithZ, Float32x4, Float32x4, Double) \
6857 V(SIMD.float32x4, withW, Float32x4WithW, Float32x4, Float32x4, Double) \
6858 V(SIMD.int32x4, add, Int32x4Add, Int32x4, Int32x4, Int32x4) \
6859 V(SIMD.int32x4, and, Int32x4And, Int32x4, Int32x4, Int32x4) \
6860 V(SIMD.int32x4, mul, Int32x4Mul, Int32x4, Int32x4, Int32x4) \
6861 V(SIMD.int32x4, or, Int32x4Or, Int32x4, Int32x4, Int32x4) \
6862 V(SIMD.int32x4, sub, Int32x4Sub, Int32x4, Int32x4, Int32x4) \
6863 V(SIMD.int32x4, xor, Int32x4Xor, Int32x4, Int32x4, Int32x4) \
6864 V(SIMD.int32x4, shuffle, Int32x4Shuffle, Int32x4, Int32x4, Integer32) \
6865 V(SIMD.int32x4, withX, Int32x4WithX, Int32x4, Int32x4, Integer32) \
6866 V(SIMD.int32x4, withY, Int32x4WithY, Int32x4, Int32x4, Integer32) \
6867 V(SIMD.int32x4, withZ, Int32x4WithZ, Int32x4, Int32x4, Integer32) \
6868 V(SIMD.int32x4, withW, Int32x4WithW, Int32x4, Int32x4, Integer32) \
6869 V(SIMD.int32x4, withFlagX, Int32x4WithFlagX, Int32x4, Int32x4, Tagged) \
6870 V(SIMD.int32x4, withFlagY, Int32x4WithFlagY, Int32x4, Int32x4, Tagged) \
6871 V(SIMD.int32x4, withFlagZ, Int32x4WithFlagZ, Int32x4, Int32x4, Tagged) \
6872 V(SIMD.int32x4, withFlagW, Int32x4WithFlagW, Int32x4, Int32x4, Tagged) \
6873 V(SIMD.int32x4, greaterThan, Int32x4GreaterThan, Int32x4, Int32x4, Int32x4) \
6874 V(SIMD.int32x4, equal, Int32x4Equal, Int32x4, Int32x4, Int32x4) \
6875 V(SIMD.int32x4, lessThan, Int32x4LessThan, Int32x4, Int32x4, Int32x4) \
6876 V(SIMD.int32x4, shiftLeft, Int32x4ShiftLeft, Int32x4, Int32x4, Integer32) \
6877 V(SIMD.int32x4, shiftRight, Int32x4ShiftRight, Int32x4, Int32x4, Integer32) \
6878 V(SIMD.int32x4, shiftRightArithmetic, Int32x4ShiftRightArithmetic, Int32x4, \
6881 #define SIMD_TERNARY_OPERATIONS(V) \
6882 V(SIMD.float32x4, clamp, Float32x4Clamp, Float32x4, Float32x4, Float32x4, \
6884 V(SIMD.float32x4, shuffleMix, Float32x4ShuffleMix, Float32x4, Float32x4, \
6885 Float32x4, Integer32) \
6886 V(SIMD.int32x4, select, Int32x4Select, Float32x4, Int32x4, Float32x4, \
6889 #define SIMD_QUARTERNARY_OPERATIONS(V) \
6890 V(SIMD, float32x4, Float32x4Constructor, Float32x4, Double, Double, Double, \
6892 V(SIMD, int32x4, Int32x4Constructor, Int32x4, Integer32, Integer32, \
6893 Integer32, Integer32) \
6894 V(SIMD.int32x4, bool, Int32x4Bool, Int32x4, Tagged, Tagged, Tagged, Tagged)
6896 #define SIMD_ARRAY_OPERATIONS(V) \
6897 V(Float32x4Array.prototype, getAt, Float32x4ArrayGetAt) \
6898 V(Float32x4Array.prototype, setAt, Float32x4ArraySetAt) \
6899 V(Int32x4Array.prototype, getAt, Int32x4ArrayGetAt) \
6900 V(Int32x4Array.prototype, setAt, Int32x4ArraySetAt)
6902 // Do not need to install them in InstallExperimentalSIMDBuiltinFunctionIds.
6903 #define SIMD_FAKE_ID_LISTS(V) \
6904 V(SIMD, unreachable, SIMD128Unreachable) \
6905 V(SIMD, change, SIMD128Change)
6907 enum BuiltinFunctionId {
6909 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
6911 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6912 // Fake id for a special case of Math.pow. Note, it continues the
6913 // list of math functions.
6915 SIMD_FAKE_ID_LISTS(DECLARE_FUNCTION_ID)
6916 SIMD_ARRAY_OPERATIONS(DECLARE_FUNCTION_ID)
6917 #undef DECLARE_FUNCTION_ID
6918 #define DECLARE_SIMD_NULLARY_FUNCTION_ID(i1, i2, name, i3) \
6920 SIMD_NULLARY_OPERATIONS(DECLARE_SIMD_NULLARY_FUNCTION_ID)
6921 #undef DECLARE_SIMD_NULLARY_FUNCTION_ID
6922 #define DECLARE_SIMD_UNARY_FUNCTION_ID(i1, i2, name, i3, i4) \
6924 SIMD_UNARY_OPERATIONS(DECLARE_SIMD_UNARY_FUNCTION_ID)
6925 SIMD_UNARY_OPERATIONS_FOR_PROPERTY_ACCESS(DECLARE_SIMD_UNARY_FUNCTION_ID)
6926 #undef DECLARE_SIMD_UNARY_FUNCTION_ID
6927 #define DECLARE_SIMD_BINARY_FUNCTION_ID(i1, i2, name, i3, i4, i5) \
6929 SIMD_BINARY_OPERATIONS(DECLARE_SIMD_BINARY_FUNCTION_ID)
6930 #undef DECLARE_SIMD_BINARY_FUNCTION_ID
6931 #define DECLARE_SIMD_TERNARY_FUNCTION_ID(i1, i2, name, i3, i4, i5, i6) \
6933 SIMD_TERNARY_OPERATIONS(DECLARE_SIMD_TERNARY_FUNCTION_ID)
6934 #undef DECLARE_SIMD_TERNARY_FUNCTION_ID
6935 #define DECLARE_SIMD_QUARTERNARY_FUNCTION_ID(i1, i2, name, i3, i4, i5, i6, i7) \
6937 SIMD_QUARTERNARY_OPERATIONS(DECLARE_SIMD_QUARTERNARY_FUNCTION_ID)
6938 #undef DECLARE_SIMD_QUARTERNARY_FUNCTION_ID
6939 kNumberOfBuiltinFunction
6943 // SharedFunctionInfo describes the JSFunction information that can be
6944 // shared by multiple instances of the function.
6945 class SharedFunctionInfo: public HeapObject {
6947 // [name]: Function name.
6948 DECL_ACCESSORS(name, Object)
6950 // [code]: Function code.
6951 DECL_ACCESSORS(code, Code)
6952 inline void ReplaceCode(Code* code);
6954 // [optimized_code_map]: Map from native context to optimized code
6955 // and a shared literals array or Smi(0) if none.
6956 DECL_ACCESSORS(optimized_code_map, Object)
6958 // Returns index i of the entry with the specified context and OSR entry.
6959 // At position i - 1 is the context, position i the code, and i + 1 the
6960 // literals array. Returns -1 when no matching entry is found.
6961 int SearchOptimizedCodeMap(Context* native_context, BailoutId osr_ast_id);
6963 // Installs optimized code from the code map on the given closure. The
6964 // index has to be consistent with a search result as defined above.
6965 FixedArray* GetLiteralsFromOptimizedCodeMap(int index);
6967 Code* GetCodeFromOptimizedCodeMap(int index);
6969 // Clear optimized code map.
6970 void ClearOptimizedCodeMap();
6972 // Removed a specific optimized code object from the optimized code map.
6973 void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
6975 // Trims the optimized code map after entries have been removed.
6976 void TrimOptimizedCodeMap(int shrink_by);
6978 // Add a new entry to the optimized code map.
6979 MUST_USE_RESULT MaybeObject* AddToOptimizedCodeMap(Context* native_context,
6981 FixedArray* literals,
6982 BailoutId osr_ast_id);
6983 static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6984 Handle<Context> native_context,
6986 Handle<FixedArray> literals,
6987 BailoutId osr_ast_id);
6989 // Layout description of the optimized code map.
6990 static const int kNextMapIndex = 0;
6991 static const int kEntriesStart = 1;
6992 static const int kContextOffset = 0;
6993 static const int kCachedCodeOffset = 1;
6994 static const int kLiteralsOffset = 2;
6995 static const int kOsrAstIdOffset = 3;
6996 static const int kEntryLength = 4;
6997 static const int kFirstContextSlot = FixedArray::kHeaderSize +
6998 (kEntriesStart + kContextOffset) * kPointerSize;
6999 static const int kFirstCodeSlot = FixedArray::kHeaderSize +
7000 (kEntriesStart + kCachedCodeOffset) * kPointerSize;
7001 static const int kFirstOsrAstIdSlot = FixedArray::kHeaderSize +
7002 (kEntriesStart + kOsrAstIdOffset) * kPointerSize;
7003 static const int kSecondEntryIndex = kEntryLength + kEntriesStart;
7004 static const int kInitialLength = kEntriesStart + kEntryLength;
7006 // [scope_info]: Scope info.
7007 DECL_ACCESSORS(scope_info, ScopeInfo)
7009 // [construct stub]: Code stub for constructing instances of this function.
7010 DECL_ACCESSORS(construct_stub, Code)
7012 // Returns if this function has been compiled to native code yet.
7013 inline bool is_compiled();
7015 // [length]: The function length - usually the number of declared parameters.
7016 // Use up to 2^30 parameters.
7017 inline int length();
7018 inline void set_length(int value);
7020 // [formal parameter count]: The declared number of parameters.
7021 inline int formal_parameter_count();
7022 inline void set_formal_parameter_count(int value);
7024 // Set the formal parameter count so the function code will be
7025 // called without using argument adaptor frames.
7026 inline void DontAdaptArguments();
7028 // [expected_nof_properties]: Expected number of properties for the function.
7029 inline int expected_nof_properties();
7030 inline void set_expected_nof_properties(int value);
7032 // Inobject slack tracking is the way to reclaim unused inobject space.
7034 // The instance size is initially determined by adding some slack to
7035 // expected_nof_properties (to allow for a few extra properties added
7036 // after the constructor). There is no guarantee that the extra space
7037 // will not be wasted.
7039 // Here is the algorithm to reclaim the unused inobject space:
7040 // - Detect the first constructor call for this SharedFunctionInfo.
7041 // When it happens enter the "in progress" state: remember the
7042 // constructor's initial_map and install a special construct stub that
7043 // counts constructor calls.
7044 // - While the tracking is in progress create objects filled with
7045 // one_pointer_filler_map instead of undefined_value. This way they can be
7046 // resized quickly and safely.
7047 // - Once enough (kGenerousAllocationCount) objects have been created
7048 // compute the 'slack' (traverse the map transition tree starting from the
7049 // initial_map and find the lowest value of unused_property_fields).
7050 // - Traverse the transition tree again and decrease the instance size
7051 // of every map. Existing objects will resize automatically (they are
7052 // filled with one_pointer_filler_map). All further allocations will
7053 // use the adjusted instance size.
7054 // - Decrease expected_nof_properties so that an allocations made from
7055 // another context will use the adjusted instance size too.
7056 // - Exit "in progress" state by clearing the reference to the initial_map
7057 // and setting the regular construct stub (generic or inline).
7059 // The above is the main event sequence. Some special cases are possible
7060 // while the tracking is in progress:
7063 // Check if the initial_map is referenced by any live objects (except this
7064 // SharedFunctionInfo). If it is, continue tracking as usual.
7065 // If it is not, clear the reference and reset the tracking state. The
7066 // tracking will be initiated again on the next constructor call.
7068 // - The constructor is called from another context.
7069 // Immediately complete the tracking, perform all the necessary changes
7070 // to maps. This is necessary because there is no efficient way to track
7071 // multiple initial_maps.
7072 // Proceed to create an object in the current context (with the adjusted
7075 // - A different constructor function sharing the same SharedFunctionInfo is
7076 // called in the same context. This could be another closure in the same
7077 // context, or the first function could have been disposed.
7078 // This is handled the same way as the previous case.
7080 // Important: inobject slack tracking is not attempted during the snapshot
7083 static const int kGenerousAllocationCount = 8;
7085 // [construction_count]: Counter for constructor calls made during
7086 // the tracking phase.
7087 inline int construction_count();
7088 inline void set_construction_count(int value);
7090 // [initial_map]: initial map of the first function called as a constructor.
7091 // Saved for the duration of the tracking phase.
7092 // This is a weak link (GC resets it to undefined_value if no other live
7093 // object reference this map).
7094 DECL_ACCESSORS(initial_map, Object)
7096 // True if the initial_map is not undefined and the countdown stub is
7098 inline bool IsInobjectSlackTrackingInProgress();
7100 // Starts the tracking.
7101 // Stores the initial map and installs the countdown stub.
7102 // IsInobjectSlackTrackingInProgress is normally true after this call,
7103 // except when tracking have not been started (e.g. the map has no unused
7104 // properties or the snapshot is being built).
7105 void StartInobjectSlackTracking(Map* map);
7107 // Completes the tracking.
7108 // IsInobjectSlackTrackingInProgress is false after this call.
7109 void CompleteInobjectSlackTracking();
7111 // Invoked before pointers in SharedFunctionInfo are being marked.
7112 // Also clears the optimized code map.
7113 inline void BeforeVisitingPointers();
7115 // Clears the initial_map before the GC marking phase to ensure the reference
7116 // is weak. IsInobjectSlackTrackingInProgress is false after this call.
7117 void DetachInitialMap();
7119 // Restores the link to the initial map after the GC marking phase.
7120 // IsInobjectSlackTrackingInProgress is true after this call.
7121 void AttachInitialMap(Map* map);
7123 // False if there are definitely no live objects created from this function.
7124 // True if live objects _may_ exist (existence not guaranteed).
7125 // May go back from true to false after GC.
7126 DECL_BOOLEAN_ACCESSORS(live_objects_may_exist)
7128 // [instance class name]: class name for instances.
7129 DECL_ACCESSORS(instance_class_name, Object)
7131 // [function data]: This field holds some additional data for function.
7132 // Currently it either has FunctionTemplateInfo to make benefit the API
7133 // or Smi identifying a builtin function.
7134 // In the long run we don't want all functions to have this field but
7135 // we can fix that when we have a better model for storing hidden data
7137 DECL_ACCESSORS(function_data, Object)
7139 inline bool IsApiFunction();
7140 inline FunctionTemplateInfo* get_api_func_data();
7141 inline bool HasBuiltinFunctionId();
7142 inline BuiltinFunctionId builtin_function_id();
7144 // [script info]: Script from which the function originates.
7145 DECL_ACCESSORS(script, Object)
7147 // [num_literals]: Number of literals used by this function.
7148 inline int num_literals();
7149 inline void set_num_literals(int value);
7151 // [start_position_and_type]: Field used to store both the source code
7152 // position, whether or not the function is a function expression,
7153 // and whether or not the function is a toplevel function. The two
7154 // least significants bit indicates whether the function is an
7155 // expression and the rest contains the source code position.
7156 inline int start_position_and_type();
7157 inline void set_start_position_and_type(int value);
7159 // [debug info]: Debug information.
7160 DECL_ACCESSORS(debug_info, Object)
7162 // [inferred name]: Name inferred from variable or property
7163 // assignment of this function. Used to facilitate debugging and
7164 // profiling of JavaScript code written in OO style, where almost
7165 // all functions are anonymous but are assigned to object
7167 DECL_ACCESSORS(inferred_name, String)
7169 // The function's name if it is non-empty, otherwise the inferred name.
7170 String* DebugName();
7172 // Position of the 'function' token in the script source.
7173 inline int function_token_position();
7174 inline void set_function_token_position(int function_token_position);
7176 // Position of this function in the script source.
7177 inline int start_position();
7178 inline void set_start_position(int start_position);
7180 // End position of this function in the script source.
7181 inline int end_position();
7182 inline void set_end_position(int end_position);
7184 // Is this function a function expression in the source code.
7185 DECL_BOOLEAN_ACCESSORS(is_expression)
7187 // Is this function a top-level function (scripts, evals).
7188 DECL_BOOLEAN_ACCESSORS(is_toplevel)
7190 // Bit field containing various information collected by the compiler to
7191 // drive optimization.
7192 inline int compiler_hints();
7193 inline void set_compiler_hints(int value);
7195 inline int ast_node_count();
7196 inline void set_ast_node_count(int count);
7198 inline int profiler_ticks();
7200 // Inline cache age is used to infer whether the function survived a context
7201 // disposal or not. In the former case we reset the opt_count.
7202 inline int ic_age();
7203 inline void set_ic_age(int age);
7205 // Indicates if this function can be lazy compiled.
7206 // This is used to determine if we can safely flush code from a function
7207 // when doing GC if we expect that the function will no longer be used.
7208 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
7210 // Indicates if this function can be lazy compiled without a context.
7211 // This is used to determine if we can force compilation without reaching
7212 // the function through program execution but through other means (e.g. heap
7213 // iteration by the debugger).
7214 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
7216 // Indicates whether optimizations have been disabled for this
7217 // shared function info. If a function is repeatedly optimized or if
7218 // we cannot optimize the function we disable optimization to avoid
7219 // spending time attempting to optimize it again.
7220 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
7222 // Indicates the language mode of the function's code as defined by the
7223 // current harmony drafts for the next ES language standard. Possible
7225 // 1. CLASSIC_MODE - Unrestricted syntax and semantics, same as in ES5.
7226 // 2. STRICT_MODE - Restricted syntax and semantics, same as in ES5.
7227 // 3. EXTENDED_MODE - Only available under the harmony flag, not part of ES5.
7228 inline LanguageMode language_mode();
7229 inline void set_language_mode(LanguageMode language_mode);
7231 // Indicates whether the language mode of this function is CLASSIC_MODE.
7232 inline bool is_classic_mode();
7234 // Indicates whether the language mode of this function is EXTENDED_MODE.
7235 inline bool is_extended_mode();
7237 // False if the function definitely does not allocate an arguments object.
7238 DECL_BOOLEAN_ACCESSORS(uses_arguments)
7240 // True if the function has any duplicated parameter names.
7241 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
7243 // Indicates whether the function is a native function.
7244 // These needs special treatment in .call and .apply since
7245 // null passed as the receiver should not be translated to the
7247 DECL_BOOLEAN_ACCESSORS(native)
7249 // Indicate that this builtin needs to be inlined in crankshaft.
7250 DECL_BOOLEAN_ACCESSORS(inline_builtin)
7252 // Indicates that the function was created by the Function function.
7253 // Though it's anonymous, toString should treat it as if it had the name
7254 // "anonymous". We don't set the name itself so that the system does not
7255 // see a binding for it.
7256 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
7258 // Indicates whether the function is a bound function created using
7259 // the bind function.
7260 DECL_BOOLEAN_ACCESSORS(bound)
7262 // Indicates that the function is anonymous (the name field can be set
7263 // through the API, which does not change this flag).
7264 DECL_BOOLEAN_ACCESSORS(is_anonymous)
7266 // Is this a function or top-level/eval code.
7267 DECL_BOOLEAN_ACCESSORS(is_function)
7269 // Indicates that the function cannot be optimized.
7270 DECL_BOOLEAN_ACCESSORS(dont_optimize)
7272 // Indicates that the function cannot be inlined.
7273 DECL_BOOLEAN_ACCESSORS(dont_inline)
7275 // Indicates that code for this function cannot be cached.
7276 DECL_BOOLEAN_ACCESSORS(dont_cache)
7278 // Indicates that code for this function cannot be flushed.
7279 DECL_BOOLEAN_ACCESSORS(dont_flush)
7281 // Indicates that this function is a generator.
7282 DECL_BOOLEAN_ACCESSORS(is_generator)
7284 // Indicates whether or not the code in the shared function support
7286 inline bool has_deoptimization_support();
7288 // Enable deoptimization support through recompiled code.
7289 void EnableDeoptimizationSupport(Code* recompiled);
7291 // Disable (further) attempted optimization of all functions sharing this
7292 // shared function info.
7293 void DisableOptimization(BailoutReason reason);
7295 inline BailoutReason DisableOptimizationReason();
7297 // Lookup the bailout ID and ASSERT that it exists in the non-optimized
7298 // code, returns whether it asserted (i.e., always true if assertions are
7300 bool VerifyBailoutId(BailoutId id);
7302 // [source code]: Source code for the function.
7303 bool HasSourceCode();
7304 Handle<Object> GetSourceCode();
7306 // Number of times the function was optimized.
7307 inline int opt_count();
7308 inline void set_opt_count(int opt_count);
7310 // Number of times the function was deoptimized.
7311 inline void set_deopt_count(int value);
7312 inline int deopt_count();
7313 inline void increment_deopt_count();
7315 // Number of time we tried to re-enable optimization after it
7316 // was disabled due to high number of deoptimizations.
7317 inline void set_opt_reenable_tries(int value);
7318 inline int opt_reenable_tries();
7320 inline void TryReenableOptimization();
7322 // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
7323 inline void set_counters(int value);
7324 inline int counters();
7326 // Stores opt_count and bailout_reason as bit-fields.
7327 inline void set_opt_count_and_bailout_reason(int value);
7328 inline int opt_count_and_bailout_reason();
7330 void set_bailout_reason(BailoutReason reason) {
7331 set_opt_count_and_bailout_reason(
7332 DisabledOptimizationReasonBits::update(opt_count_and_bailout_reason(),
7336 void set_dont_optimize_reason(BailoutReason reason) {
7337 set_bailout_reason(reason);
7338 set_dont_optimize(reason != kNoReason);
7341 // Check whether or not this function is inlineable.
7342 bool IsInlineable();
7344 // Source size of this function.
7347 // Calculate the instance size.
7348 int CalculateInstanceSize();
7350 // Calculate the number of in-object properties.
7351 int CalculateInObjectProperties();
7353 // Dispatched behavior.
7354 // Set max_length to -1 for unlimited length.
7355 void SourceCodePrint(StringStream* accumulator, int max_length);
7356 DECLARE_PRINTER(SharedFunctionInfo)
7357 DECLARE_VERIFIER(SharedFunctionInfo)
7359 void ResetForNewContext(int new_ic_age);
7362 static inline SharedFunctionInfo* cast(Object* obj);
7365 static const int kDontAdaptArgumentsSentinel = -1;
7367 // Layout description.
7369 static const int kNameOffset = HeapObject::kHeaderSize;
7370 static const int kCodeOffset = kNameOffset + kPointerSize;
7371 static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
7372 static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
7373 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
7374 static const int kInstanceClassNameOffset =
7375 kConstructStubOffset + kPointerSize;
7376 static const int kFunctionDataOffset =
7377 kInstanceClassNameOffset + kPointerSize;
7378 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
7379 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
7380 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
7381 static const int kInitialMapOffset =
7382 kInferredNameOffset + kPointerSize;
7383 // ast_node_count is a Smi field. It could be grouped with another Smi field
7384 // into a PSEUDO_SMI_ACCESSORS pair (on x64), if one becomes available.
7385 static const int kAstNodeCountOffset =
7386 kInitialMapOffset + kPointerSize;
7387 #if V8_HOST_ARCH_32_BIT
7389 static const int kLengthOffset =
7390 kAstNodeCountOffset + kPointerSize;
7391 static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
7392 static const int kExpectedNofPropertiesOffset =
7393 kFormalParameterCountOffset + kPointerSize;
7394 static const int kNumLiteralsOffset =
7395 kExpectedNofPropertiesOffset + kPointerSize;
7396 static const int kStartPositionAndTypeOffset =
7397 kNumLiteralsOffset + kPointerSize;
7398 static const int kEndPositionOffset =
7399 kStartPositionAndTypeOffset + kPointerSize;
7400 static const int kFunctionTokenPositionOffset =
7401 kEndPositionOffset + kPointerSize;
7402 static const int kCompilerHintsOffset =
7403 kFunctionTokenPositionOffset + kPointerSize;
7404 static const int kOptCountAndBailoutReasonOffset =
7405 kCompilerHintsOffset + kPointerSize;
7406 static const int kCountersOffset =
7407 kOptCountAndBailoutReasonOffset + kPointerSize;
7410 static const int kSize = kCountersOffset + kPointerSize;
7412 // The only reason to use smi fields instead of int fields
7413 // is to allow iteration without maps decoding during
7414 // garbage collections.
7415 // To avoid wasting space on 64-bit architectures we use
7416 // the following trick: we group integer fields into pairs
7417 // First integer in each pair is shifted left by 1.
7418 // By doing this we guarantee that LSB of each kPointerSize aligned
7419 // word is not set and thus this word cannot be treated as pointer
7420 // to HeapObject during old space traversal.
7421 static const int kLengthOffset =
7422 kAstNodeCountOffset + kPointerSize;
7423 static const int kFormalParameterCountOffset =
7424 kLengthOffset + kIntSize;
7426 static const int kExpectedNofPropertiesOffset =
7427 kFormalParameterCountOffset + kIntSize;
7428 static const int kNumLiteralsOffset =
7429 kExpectedNofPropertiesOffset + kIntSize;
7431 static const int kEndPositionOffset =
7432 kNumLiteralsOffset + kIntSize;
7433 static const int kStartPositionAndTypeOffset =
7434 kEndPositionOffset + kIntSize;
7436 static const int kFunctionTokenPositionOffset =
7437 kStartPositionAndTypeOffset + kIntSize;
7438 static const int kCompilerHintsOffset =
7439 kFunctionTokenPositionOffset + kIntSize;
7441 static const int kOptCountAndBailoutReasonOffset =
7442 kCompilerHintsOffset + kIntSize;
7444 static const int kCountersOffset =
7445 kOptCountAndBailoutReasonOffset + kIntSize;
7448 static const int kSize = kCountersOffset + kIntSize;
7452 // The construction counter for inobject slack tracking is stored in the
7453 // most significant byte of compiler_hints which is otherwise unused.
7454 // Its offset depends on the endian-ness of the architecture.
7455 #if __BYTE_ORDER == __LITTLE_ENDIAN
7456 static const int kConstructionCountOffset = kCompilerHintsOffset + 3;
7457 #elif __BYTE_ORDER == __BIG_ENDIAN
7458 static const int kConstructionCountOffset = kCompilerHintsOffset + 0;
7460 #error Unknown byte ordering
7463 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
7465 typedef FixedBodyDescriptor<kNameOffset,
7466 kInitialMapOffset + kPointerSize,
7467 kSize> BodyDescriptor;
7469 // Bit positions in start_position_and_type.
7470 // The source code start position is in the 30 most significant bits of
7471 // the start_position_and_type field.
7472 static const int kIsExpressionBit = 0;
7473 static const int kIsTopLevelBit = 1;
7474 static const int kStartPositionShift = 2;
7475 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
7477 // Bit positions in compiler_hints.
7478 enum CompilerHints {
7479 kAllowLazyCompilation,
7480 kAllowLazyCompilationWithoutContext,
7481 kLiveObjectsMayExist,
7482 kOptimizationDisabled,
7483 kStrictModeFunction,
7484 kExtendedModeFunction,
7486 kHasDuplicateParameters,
7491 kNameShouldPrintAsAnonymous,
7498 kCompilerHintsCount // Pseudo entry
7501 class DeoptCountBits: public BitField<int, 0, 4> {};
7502 class OptReenableTriesBits: public BitField<int, 4, 18> {};
7503 class ICAgeBits: public BitField<int, 22, 8> {};
7505 class OptCountBits: public BitField<int, 0, 22> {};
7506 class DisabledOptimizationReasonBits: public BitField<int, 22, 8> {};
7509 #if V8_HOST_ARCH_32_BIT
7510 // On 32 bit platforms, compiler hints is a smi.
7511 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
7512 static const int kCompilerHintsSize = kPointerSize;
7514 // On 64 bit platforms, compiler hints is not a smi, see comment above.
7515 static const int kCompilerHintsSmiTagSize = 0;
7516 static const int kCompilerHintsSize = kIntSize;
7519 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
7520 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
7523 // Constants for optimizing codegen for strict mode function and
7525 // Allows to use byte-width instructions.
7526 static const int kStrictModeBitWithinByte =
7527 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
7529 static const int kExtendedModeBitWithinByte =
7530 (kExtendedModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
7532 static const int kNativeBitWithinByte =
7533 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
7535 #if __BYTE_ORDER == __LITTLE_ENDIAN
7536 static const int kStrictModeByteOffset = kCompilerHintsOffset +
7537 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
7538 static const int kExtendedModeByteOffset = kCompilerHintsOffset +
7539 (kExtendedModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
7540 static const int kNativeByteOffset = kCompilerHintsOffset +
7541 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
7542 #elif __BYTE_ORDER == __BIG_ENDIAN
7543 static const int kStrictModeByteOffset = kCompilerHintsOffset +
7544 (kCompilerHintsSize - 1) -
7545 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
7546 static const int kExtendedModeByteOffset = kCompilerHintsOffset +
7547 (kCompilerHintsSize - 1) -
7548 ((kExtendedModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
7549 static const int kNativeByteOffset = kCompilerHintsOffset +
7550 (kCompilerHintsSize - 1) -
7551 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
7553 #error Unknown byte ordering
7557 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
7561 class JSGeneratorObject: public JSObject {
7563 // [function]: The function corresponding to this generator object.
7564 DECL_ACCESSORS(function, JSFunction)
7566 // [context]: The context of the suspended computation.
7567 DECL_ACCESSORS(context, Context)
7569 // [receiver]: The receiver of the suspended computation.
7570 DECL_ACCESSORS(receiver, Object)
7572 // [continuation]: Offset into code of continuation.
7574 // A positive offset indicates a suspended generator. The special
7575 // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
7576 // cannot be resumed.
7577 inline int continuation();
7578 inline void set_continuation(int continuation);
7580 // [operand_stack]: Saved operand stack.
7581 DECL_ACCESSORS(operand_stack, FixedArray)
7583 // [stack_handler_index]: Index of first stack handler in operand_stack, or -1
7584 // if the captured activation had no stack handler.
7585 inline int stack_handler_index();
7586 inline void set_stack_handler_index(int stack_handler_index);
7589 static inline JSGeneratorObject* cast(Object* obj);
7591 // Dispatched behavior.
7592 DECLARE_PRINTER(JSGeneratorObject)
7593 DECLARE_VERIFIER(JSGeneratorObject)
7595 // Magic sentinel values for the continuation.
7596 static const int kGeneratorExecuting = -1;
7597 static const int kGeneratorClosed = 0;
7599 // Layout description.
7600 static const int kFunctionOffset = JSObject::kHeaderSize;
7601 static const int kContextOffset = kFunctionOffset + kPointerSize;
7602 static const int kReceiverOffset = kContextOffset + kPointerSize;
7603 static const int kContinuationOffset = kReceiverOffset + kPointerSize;
7604 static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
7605 static const int kStackHandlerIndexOffset =
7606 kOperandStackOffset + kPointerSize;
7607 static const int kSize = kStackHandlerIndexOffset + kPointerSize;
7609 // Resume mode, for use by runtime functions.
7610 enum ResumeMode { NEXT, THROW };
7612 // Yielding from a generator returns an object with the following inobject
7613 // properties. See Context::generator_result_map() for the map.
7614 static const int kResultValuePropertyIndex = 0;
7615 static const int kResultDonePropertyIndex = 1;
7616 static const int kResultPropertyCount = 2;
7618 static const int kResultValuePropertyOffset = JSObject::kHeaderSize;
7619 static const int kResultDonePropertyOffset =
7620 kResultValuePropertyOffset + kPointerSize;
7621 static const int kResultSize = kResultDonePropertyOffset + kPointerSize;
7624 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
7628 // Representation for module instance objects.
7629 class JSModule: public JSObject {
7631 // [context]: the context holding the module's locals, or undefined if none.
7632 DECL_ACCESSORS(context, Object)
7634 // [scope_info]: Scope info.
7635 DECL_ACCESSORS(scope_info, ScopeInfo)
7638 static inline JSModule* cast(Object* obj);
7640 // Dispatched behavior.
7641 DECLARE_PRINTER(JSModule)
7642 DECLARE_VERIFIER(JSModule)
7644 // Layout description.
7645 static const int kContextOffset = JSObject::kHeaderSize;
7646 static const int kScopeInfoOffset = kContextOffset + kPointerSize;
7647 static const int kSize = kScopeInfoOffset + kPointerSize;
7650 DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
7654 // JSFunction describes JavaScript functions.
7655 class JSFunction: public JSObject {
7657 // [prototype_or_initial_map]:
7658 DECL_ACCESSORS(prototype_or_initial_map, Object)
7660 // [shared]: The information about the function that
7661 // can be shared by instances.
7662 DECL_ACCESSORS(shared, SharedFunctionInfo)
7664 // [context]: The context for this function.
7665 inline Context* context();
7666 inline void set_context(Object* context);
7668 // [code]: The generated code object for this function. Executed
7669 // when the function is invoked, e.g. foo() or new foo(). See
7670 // [[Call]] and [[Construct]] description in ECMA-262, section
7672 inline Code* code();
7673 inline void set_code(Code* code);
7674 inline void set_code_no_write_barrier(Code* code);
7675 inline void ReplaceCode(Code* code);
7677 // Tells whether this function is builtin.
7678 inline bool IsBuiltin();
7680 // Tells whether or not the function needs arguments adaption.
7681 inline bool NeedsArgumentsAdaption();
7683 // Tells whether or not this function has been optimized.
7684 inline bool IsOptimized();
7686 // Tells whether or not this function can be optimized.
7687 inline bool IsOptimizable();
7689 // Mark this function for lazy recompilation. The function will be
7690 // recompiled the next time it is executed.
7691 void MarkForOptimization();
7692 void MarkForConcurrentOptimization();
7693 void MarkInOptimizationQueue();
7695 static bool CompileOptimized(Handle<JSFunction> function,
7696 ClearExceptionFlag flag);
7698 // Tells whether or not the function is already marked for lazy
7700 inline bool IsMarkedForOptimization();
7701 inline bool IsMarkedForConcurrentOptimization();
7703 // Tells whether or not the function is on the concurrent recompilation queue.
7704 inline bool IsInOptimizationQueue();
7706 // [literals_or_bindings]: Fixed array holding either
7707 // the materialized literals or the bindings of a bound function.
7709 // If the function contains object, regexp or array literals, the
7710 // literals array prefix contains the object, regexp, and array
7711 // function to be used when creating these literals. This is
7712 // necessary so that we do not dynamically lookup the object, regexp
7713 // or array functions. Performing a dynamic lookup, we might end up
7714 // using the functions from a new context that we should not have
7717 // On bound functions, the array is a (copy-on-write) fixed-array containing
7718 // the function that was bound, bound this-value and any bound
7719 // arguments. Bound functions never contain literals.
7720 DECL_ACCESSORS(literals_or_bindings, FixedArray)
7722 inline FixedArray* literals();
7723 inline void set_literals(FixedArray* literals);
7725 inline FixedArray* function_bindings();
7726 inline void set_function_bindings(FixedArray* bindings);
7728 // The initial map for an object created by this constructor.
7729 inline Map* initial_map();
7730 inline void set_initial_map(Map* value);
7731 inline bool has_initial_map();
7732 static void EnsureHasInitialMap(Handle<JSFunction> function);
7734 // Get and set the prototype property on a JSFunction. If the
7735 // function has an initial map the prototype is set on the initial
7736 // map. Otherwise, the prototype is put in the initial map field
7737 // until an initial map is needed.
7738 inline bool has_prototype();
7739 inline bool has_instance_prototype();
7740 inline Object* prototype();
7741 inline Object* instance_prototype();
7742 static void SetPrototype(Handle<JSFunction> function,
7743 Handle<Object> value);
7744 static void SetInstancePrototype(Handle<JSFunction> function,
7745 Handle<Object> value);
7747 // After prototype is removed, it will not be created when accessed, and
7748 // [[Construct]] from this function will not be allowed.
7749 void RemovePrototype();
7750 inline bool should_have_prototype();
7752 // Accessor for this function's initial map's [[class]]
7753 // property. This is primarily used by ECMA native functions. This
7754 // method sets the class_name field of this function's initial map
7755 // to a given value. It creates an initial map if this function does
7756 // not have one. Note that this method does not copy the initial map
7757 // if it has one already, but simply replaces it with the new value.
7758 // Instances created afterwards will have a map whose [[class]] is
7759 // set to 'value', but there is no guarantees on instances created
7761 void SetInstanceClassName(String* name);
7763 // Returns if this function has been compiled to native code yet.
7764 inline bool is_compiled();
7766 // [next_function_link]: Links functions into various lists, e.g. the list
7767 // of optimized functions hanging off the native_context. The CodeFlusher
7768 // uses this link to chain together flushing candidates. Treated weakly
7769 // by the garbage collector.
7770 DECL_ACCESSORS(next_function_link, Object)
7772 // Prints the name of the function using PrintF.
7773 void PrintName(FILE* out = stdout);
7776 static inline JSFunction* cast(Object* obj);
7778 // Iterates the objects, including code objects indirectly referenced
7779 // through pointers to the first instruction in the code object.
7780 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
7782 // Dispatched behavior.
7783 DECLARE_PRINTER(JSFunction)
7784 DECLARE_VERIFIER(JSFunction)
7786 // Returns the number of allocated literals.
7787 inline int NumberOfLiterals();
7789 // Retrieve the native context from a function's literal array.
7790 static Context* NativeContextFromLiterals(FixedArray* literals);
7792 // Used for flags such as --hydrogen-filter.
7793 bool PassesFilter(const char* raw_filter);
7795 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
7796 // kSize) is weak and has special handling during garbage collection.
7797 static const int kCodeEntryOffset = JSObject::kHeaderSize;
7798 static const int kPrototypeOrInitialMapOffset =
7799 kCodeEntryOffset + kPointerSize;
7800 static const int kSharedFunctionInfoOffset =
7801 kPrototypeOrInitialMapOffset + kPointerSize;
7802 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
7803 static const int kLiteralsOffset = kContextOffset + kPointerSize;
7804 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
7805 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
7806 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
7808 // Layout of the literals array.
7809 static const int kLiteralsPrefixSize = 1;
7810 static const int kLiteralNativeContextIndex = 0;
7812 // Layout of the bound-function binding array.
7813 static const int kBoundFunctionIndex = 0;
7814 static const int kBoundThisIndex = 1;
7815 static const int kBoundArgumentsStartIndex = 2;
7818 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7822 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7823 // and the prototype is hidden. JSGlobalProxy always delegates
7824 // property accesses to its prototype if the prototype is not null.
7826 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7828 // Accessing a JSGlobalProxy requires security check.
7830 class JSGlobalProxy : public JSObject {
7832 // [native_context]: the owner native context of this global proxy object.
7833 // It is null value if this object is not used by any context.
7834 DECL_ACCESSORS(native_context, Object)
7837 static inline JSGlobalProxy* cast(Object* obj);
7839 inline bool IsDetachedFrom(GlobalObject* global);
7841 // Dispatched behavior.
7842 DECLARE_PRINTER(JSGlobalProxy)
7843 DECLARE_VERIFIER(JSGlobalProxy)
7845 // Layout description.
7846 static const int kNativeContextOffset = JSObject::kHeaderSize;
7847 static const int kSize = kNativeContextOffset + kPointerSize;
7850 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7854 // Forward declaration.
7855 class JSBuiltinsObject;
7857 // Common super class for JavaScript global objects and the special
7858 // builtins global objects.
7859 class GlobalObject: public JSObject {
7861 // [builtins]: the object holding the runtime routines written in JS.
7862 DECL_ACCESSORS(builtins, JSBuiltinsObject)
7864 // [native context]: the natives corresponding to this global object.
7865 DECL_ACCESSORS(native_context, Context)
7867 // [global context]: the most recent (i.e. innermost) global context.
7868 DECL_ACCESSORS(global_context, Context)
7870 // [global receiver]: the global receiver object of the context
7871 DECL_ACCESSORS(global_receiver, JSObject)
7873 // Retrieve the property cell used to store a property.
7874 PropertyCell* GetPropertyCell(LookupResult* result);
7876 // This is like GetProperty, but is used when you know the lookup won't fail
7877 // by throwing an exception. This is for the debug and builtins global
7878 // objects, where it is known which properties can be expected to be present
7880 Object* GetPropertyNoExceptionThrown(Name* key) {
7881 Object* answer = GetProperty(key)->ToObjectUnchecked();
7886 static inline GlobalObject* cast(Object* obj);
7888 // Layout description.
7889 static const int kBuiltinsOffset = JSObject::kHeaderSize;
7890 static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7891 static const int kGlobalContextOffset = kNativeContextOffset + kPointerSize;
7892 static const int kGlobalReceiverOffset = kGlobalContextOffset + kPointerSize;
7893 static const int kHeaderSize = kGlobalReceiverOffset + kPointerSize;
7896 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7900 // JavaScript global object.
7901 class JSGlobalObject: public GlobalObject {
7904 static inline JSGlobalObject* cast(Object* obj);
7906 // Ensure that the global object has a cell for the given property name.
7907 static Handle<PropertyCell> EnsurePropertyCell(Handle<JSGlobalObject> global,
7910 inline bool IsDetached();
7912 // Dispatched behavior.
7913 DECLARE_PRINTER(JSGlobalObject)
7914 DECLARE_VERIFIER(JSGlobalObject)
7916 // Layout description.
7917 static const int kSize = GlobalObject::kHeaderSize;
7920 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7924 // Builtins global object which holds the runtime routines written in
7926 class JSBuiltinsObject: public GlobalObject {
7928 // Accessors for the runtime routines written in JavaScript.
7929 inline Object* javascript_builtin(Builtins::JavaScript id);
7930 inline void set_javascript_builtin(Builtins::JavaScript id, Object* value);
7932 // Accessors for code of the runtime routines written in JavaScript.
7933 inline Code* javascript_builtin_code(Builtins::JavaScript id);
7934 inline void set_javascript_builtin_code(Builtins::JavaScript id, Code* value);
7937 static inline JSBuiltinsObject* cast(Object* obj);
7939 // Dispatched behavior.
7940 DECLARE_PRINTER(JSBuiltinsObject)
7941 DECLARE_VERIFIER(JSBuiltinsObject)
7943 // Layout description. The size of the builtins object includes
7944 // room for two pointers per runtime routine written in javascript
7945 // (function and code object).
7946 static const int kJSBuiltinsCount = Builtins::id_count;
7947 static const int kJSBuiltinsOffset = GlobalObject::kHeaderSize;
7948 static const int kJSBuiltinsCodeOffset =
7949 GlobalObject::kHeaderSize + (kJSBuiltinsCount * kPointerSize);
7950 static const int kSize =
7951 kJSBuiltinsCodeOffset + (kJSBuiltinsCount * kPointerSize);
7953 static int OffsetOfFunctionWithId(Builtins::JavaScript id) {
7954 return kJSBuiltinsOffset + id * kPointerSize;
7957 static int OffsetOfCodeWithId(Builtins::JavaScript id) {
7958 return kJSBuiltinsCodeOffset + id * kPointerSize;
7962 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7966 // Representation for JS Wrapper objects, String, Number, Float32x4, Int32x4,
7968 class JSValue: public JSObject {
7970 // [value]: the object being wrapped.
7971 DECL_ACCESSORS(value, Object)
7974 static inline JSValue* cast(Object* obj);
7976 // Dispatched behavior.
7977 DECLARE_PRINTER(JSValue)
7978 DECLARE_VERIFIER(JSValue)
7980 // Layout description.
7981 static const int kValueOffset = JSObject::kHeaderSize;
7982 static const int kSize = kValueOffset + kPointerSize;
7985 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
7991 // Representation for JS date objects.
7992 class JSDate: public JSObject {
7994 // If one component is NaN, all of them are, indicating a NaN time value.
7995 // [value]: the time value.
7996 DECL_ACCESSORS(value, Object)
7997 // [year]: caches year. Either undefined, smi, or NaN.
7998 DECL_ACCESSORS(year, Object)
7999 // [month]: caches month. Either undefined, smi, or NaN.
8000 DECL_ACCESSORS(month, Object)
8001 // [day]: caches day. Either undefined, smi, or NaN.
8002 DECL_ACCESSORS(day, Object)
8003 // [weekday]: caches day of week. Either undefined, smi, or NaN.
8004 DECL_ACCESSORS(weekday, Object)
8005 // [hour]: caches hours. Either undefined, smi, or NaN.
8006 DECL_ACCESSORS(hour, Object)
8007 // [min]: caches minutes. Either undefined, smi, or NaN.
8008 DECL_ACCESSORS(min, Object)
8009 // [sec]: caches seconds. Either undefined, smi, or NaN.
8010 DECL_ACCESSORS(sec, Object)
8011 // [cache stamp]: sample of the date cache stamp at the
8012 // moment when local fields were cached.
8013 DECL_ACCESSORS(cache_stamp, Object)
8016 static inline JSDate* cast(Object* obj);
8018 // Returns the date field with the specified index.
8019 // See FieldIndex for the list of date fields.
8020 static Object* GetField(Object* date, Smi* index);
8022 void SetValue(Object* value, bool is_value_nan);
8025 // Dispatched behavior.
8026 DECLARE_PRINTER(JSDate)
8027 DECLARE_VERIFIER(JSDate)
8029 // The order is important. It must be kept in sync with date macros
8040 kFirstUncachedField,
8041 kMillisecond = kFirstUncachedField,
8045 kYearUTC = kFirstUTCField,
8058 // Layout description.
8059 static const int kValueOffset = JSObject::kHeaderSize;
8060 static const int kYearOffset = kValueOffset + kPointerSize;
8061 static const int kMonthOffset = kYearOffset + kPointerSize;
8062 static const int kDayOffset = kMonthOffset + kPointerSize;
8063 static const int kWeekdayOffset = kDayOffset + kPointerSize;
8064 static const int kHourOffset = kWeekdayOffset + kPointerSize;
8065 static const int kMinOffset = kHourOffset + kPointerSize;
8066 static const int kSecOffset = kMinOffset + kPointerSize;
8067 static const int kCacheStampOffset = kSecOffset + kPointerSize;
8068 static const int kSize = kCacheStampOffset + kPointerSize;
8071 inline Object* DoGetField(FieldIndex index);
8073 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
8075 // Computes and caches the cacheable fields of the date.
8076 inline void SetLocalFields(int64_t local_time_ms, DateCache* date_cache);
8079 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
8083 // Representation of message objects used for error reporting through
8084 // the API. The messages are formatted in JavaScript so this object is
8085 // a real JavaScript object. The information used for formatting the
8086 // error messages are not directly accessible from JavaScript to
8087 // prevent leaking information to user code called during error
8089 class JSMessageObject: public JSObject {
8091 // [type]: the type of error message.
8092 DECL_ACCESSORS(type, String)
8094 // [arguments]: the arguments for formatting the error message.
8095 DECL_ACCESSORS(arguments, JSArray)
8097 // [script]: the script from which the error message originated.
8098 DECL_ACCESSORS(script, Object)
8100 // [stack_trace]: the stack trace for this error message.
8101 DECL_ACCESSORS(stack_trace, Object)
8103 // [stack_frames]: an array of stack frames for this error object.
8104 DECL_ACCESSORS(stack_frames, Object)
8106 // [start_position]: the start position in the script for the error message.
8107 inline int start_position();
8108 inline void set_start_position(int value);
8110 // [end_position]: the end position in the script for the error message.
8111 inline int end_position();
8112 inline void set_end_position(int value);
8115 static inline JSMessageObject* cast(Object* obj);
8117 // Dispatched behavior.
8118 DECLARE_PRINTER(JSMessageObject)
8119 DECLARE_VERIFIER(JSMessageObject)
8121 // Layout description.
8122 static const int kTypeOffset = JSObject::kHeaderSize;
8123 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
8124 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
8125 static const int kStackTraceOffset = kScriptOffset + kPointerSize;
8126 static const int kStackFramesOffset = kStackTraceOffset + kPointerSize;
8127 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
8128 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
8129 static const int kSize = kEndPositionOffset + kPointerSize;
8131 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
8132 kStackFramesOffset + kPointerSize,
8133 kSize> BodyDescriptor;
8137 // Regular expressions
8138 // The regular expression holds a single reference to a FixedArray in
8139 // the kDataOffset field.
8140 // The FixedArray contains the following data:
8141 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
8142 // - reference to the original source string
8143 // - reference to the original flag string
8144 // If it is an atom regexp
8145 // - a reference to a literal string to search for
8146 // If it is an irregexp regexp:
8147 // - a reference to code for ASCII inputs (bytecode or compiled), or a smi
8148 // used for tracking the last usage (used for code flushing).
8149 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
8150 // used for tracking the last usage (used for code flushing)..
8151 // - max number of registers used by irregexp implementations.
8152 // - number of capture registers (output values) of the regexp.
8153 class JSRegExp: public JSObject {
8156 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
8157 // ATOM: A simple string to match against using an indexOf operation.
8158 // IRREGEXP: Compiled with Irregexp.
8159 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
8160 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
8161 enum Flag { NONE = 0, GLOBAL = 1, IGNORE_CASE = 2, MULTILINE = 4 };
8165 explicit Flags(uint32_t value) : value_(value) { }
8166 bool is_global() { return (value_ & GLOBAL) != 0; }
8167 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
8168 bool is_multiline() { return (value_ & MULTILINE) != 0; }
8169 uint32_t value() { return value_; }
8174 DECL_ACCESSORS(data, Object)
8176 inline Type TypeTag();
8177 inline int CaptureCount();
8178 inline Flags GetFlags();
8179 inline String* Pattern();
8180 inline Object* DataAt(int index);
8181 // Set implementation data after the object has been prepared.
8182 inline void SetDataAt(int index, Object* value);
8184 static int code_index(bool is_ascii) {
8186 return kIrregexpASCIICodeIndex;
8188 return kIrregexpUC16CodeIndex;
8192 static int saved_code_index(bool is_ascii) {
8194 return kIrregexpASCIICodeSavedIndex;
8196 return kIrregexpUC16CodeSavedIndex;
8200 static inline JSRegExp* cast(Object* obj);
8202 // Dispatched behavior.
8203 DECLARE_VERIFIER(JSRegExp)
8205 static const int kDataOffset = JSObject::kHeaderSize;
8206 static const int kSize = kDataOffset + kPointerSize;
8208 // Indices in the data array.
8209 static const int kTagIndex = 0;
8210 static const int kSourceIndex = kTagIndex + 1;
8211 static const int kFlagsIndex = kSourceIndex + 1;
8212 static const int kDataIndex = kFlagsIndex + 1;
8213 // The data fields are used in different ways depending on the
8214 // value of the tag.
8215 // Atom regexps (literal strings).
8216 static const int kAtomPatternIndex = kDataIndex;
8218 static const int kAtomDataSize = kAtomPatternIndex + 1;
8220 // Irregexp compiled code or bytecode for ASCII. If compilation
8221 // fails, this fields hold an exception object that should be
8222 // thrown if the regexp is used again.
8223 static const int kIrregexpASCIICodeIndex = kDataIndex;
8224 // Irregexp compiled code or bytecode for UC16. If compilation
8225 // fails, this fields hold an exception object that should be
8226 // thrown if the regexp is used again.
8227 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
8229 // Saved instance of Irregexp compiled code or bytecode for ASCII that
8230 // is a potential candidate for flushing.
8231 static const int kIrregexpASCIICodeSavedIndex = kDataIndex + 2;
8232 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
8233 // a potential candidate for flushing.
8234 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
8236 // Maximal number of registers used by either ASCII or UC16.
8237 // Only used to check that there is enough stack space
8238 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
8239 // Number of captures in the compiled regexp.
8240 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
8242 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
8244 // Offsets directly into the data fixed array.
8245 static const int kDataTagOffset =
8246 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
8247 static const int kDataAsciiCodeOffset =
8248 FixedArray::kHeaderSize + kIrregexpASCIICodeIndex * kPointerSize;
8249 static const int kDataUC16CodeOffset =
8250 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
8251 static const int kIrregexpCaptureCountOffset =
8252 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
8254 // In-object fields.
8255 static const int kSourceFieldIndex = 0;
8256 static const int kGlobalFieldIndex = 1;
8257 static const int kIgnoreCaseFieldIndex = 2;
8258 static const int kMultilineFieldIndex = 3;
8259 static const int kLastIndexFieldIndex = 4;
8260 static const int kInObjectFieldCount = 5;
8262 // The uninitialized value for a regexp code object.
8263 static const int kUninitializedValue = -1;
8265 // The compilation error value for the regexp code object. The real error
8266 // object is in the saved code field.
8267 static const int kCompilationErrorValue = -2;
8269 // When we store the sweep generation at which we moved the code from the
8270 // code index to the saved code index we mask it of to be in the [0:255]
8272 static const int kCodeAgeMask = 0xff;
8276 class CompilationCacheShape : public BaseShape<HashTableKey*> {
8278 static inline bool IsMatch(HashTableKey* key, Object* value) {
8279 return key->IsMatch(value);
8282 static inline uint32_t Hash(HashTableKey* key) {
8286 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
8287 return key->HashForObject(object);
8290 MUST_USE_RESULT static MaybeObject* AsObject(Heap* heap,
8291 HashTableKey* key) {
8292 return key->AsObject(heap);
8295 static const int kPrefixSize = 0;
8296 static const int kEntrySize = 2;
8300 class CompilationCacheTable: public HashTable<CompilationCacheShape,
8303 // Find cached value for a string key, otherwise return null.
8304 Object* Lookup(String* src, Context* context);
8305 Object* LookupEval(String* src,
8307 LanguageMode language_mode,
8308 int scope_position);
8309 Object* LookupRegExp(String* source, JSRegExp::Flags flags);
8310 MUST_USE_RESULT MaybeObject* Put(String* src,
8313 MUST_USE_RESULT MaybeObject* PutEval(String* src,
8315 SharedFunctionInfo* value,
8316 int scope_position);
8317 MUST_USE_RESULT MaybeObject* PutRegExp(String* src,
8318 JSRegExp::Flags flags,
8321 // Remove given value from cache.
8322 void Remove(Object* value);
8324 static inline CompilationCacheTable* cast(Object* obj);
8327 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
8331 class CodeCache: public Struct {
8333 DECL_ACCESSORS(default_cache, FixedArray)
8334 DECL_ACCESSORS(normal_type_cache, Object)
8336 // Add the code object to the cache.
8337 MUST_USE_RESULT MaybeObject* Update(Name* name, Code* code);
8339 // Lookup code object in the cache. Returns code object if found and undefined
8341 Object* Lookup(Name* name, Code::Flags flags);
8343 // Get the internal index of a code object in the cache. Returns -1 if the
8344 // code object is not in that cache. This index can be used to later call
8345 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
8347 int GetIndex(Object* name, Code* code);
8349 // Remove an object from the cache with the provided internal index.
8350 void RemoveByIndex(Object* name, Code* code, int index);
8352 static inline CodeCache* cast(Object* obj);
8354 // Dispatched behavior.
8355 DECLARE_PRINTER(CodeCache)
8356 DECLARE_VERIFIER(CodeCache)
8358 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
8359 static const int kNormalTypeCacheOffset =
8360 kDefaultCacheOffset + kPointerSize;
8361 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
8364 MUST_USE_RESULT MaybeObject* UpdateDefaultCache(Name* name, Code* code);
8365 MUST_USE_RESULT MaybeObject* UpdateNormalTypeCache(Name* name, Code* code);
8366 Object* LookupDefaultCache(Name* name, Code::Flags flags);
8367 Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
8369 // Code cache layout of the default cache. Elements are alternating name and
8370 // code objects for non normal load/store/call IC's.
8371 static const int kCodeCacheEntrySize = 2;
8372 static const int kCodeCacheEntryNameOffset = 0;
8373 static const int kCodeCacheEntryCodeOffset = 1;
8375 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
8379 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
8381 static inline bool IsMatch(HashTableKey* key, Object* value) {
8382 return key->IsMatch(value);
8385 static inline uint32_t Hash(HashTableKey* key) {
8389 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
8390 return key->HashForObject(object);
8393 MUST_USE_RESULT static MaybeObject* AsObject(Heap* heap,
8394 HashTableKey* key) {
8395 return key->AsObject(heap);
8398 static const int kPrefixSize = 0;
8399 static const int kEntrySize = 2;
8403 class CodeCacheHashTable: public HashTable<CodeCacheHashTableShape,
8406 Object* Lookup(Name* name, Code::Flags flags);
8407 MUST_USE_RESULT MaybeObject* Put(Name* name, Code* code);
8409 int GetIndex(Name* name, Code::Flags flags);
8410 void RemoveByIndex(int index);
8412 static inline CodeCacheHashTable* cast(Object* obj);
8414 // Initial size of the fixed array backing the hash table.
8415 static const int kInitialSize = 64;
8418 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
8422 class PolymorphicCodeCache: public Struct {
8424 DECL_ACCESSORS(cache, Object)
8426 static void Update(Handle<PolymorphicCodeCache> cache,
8427 MapHandleList* maps,
8431 MUST_USE_RESULT MaybeObject* Update(MapHandleList* maps,
8435 // Returns an undefined value if the entry is not found.
8436 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
8438 static inline PolymorphicCodeCache* cast(Object* obj);
8440 // Dispatched behavior.
8441 DECLARE_PRINTER(PolymorphicCodeCache)
8442 DECLARE_VERIFIER(PolymorphicCodeCache)
8444 static const int kCacheOffset = HeapObject::kHeaderSize;
8445 static const int kSize = kCacheOffset + kPointerSize;
8448 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
8452 class PolymorphicCodeCacheHashTable
8453 : public HashTable<CodeCacheHashTableShape, HashTableKey*> {
8455 Object* Lookup(MapHandleList* maps, int code_kind);
8457 MUST_USE_RESULT MaybeObject* Put(MapHandleList* maps,
8461 static inline PolymorphicCodeCacheHashTable* cast(Object* obj);
8463 static const int kInitialSize = 64;
8465 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
8469 class TypeFeedbackInfo: public Struct {
8471 inline int ic_total_count();
8472 inline void set_ic_total_count(int count);
8474 inline int ic_with_type_info_count();
8475 inline void change_ic_with_type_info_count(int count);
8477 inline void initialize_storage();
8479 inline void change_own_type_change_checksum();
8480 inline int own_type_change_checksum();
8482 inline void set_inlined_type_change_checksum(int checksum);
8483 inline bool matches_inlined_type_change_checksum(int checksum);
8485 DECL_ACCESSORS(type_feedback_cells, TypeFeedbackCells)
8487 static inline TypeFeedbackInfo* cast(Object* obj);
8489 // Dispatched behavior.
8490 DECLARE_PRINTER(TypeFeedbackInfo)
8491 DECLARE_VERIFIER(TypeFeedbackInfo)
8493 static const int kStorage1Offset = HeapObject::kHeaderSize;
8494 static const int kStorage2Offset = kStorage1Offset + kPointerSize;
8495 static const int kTypeFeedbackCellsOffset = kStorage2Offset + kPointerSize;
8496 static const int kSize = kTypeFeedbackCellsOffset + kPointerSize;
8499 static const int kTypeChangeChecksumBits = 7;
8501 class ICTotalCountField: public BitField<int, 0,
8502 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
8503 class OwnTypeChangeChecksum: public BitField<int,
8504 kSmiValueSize - kTypeChangeChecksumBits,
8505 kTypeChangeChecksumBits> {}; // NOLINT
8506 class ICsWithTypeInfoCountField: public BitField<int, 0,
8507 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
8508 class InlinedTypeChangeChecksum: public BitField<int,
8509 kSmiValueSize - kTypeChangeChecksumBits,
8510 kTypeChangeChecksumBits> {}; // NOLINT
8512 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
8516 enum AllocationSiteMode {
8517 DONT_TRACK_ALLOCATION_SITE,
8518 TRACK_ALLOCATION_SITE,
8519 LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
8523 class AllocationSite: public Struct {
8525 static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
8526 static const double kPretenureRatio;
8527 static const int kPretenureMinimumCreated = 100;
8529 // Values for pretenure decision field.
8530 enum PretenureDecision {
8535 kLastPretenureDecisionValue = kZombie
8538 DECL_ACCESSORS(transition_info, Object)
8539 // nested_site threads a list of sites that represent nested literals
8540 // walked in a particular order. So [[1, 2], 1, 2] will have one
8541 // nested_site, but [[1, 2], 3, [4]] will have a list of two.
8542 DECL_ACCESSORS(nested_site, Object)
8543 DECL_ACCESSORS(pretenure_data, Smi)
8544 DECL_ACCESSORS(pretenure_create_count, Smi)
8545 DECL_ACCESSORS(dependent_code, DependentCode)
8546 DECL_ACCESSORS(weak_next, Object)
8548 inline void Initialize();
8550 // This method is expensive, it should only be called for reporting.
8551 bool IsNestedSite();
8553 // transition_info bitfields, for constructed array transition info.
8554 class ElementsKindBits: public BitField<ElementsKind, 0, 15> {};
8555 class UnusedBits: public BitField<int, 15, 14> {};
8556 class DoNotInlineBit: public BitField<bool, 29, 1> {};
8558 // Bitfields for pretenure_data
8559 class MementoFoundCountBits: public BitField<int, 0, 28> {};
8560 class PretenureDecisionBits: public BitField<PretenureDecision, 28, 2> {};
8561 STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
8563 // Increments the mementos found counter and returns true when the first
8564 // memento was found for a given allocation site.
8565 inline bool IncrementMementoFoundCount();
8567 inline void IncrementMementoCreateCount();
8569 PretenureFlag GetPretenureMode();
8571 void ResetPretenureDecision();
8573 PretenureDecision pretenure_decision() {
8574 int value = pretenure_data()->value();
8575 return PretenureDecisionBits::decode(value);
8578 void set_pretenure_decision(PretenureDecision decision) {
8579 int value = pretenure_data()->value();
8581 Smi::FromInt(PretenureDecisionBits::update(value, decision)),
8582 SKIP_WRITE_BARRIER);
8585 int memento_found_count() {
8586 int value = pretenure_data()->value();
8587 return MementoFoundCountBits::decode(value);
8590 inline void set_memento_found_count(int count);
8592 int memento_create_count() {
8593 return pretenure_create_count()->value();
8596 void set_memento_create_count(int count) {
8597 set_pretenure_create_count(Smi::FromInt(count), SKIP_WRITE_BARRIER);
8600 // The pretenuring decision is made during gc, and the zombie state allows
8601 // us to recognize when an allocation site is just being kept alive because
8602 // a later traversal of new space may discover AllocationMementos that point
8603 // to this AllocationSite.
8605 return pretenure_decision() == kZombie;
8608 inline void MarkZombie();
8610 inline bool DigestPretenuringFeedback();
8612 ElementsKind GetElementsKind() {
8613 ASSERT(!SitePointsToLiteral());
8614 int value = Smi::cast(transition_info())->value();
8615 return ElementsKindBits::decode(value);
8618 void SetElementsKind(ElementsKind kind) {
8619 int value = Smi::cast(transition_info())->value();
8620 set_transition_info(Smi::FromInt(ElementsKindBits::update(value, kind)),
8621 SKIP_WRITE_BARRIER);
8624 bool CanInlineCall() {
8625 int value = Smi::cast(transition_info())->value();
8626 return DoNotInlineBit::decode(value) == 0;
8629 void SetDoNotInlineCall() {
8630 int value = Smi::cast(transition_info())->value();
8631 set_transition_info(Smi::FromInt(DoNotInlineBit::update(value, true)),
8632 SKIP_WRITE_BARRIER);
8635 bool SitePointsToLiteral() {
8636 // If transition_info is a smi, then it represents an ElementsKind
8637 // for a constructed array. Otherwise, it must be a boilerplate
8638 // for an object or array literal.
8639 return transition_info()->IsJSArray() || transition_info()->IsJSObject();
8642 MaybeObject* DigestTransitionFeedback(ElementsKind to_kind);
8649 static void AddDependentCompilationInfo(Handle<AllocationSite> site,
8651 CompilationInfo* info);
8653 DECLARE_PRINTER(AllocationSite)
8654 DECLARE_VERIFIER(AllocationSite)
8656 static inline AllocationSite* cast(Object* obj);
8657 static inline AllocationSiteMode GetMode(
8658 ElementsKind boilerplate_elements_kind);
8659 static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
8660 static inline bool CanTrack(InstanceType type);
8662 static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
8663 static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
8664 static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
8665 static const int kPretenureCreateCountOffset =
8666 kPretenureDataOffset + kPointerSize;
8667 static const int kDependentCodeOffset =
8668 kPretenureCreateCountOffset + kPointerSize;
8669 static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
8670 static const int kSize = kWeakNextOffset + kPointerSize;
8672 // During mark compact we need to take special care for the dependent code
8674 static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
8675 static const int kPointerFieldsEndOffset = kDependentCodeOffset;
8677 // For other visitors, use the fixed body descriptor below.
8678 typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
8679 kDependentCodeOffset + kPointerSize,
8680 kSize> BodyDescriptor;
8683 inline DependentCode::DependencyGroup ToDependencyGroup(Reason reason);
8684 bool PretenuringDecisionMade() {
8685 return pretenure_decision() != kUndecided;
8688 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
8692 class AllocationMemento: public Struct {
8694 static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
8695 static const int kSize = kAllocationSiteOffset + kPointerSize;
8697 DECL_ACCESSORS(allocation_site, Object)
8700 return allocation_site()->IsAllocationSite() &&
8701 !AllocationSite::cast(allocation_site())->IsZombie();
8703 AllocationSite* GetAllocationSite() {
8705 return AllocationSite::cast(allocation_site());
8708 DECLARE_PRINTER(AllocationMemento)
8709 DECLARE_VERIFIER(AllocationMemento)
8711 static inline AllocationMemento* cast(Object* obj);
8714 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
8718 // Representation of a slow alias as part of a non-strict arguments objects.
8719 // For fast aliases (if HasNonStrictArgumentsElements()):
8720 // - the parameter map contains an index into the context
8721 // - all attributes of the element have default values
8722 // For slow aliases (if HasDictionaryArgumentsElements()):
8723 // - the parameter map contains no fast alias mapping (i.e. the hole)
8724 // - this struct (in the slow backing store) contains an index into the context
8725 // - all attributes are available as part if the property details
8726 class AliasedArgumentsEntry: public Struct {
8728 inline int aliased_context_slot();
8729 inline void set_aliased_context_slot(int count);
8731 static inline AliasedArgumentsEntry* cast(Object* obj);
8733 // Dispatched behavior.
8734 DECLARE_PRINTER(AliasedArgumentsEntry)
8735 DECLARE_VERIFIER(AliasedArgumentsEntry)
8737 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
8738 static const int kSize = kAliasedContextSlot + kPointerSize;
8741 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
8745 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
8746 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
8749 class StringHasher {
8751 explicit inline StringHasher(int length, uint32_t seed);
8753 template <typename schar>
8754 static inline uint32_t HashSequentialString(const schar* chars,
8758 // Reads all the data, even for long strings and computes the utf16 length.
8759 static uint32_t ComputeUtf8Hash(Vector<const char> chars,
8761 int* utf16_length_out);
8763 // Calculated hash value for a string consisting of 1 to
8764 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
8765 // value is represented decimal value.
8766 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
8768 // No string is allowed to have a hash of zero. That value is reserved
8769 // for internal properties. If the hash calculation yields zero then we
8771 static const int kZeroHash = 27;
8773 // Reusable parts of the hashing algorithm.
8774 INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
8775 INLINE(static uint32_t GetHashCore(uint32_t running_hash));
8778 // Returns the value to store in the hash field of a string with
8779 // the given length and contents.
8780 uint32_t GetHashField();
8781 // Returns true if the hash of this string can be computed without
8782 // looking at the contents.
8783 inline bool has_trivial_hash();
8784 // Adds a block of characters to the hash.
8785 template<typename Char>
8786 inline void AddCharacters(const Char* chars, int len);
8789 // Add a character to the hash.
8790 inline void AddCharacter(uint16_t c);
8791 // Update index. Returns true if string is still an index.
8792 inline bool UpdateIndex(uint16_t c);
8795 uint32_t raw_running_hash_;
8796 uint32_t array_index_;
8797 bool is_array_index_;
8798 bool is_first_char_;
8799 DISALLOW_COPY_AND_ASSIGN(StringHasher);
8803 // The characteristics of a string are stored in its map. Retrieving these
8804 // few bits of information is moderately expensive, involving two memory
8805 // loads where the second is dependent on the first. To improve efficiency
8806 // the shape of the string is given its own class so that it can be retrieved
8807 // once and used for several string operations. A StringShape is small enough
8808 // to be passed by value and is immutable, but be aware that flattening a
8809 // string can potentially alter its shape. Also be aware that a GC caused by
8810 // something else can alter the shape of a string due to ConsString
8811 // shortcutting. Keeping these restrictions in mind has proven to be error-
8812 // prone and so we no longer put StringShapes in variables unless there is a
8813 // concrete performance benefit at that particular point in the code.
8814 class StringShape BASE_EMBEDDED {
8816 inline explicit StringShape(String* s);
8817 inline explicit StringShape(Map* s);
8818 inline explicit StringShape(InstanceType t);
8819 inline bool IsSequential();
8820 inline bool IsExternal();
8821 inline bool IsCons();
8822 inline bool IsSliced();
8823 inline bool IsIndirect();
8824 inline bool IsExternalAscii();
8825 inline bool IsExternalTwoByte();
8826 inline bool IsSequentialAscii();
8827 inline bool IsSequentialTwoByte();
8828 inline bool IsInternalized();
8829 inline StringRepresentationTag representation_tag();
8830 inline uint32_t encoding_tag();
8831 inline uint32_t full_representation_tag();
8832 inline uint32_t size_tag();
8834 inline uint32_t type() { return type_; }
8835 inline void invalidate() { valid_ = false; }
8836 inline bool valid() { return valid_; }
8838 inline void invalidate() { }
8844 inline void set_valid() { valid_ = true; }
8847 inline void set_valid() { }
8852 // The Name abstract class captures anything that can be used as a property
8853 // name, i.e., strings and symbols. All names store a hash value.
8854 class Name: public HeapObject {
8856 // Get and set the hash field of the name.
8857 inline uint32_t hash_field();
8858 inline void set_hash_field(uint32_t value);
8860 // Tells whether the hash code has been computed.
8861 inline bool HasHashCode();
8863 // Returns a hash value used for the property table
8864 inline uint32_t Hash();
8866 // Equality operations.
8867 inline bool Equals(Name* other);
8870 inline bool AsArrayIndex(uint32_t* index);
8873 static inline Name* cast(Object* obj);
8875 bool IsCacheable(Isolate* isolate);
8877 DECLARE_PRINTER(Name)
8879 // Layout description.
8880 static const int kHashFieldOffset = HeapObject::kHeaderSize;
8881 static const int kSize = kHashFieldOffset + kPointerSize;
8883 // Mask constant for checking if a name has a computed hash code
8884 // and if it is a string that is an array index. The least significant bit
8885 // indicates whether a hash code has been computed. If the hash code has
8886 // been computed the 2nd bit tells whether the string can be used as an
8888 static const int kHashNotComputedMask = 1;
8889 static const int kIsNotArrayIndexMask = 1 << 1;
8890 static const int kNofHashBitFields = 2;
8892 // Shift constant retrieving hash code from hash field.
8893 static const int kHashShift = kNofHashBitFields;
8895 // Only these bits are relevant in the hash, since the top two are shifted
8897 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8899 // Array index strings this short can keep their index in the hash field.
8900 static const int kMaxCachedArrayIndexLength = 7;
8902 // For strings which are array indexes the hash value has the string length
8903 // mixed into the hash, mainly to avoid a hash value of zero which would be
8904 // the case for the string '0'. 24 bits are used for the array index value.
8905 static const int kArrayIndexValueBits = 24;
8906 static const int kArrayIndexLengthBits =
8907 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8909 STATIC_CHECK((kArrayIndexLengthBits > 0));
8911 static const int kArrayIndexHashLengthShift =
8912 kArrayIndexValueBits + kNofHashBitFields;
8914 static const int kArrayIndexHashMask = (1 << kArrayIndexHashLengthShift) - 1;
8916 static const int kArrayIndexValueMask =
8917 ((1 << kArrayIndexValueBits) - 1) << kHashShift;
8919 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8920 // could use a mask to test if the length of string is less than or equal to
8921 // kMaxCachedArrayIndexLength.
8922 STATIC_CHECK(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8924 static const int kContainsCachedArrayIndexMask =
8925 (~kMaxCachedArrayIndexLength << kArrayIndexHashLengthShift) |
8926 kIsNotArrayIndexMask;
8928 // Value of empty hash field indicating that the hash is not computed.
8929 static const int kEmptyHashField =
8930 kIsNotArrayIndexMask | kHashNotComputedMask;
8933 static inline bool IsHashFieldComputed(uint32_t field);
8936 DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8941 class Symbol: public Name {
8943 // [name]: the print name of a symbol, or undefined if none.
8944 DECL_ACCESSORS(name, Object)
8946 DECL_ACCESSORS(flags, Smi)
8948 // [is_private]: whether this is a private symbol.
8949 DECL_BOOLEAN_ACCESSORS(is_private)
8952 static inline Symbol* cast(Object* obj);
8954 // Dispatched behavior.
8955 DECLARE_PRINTER(Symbol)
8956 DECLARE_VERIFIER(Symbol)
8958 // Layout description.
8959 static const int kNameOffset = Name::kSize;
8960 static const int kFlagsOffset = kNameOffset + kPointerSize;
8961 static const int kSize = kFlagsOffset + kPointerSize;
8963 typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
8966 static const int kPrivateBit = 0;
8968 DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
8974 // The String abstract class captures JavaScript string values:
8977 // 4.3.16 String Value
8978 // A string value is a member of the type String and is a finite
8979 // ordered sequence of zero or more 16-bit unsigned integer values.
8981 // All string values have a length field.
8982 class String: public Name {
8984 enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
8986 // Representation of the flat content of a String.
8987 // A non-flat string doesn't have flat content.
8988 // A flat string has content that's encoded as a sequence of either
8989 // ASCII chars or two-byte UC16.
8990 // Returned by String::GetFlatContent().
8993 // Returns true if the string is flat and this structure contains content.
8994 bool IsFlat() { return state_ != NON_FLAT; }
8995 // Returns true if the structure contains ASCII content.
8996 bool IsAscii() { return state_ == ASCII; }
8997 // Returns true if the structure contains two-byte content.
8998 bool IsTwoByte() { return state_ == TWO_BYTE; }
9000 // Return the one byte content of the string. Only use if IsAscii() returns
9002 Vector<const uint8_t> ToOneByteVector() {
9003 ASSERT_EQ(ASCII, state_);
9006 // Return the two-byte content of the string. Only use if IsTwoByte()
9008 Vector<const uc16> ToUC16Vector() {
9009 ASSERT_EQ(TWO_BYTE, state_);
9010 return Vector<const uc16>::cast(buffer_);
9014 enum State { NON_FLAT, ASCII, TWO_BYTE };
9016 // Constructors only used by String::GetFlatContent().
9017 explicit FlatContent(Vector<const uint8_t> chars)
9020 explicit FlatContent(Vector<const uc16> chars)
9021 : buffer_(Vector<const byte>::cast(chars)),
9022 state_(TWO_BYTE) { }
9023 FlatContent() : buffer_(), state_(NON_FLAT) { }
9025 Vector<const uint8_t> buffer_;
9028 friend class String;
9031 // Get and set the length of the string.
9032 inline int length();
9033 inline void set_length(int value);
9035 // Returns whether this string has only ASCII chars, i.e. all of them can
9036 // be ASCII encoded. This might be the case even if the string is
9037 // two-byte. Such strings may appear when the embedder prefers
9038 // two-byte external representations even for ASCII data.
9039 inline bool IsOneByteRepresentation();
9040 inline bool IsTwoByteRepresentation();
9042 // Cons and slices have an encoding flag that may not represent the actual
9043 // encoding of the underlying string. This is taken into account here.
9044 // Requires: this->IsFlat()
9045 inline bool IsOneByteRepresentationUnderneath();
9046 inline bool IsTwoByteRepresentationUnderneath();
9048 // NOTE: this should be considered only a hint. False negatives are
9050 inline bool HasOnlyOneByteChars();
9052 // Get and set individual two byte chars in the string.
9053 inline void Set(int index, uint16_t value);
9054 // Get individual two byte char in the string. Repeated calls
9055 // to this method are not efficient unless the string is flat.
9056 INLINE(uint16_t Get(int index));
9058 // Try to flatten the string. Checks first inline to see if it is
9059 // necessary. Does nothing if the string is not a cons string.
9060 // Flattening allocates a sequential string with the same data as
9061 // the given string and mutates the cons string to a degenerate
9062 // form, where the first component is the new sequential string and
9063 // the second component is the empty string. If allocation fails,
9064 // this function returns a failure. If flattening succeeds, this
9065 // function returns the sequential string that is now the first
9066 // component of the cons string.
9068 // Degenerate cons strings are handled specially by the garbage
9069 // collector (see IsShortcutCandidate).
9071 // Use FlattenString from Handles.cc to flatten even in case an
9072 // allocation failure happens.
9073 inline MaybeObject* TryFlatten(PretenureFlag pretenure = NOT_TENURED);
9075 // Convenience function. Has exactly the same behavior as
9076 // TryFlatten(), except in the case of failure returns the original
9078 inline String* TryFlattenGetString(PretenureFlag pretenure = NOT_TENURED);
9080 // Tries to return the content of a flat string as a structure holding either
9081 // a flat vector of char or of uc16.
9082 // If the string isn't flat, and therefore doesn't have flat content, the
9083 // returned structure will report so, and can't provide a vector of either
9085 FlatContent GetFlatContent();
9087 // Returns the parent of a sliced string or first part of a flat cons string.
9088 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
9089 inline String* GetUnderlying();
9091 // Mark the string as an undetectable object. It only applies to
9092 // ASCII and two byte string types.
9093 bool MarkAsUndetectable();
9095 // String equality operations.
9096 inline bool Equals(String* other);
9097 bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
9098 bool IsOneByteEqualTo(Vector<const uint8_t> str);
9099 bool IsTwoByteEqualTo(Vector<const uc16> str);
9101 // Return a UTF8 representation of the string. The string is null
9102 // terminated but may optionally contain nulls. Length is returned
9103 // in length_output if length_output is not a null pointer The string
9104 // should be nearly flat, otherwise the performance of this method may
9105 // be very slow (quadratic in the length). Setting robustness_flag to
9106 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
9107 // handles unexpected data without causing assert failures and it does not
9108 // do any heap allocations. This is useful when printing stack traces.
9109 SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
9110 RobustnessFlag robustness_flag,
9113 int* length_output = 0);
9114 SmartArrayPointer<char> ToCString(
9115 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
9116 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
9117 int* length_output = 0);
9119 // Return a 16 bit Unicode representation of the string.
9120 // The string should be nearly flat, otherwise the performance of
9121 // of this method may be very bad. Setting robustness_flag to
9122 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
9123 // handles unexpected data without causing assert failures and it does not
9124 // do any heap allocations. This is useful when printing stack traces.
9125 SmartArrayPointer<uc16> ToWideCString(
9126 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
9128 bool ComputeArrayIndex(uint32_t* index);
9131 bool MakeExternal(v8::String::ExternalStringResource* resource);
9132 bool MakeExternal(v8::String::ExternalAsciiStringResource* resource);
9135 inline bool AsArrayIndex(uint32_t* index);
9138 static inline String* cast(Object* obj);
9140 void PrintOn(FILE* out);
9142 // For use during stack traces. Performs rudimentary sanity check.
9145 // Dispatched behavior.
9146 void StringShortPrint(StringStream* accumulator);
9148 char* ToAsciiArray();
9150 DECLARE_PRINTER(String)
9151 DECLARE_VERIFIER(String)
9153 inline bool IsFlat();
9155 // Layout description.
9156 static const int kLengthOffset = Name::kSize;
9157 static const int kSize = kLengthOffset + kPointerSize;
9159 // Maximum number of characters to consider when trying to convert a string
9160 // value into an array index.
9161 static const int kMaxArrayIndexSize = 10;
9162 STATIC_CHECK(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
9165 static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
9166 static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
9167 static const int kMaxUtf16CodeUnit = 0xffff;
9169 // Value of hash field containing computed hash equal to zero.
9170 static const int kEmptyStringHash = kIsNotArrayIndexMask;
9172 // Maximal string length.
9173 static const int kMaxLength = (1 << (32 - 2)) - 1;
9175 // Max length for computing hash. For strings longer than this limit the
9176 // string length is used as the hash value.
9177 static const int kMaxHashCalcLength = 16383;
9179 // Limit for truncation in short printing.
9180 static const int kMaxShortPrintLength = 1024;
9182 // Support for regular expressions.
9183 const uc16* GetTwoByteData(unsigned start);
9185 // Helper function for flattening strings.
9186 template <typename sinkchar>
9187 static void WriteToFlat(String* source,
9192 // The return value may point to the first aligned word containing the
9193 // first non-ascii character, rather than directly to the non-ascii character.
9194 // If the return value is >= the passed length, the entire string was ASCII.
9195 static inline int NonAsciiStart(const char* chars, int length) {
9196 const char* start = chars;
9197 const char* limit = chars + length;
9198 #ifdef V8_HOST_CAN_READ_UNALIGNED
9199 ASSERT(unibrow::Utf8::kMaxOneByteChar == 0x7F);
9200 const uintptr_t non_ascii_mask = kUintptrAllBitsSet / 0xFF * 0x80;
9201 while (chars + sizeof(uintptr_t) <= limit) {
9202 if (*reinterpret_cast<const uintptr_t*>(chars) & non_ascii_mask) {
9203 return static_cast<int>(chars - start);
9205 chars += sizeof(uintptr_t);
9208 while (chars < limit) {
9209 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
9210 return static_cast<int>(chars - start);
9214 return static_cast<int>(chars - start);
9217 static inline bool IsAscii(const char* chars, int length) {
9218 return NonAsciiStart(chars, length) >= length;
9221 static inline bool IsAscii(const uint8_t* chars, int length) {
9223 NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
9226 static inline int NonOneByteStart(const uc16* chars, int length) {
9227 const uc16* limit = chars + length;
9228 const uc16* start = chars;
9229 while (chars < limit) {
9230 if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
9233 return static_cast<int>(chars - start);
9236 static inline bool IsOneByte(const uc16* chars, int length) {
9237 return NonOneByteStart(chars, length) >= length;
9240 // TODO(dcarney): Replace all instances of this with VisitFlat.
9241 template<class Visitor, class ConsOp>
9242 static inline void Visit(String* string,
9249 template<class Visitor>
9250 static inline ConsString* VisitFlat(Visitor* visitor,
9256 template<class Visitor>
9257 static inline ConsString* VisitFlat(Visitor* visitor,
9260 int32_t type = string->map()->instance_type();
9261 return VisitFlat(visitor, string, offset, string->length(), type);
9267 // Try to flatten the top level ConsString that is hiding behind this
9268 // string. This is a no-op unless the string is a ConsString. Flatten
9269 // mutates the ConsString and might return a failure.
9270 MUST_USE_RESULT MaybeObject* SlowTryFlatten(PretenureFlag pretenure);
9272 // Slow case of String::Equals. This implementation works on any strings
9273 // but it is most efficient on strings that are almost flat.
9274 bool SlowEquals(String* other);
9276 // Slow case of AsArrayIndex.
9277 bool SlowAsArrayIndex(uint32_t* index);
9279 // Compute and set the hash code.
9280 uint32_t ComputeAndSetHash();
9282 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
9286 // The SeqString abstract class captures sequential string values.
9287 class SeqString: public String {
9290 static inline SeqString* cast(Object* obj);
9292 // Layout description.
9293 static const int kHeaderSize = String::kSize;
9295 // Truncate the string in-place if possible and return the result.
9296 // In case of new_length == 0, the empty string is returned without
9297 // truncating the original string.
9298 MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
9301 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
9305 // The AsciiString class captures sequential ASCII string objects.
9306 // Each character in the AsciiString is an ASCII character.
9307 class SeqOneByteString: public SeqString {
9309 static const bool kHasAsciiEncoding = true;
9311 // Dispatched behavior.
9312 inline uint16_t SeqOneByteStringGet(int index);
9313 inline void SeqOneByteStringSet(int index, uint16_t value);
9315 // Get the address of the characters in this string.
9316 inline Address GetCharsAddress();
9318 inline uint8_t* GetChars();
9321 static inline SeqOneByteString* cast(Object* obj);
9323 // Garbage collection support. This method is called by the
9324 // garbage collector to compute the actual size of an AsciiString
9326 inline int SeqOneByteStringSize(InstanceType instance_type);
9328 // Computes the size for an AsciiString instance of a given length.
9329 static int SizeFor(int length) {
9330 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
9333 // Maximal memory usage for a single sequential ASCII string.
9334 static const int kMaxSize = 512 * MB - 1;
9335 // Maximal length of a single sequential ASCII string.
9336 // Q.v. String::kMaxLength which is the maximal size of concatenated strings.
9337 static const int kMaxLength = (kMaxSize - kHeaderSize);
9340 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
9344 // The TwoByteString class captures sequential unicode string objects.
9345 // Each character in the TwoByteString is a two-byte uint16_t.
9346 class SeqTwoByteString: public SeqString {
9348 static const bool kHasAsciiEncoding = false;
9350 // Dispatched behavior.
9351 inline uint16_t SeqTwoByteStringGet(int index);
9352 inline void SeqTwoByteStringSet(int index, uint16_t value);
9354 // Get the address of the characters in this string.
9355 inline Address GetCharsAddress();
9357 inline uc16* GetChars();
9360 const uint16_t* SeqTwoByteStringGetData(unsigned start);
9363 static inline SeqTwoByteString* cast(Object* obj);
9365 // Garbage collection support. This method is called by the
9366 // garbage collector to compute the actual size of a TwoByteString
9368 inline int SeqTwoByteStringSize(InstanceType instance_type);
9370 // Computes the size for a TwoByteString instance of a given length.
9371 static int SizeFor(int length) {
9372 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
9375 // Maximal memory usage for a single sequential two-byte string.
9376 static const int kMaxSize = 512 * MB - 1;
9377 // Maximal length of a single sequential two-byte string.
9378 // Q.v. String::kMaxLength which is the maximal size of concatenated strings.
9379 static const int kMaxLength = (kMaxSize - kHeaderSize) / sizeof(uint16_t);
9382 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
9386 // The ConsString class describes string values built by using the
9387 // addition operator on strings. A ConsString is a pair where the
9388 // first and second components are pointers to other string values.
9389 // One or both components of a ConsString can be pointers to other
9390 // ConsStrings, creating a binary tree of ConsStrings where the leaves
9391 // are non-ConsString string values. The string value represented by
9392 // a ConsString can be obtained by concatenating the leaf string
9393 // values in a left-to-right depth-first traversal of the tree.
9394 class ConsString: public String {
9396 // First string of the cons cell.
9397 inline String* first();
9398 // Doesn't check that the result is a string, even in debug mode. This is
9399 // useful during GC where the mark bits confuse the checks.
9400 inline Object* unchecked_first();
9401 inline void set_first(String* first,
9402 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9404 // Second string of the cons cell.
9405 inline String* second();
9406 // Doesn't check that the result is a string, even in debug mode. This is
9407 // useful during GC where the mark bits confuse the checks.
9408 inline Object* unchecked_second();
9409 inline void set_second(String* second,
9410 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9412 // Dispatched behavior.
9413 uint16_t ConsStringGet(int index);
9416 static inline ConsString* cast(Object* obj);
9418 // Layout description.
9419 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
9420 static const int kSecondOffset = kFirstOffset + kPointerSize;
9421 static const int kSize = kSecondOffset + kPointerSize;
9423 // Minimum length for a cons string.
9424 static const int kMinLength = 13;
9426 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
9429 DECLARE_VERIFIER(ConsString)
9432 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
9436 // The Sliced String class describes strings that are substrings of another
9437 // sequential string. The motivation is to save time and memory when creating
9438 // a substring. A Sliced String is described as a pointer to the parent,
9439 // the offset from the start of the parent string and the length. Using
9440 // a Sliced String therefore requires unpacking of the parent string and
9441 // adding the offset to the start address. A substring of a Sliced String
9442 // are not nested since the double indirection is simplified when creating
9443 // such a substring.
9444 // Currently missing features are:
9445 // - handling externalized parent strings
9446 // - external strings as parent
9447 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
9448 class SlicedString: public String {
9450 inline String* parent();
9451 inline void set_parent(String* parent,
9452 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9453 inline int offset();
9454 inline void set_offset(int offset);
9456 // Dispatched behavior.
9457 uint16_t SlicedStringGet(int index);
9460 static inline SlicedString* cast(Object* obj);
9462 // Layout description.
9463 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
9464 static const int kOffsetOffset = kParentOffset + kPointerSize;
9465 static const int kSize = kOffsetOffset + kPointerSize;
9467 // Minimum length for a sliced string.
9468 static const int kMinLength = 13;
9470 typedef FixedBodyDescriptor<kParentOffset,
9471 kOffsetOffset + kPointerSize, kSize>
9474 DECLARE_VERIFIER(SlicedString)
9477 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
9481 // The ExternalString class describes string values that are backed by
9482 // a string resource that lies outside the V8 heap. ExternalStrings
9483 // consist of the length field common to all strings, a pointer to the
9484 // external resource. It is important to ensure (externally) that the
9485 // resource is not deallocated while the ExternalString is live in the
9488 // The API expects that all ExternalStrings are created through the
9489 // API. Therefore, ExternalStrings should not be used internally.
9490 class ExternalString: public String {
9493 static inline ExternalString* cast(Object* obj);
9495 // Layout description.
9496 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
9497 static const int kShortSize = kResourceOffset + kPointerSize;
9498 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
9499 static const int kSize = kResourceDataOffset + kPointerSize;
9501 static const int kMaxShortLength =
9502 (kShortSize - SeqString::kHeaderSize) / kCharSize;
9504 // Return whether external string is short (data pointer is not cached).
9505 inline bool is_short();
9507 STATIC_CHECK(kResourceOffset == Internals::kStringResourceOffset);
9510 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
9514 // The ExternalAsciiString class is an external string backed by an
9516 class ExternalAsciiString: public ExternalString {
9518 static const bool kHasAsciiEncoding = true;
9520 typedef v8::String::ExternalAsciiStringResource Resource;
9522 // The underlying resource.
9523 inline const Resource* resource();
9524 inline void set_resource(const Resource* buffer);
9526 // Update the pointer cache to the external character array.
9527 // The cached pointer is always valid, as the external character array does =
9528 // not move during lifetime. Deserialization is the only exception, after
9529 // which the pointer cache has to be refreshed.
9530 inline void update_data_cache();
9532 inline const uint8_t* GetChars();
9534 // Dispatched behavior.
9535 inline uint16_t ExternalAsciiStringGet(int index);
9538 static inline ExternalAsciiString* cast(Object* obj);
9540 // Garbage collection support.
9541 inline void ExternalAsciiStringIterateBody(ObjectVisitor* v);
9543 template<typename StaticVisitor>
9544 inline void ExternalAsciiStringIterateBody();
9547 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalAsciiString);
9551 // The ExternalTwoByteString class is an external string backed by a UTF-16
9553 class ExternalTwoByteString: public ExternalString {
9555 static const bool kHasAsciiEncoding = false;
9557 typedef v8::String::ExternalStringResource Resource;
9559 // The underlying string resource.
9560 inline const Resource* resource();
9561 inline void set_resource(const Resource* buffer);
9563 // Update the pointer cache to the external character array.
9564 // The cached pointer is always valid, as the external character array does =
9565 // not move during lifetime. Deserialization is the only exception, after
9566 // which the pointer cache has to be refreshed.
9567 inline void update_data_cache();
9569 inline const uint16_t* GetChars();
9571 // Dispatched behavior.
9572 inline uint16_t ExternalTwoByteStringGet(int index);
9575 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
9578 static inline ExternalTwoByteString* cast(Object* obj);
9580 // Garbage collection support.
9581 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
9583 template<typename StaticVisitor>
9584 inline void ExternalTwoByteStringIterateBody();
9587 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
9591 // Utility superclass for stack-allocated objects that must be updated
9592 // on gc. It provides two ways for the gc to update instances, either
9593 // iterating or updating after gc.
9594 class Relocatable BASE_EMBEDDED {
9596 explicit inline Relocatable(Isolate* isolate);
9597 inline virtual ~Relocatable();
9598 virtual void IterateInstance(ObjectVisitor* v) { }
9599 virtual void PostGarbageCollection() { }
9601 static void PostGarbageCollectionProcessing(Isolate* isolate);
9602 static int ArchiveSpacePerThread();
9603 static char* ArchiveState(Isolate* isolate, char* to);
9604 static char* RestoreState(Isolate* isolate, char* from);
9605 static void Iterate(Isolate* isolate, ObjectVisitor* v);
9606 static void Iterate(ObjectVisitor* v, Relocatable* top);
9607 static char* Iterate(ObjectVisitor* v, char* t);
9615 // A flat string reader provides random access to the contents of a
9616 // string independent of the character width of the string. The handle
9617 // must be valid as long as the reader is being used.
9618 class FlatStringReader : public Relocatable {
9620 FlatStringReader(Isolate* isolate, Handle<String> str);
9621 FlatStringReader(Isolate* isolate, Vector<const char> input);
9622 void PostGarbageCollection();
9623 inline uc32 Get(int index);
9624 int length() { return length_; }
9633 // A ConsStringOp that returns null.
9634 // Useful when the operation to apply on a ConsString
9635 // requires an expensive data structure.
9636 class ConsStringNullOp {
9638 inline ConsStringNullOp() {}
9639 static inline String* Operate(String*, unsigned*, int32_t*, unsigned*);
9641 DISALLOW_COPY_AND_ASSIGN(ConsStringNullOp);
9645 // This maintains an off-stack representation of the stack frames required
9646 // to traverse a ConsString, allowing an entirely iterative and restartable
9647 // traversal of the entire string
9648 // Note: this class is not GC-safe.
9649 class ConsStringIteratorOp {
9651 inline ConsStringIteratorOp() {}
9652 String* Operate(String* string,
9653 unsigned* offset_out,
9655 unsigned* length_out);
9656 inline String* ContinueOperation(int32_t* type_out, unsigned* length_out);
9657 inline void Reset();
9658 inline bool HasMore();
9661 // TODO(dcarney): Templatize this out for different stack sizes.
9662 static const unsigned kStackSize = 32;
9663 // Use a mask instead of doing modulo operations for stack wrapping.
9664 static const unsigned kDepthMask = kStackSize-1;
9665 STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
9666 static inline unsigned OffsetForDepth(unsigned depth);
9668 inline void PushLeft(ConsString* string);
9669 inline void PushRight(ConsString* string);
9670 inline void AdjustMaximumDepth();
9672 String* NextLeaf(bool* blew_stack, int32_t* type_out, unsigned* length_out);
9673 String* Search(unsigned* offset_out,
9675 unsigned* length_out);
9678 unsigned maximum_depth_;
9679 // Stack must always contain only frames for which right traversal
9680 // has not yet been performed.
9681 ConsString* frames_[kStackSize];
9684 DISALLOW_COPY_AND_ASSIGN(ConsStringIteratorOp);
9688 // Note: this class is not GC-safe.
9689 class StringCharacterStream {
9691 inline StringCharacterStream(String* string,
9692 ConsStringIteratorOp* op,
9693 unsigned offset = 0);
9694 inline uint16_t GetNext();
9695 inline bool HasMore();
9696 inline void Reset(String* string, unsigned offset = 0);
9697 inline void VisitOneByteString(const uint8_t* chars, unsigned length);
9698 inline void VisitTwoByteString(const uint16_t* chars, unsigned length);
9703 const uint8_t* buffer8_;
9704 const uint16_t* buffer16_;
9706 const uint8_t* end_;
9707 ConsStringIteratorOp* op_;
9708 DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
9712 template <typename T>
9713 class VectorIterator {
9715 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
9716 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
9717 T GetNext() { return data_[index_++]; }
9718 bool has_more() { return index_ < data_.length(); }
9720 Vector<const T> data_;
9725 // The Oddball describes objects null, undefined, true, and false.
9726 class Oddball: public HeapObject {
9728 // [to_string]: Cached to_string computed at startup.
9729 DECL_ACCESSORS(to_string, String)
9731 // [to_number]: Cached to_number computed at startup.
9732 DECL_ACCESSORS(to_number, Object)
9735 inline void set_kind(byte kind);
9738 static inline Oddball* cast(Object* obj);
9740 // Dispatched behavior.
9741 DECLARE_VERIFIER(Oddball)
9743 // Initialize the fields.
9744 MUST_USE_RESULT MaybeObject* Initialize(Heap* heap,
9745 const char* to_string,
9749 // Layout description.
9750 static const int kToStringOffset = HeapObject::kHeaderSize;
9751 static const int kToNumberOffset = kToStringOffset + kPointerSize;
9752 static const int kKindOffset = kToNumberOffset + kPointerSize;
9753 static const int kSize = kKindOffset + kPointerSize;
9755 static const byte kFalse = 0;
9756 static const byte kTrue = 1;
9757 static const byte kNotBooleanMask = ~1;
9758 static const byte kTheHole = 2;
9759 static const byte kNull = 3;
9760 static const byte kArgumentMarker = 4;
9761 static const byte kUndefined = 5;
9762 static const byte kUninitialized = 6;
9763 static const byte kOther = 7;
9765 typedef FixedBodyDescriptor<kToStringOffset,
9766 kToNumberOffset + kPointerSize,
9767 kSize> BodyDescriptor;
9769 STATIC_CHECK(kKindOffset == Internals::kOddballKindOffset);
9770 STATIC_CHECK(kNull == Internals::kNullOddballKind);
9771 STATIC_CHECK(kUndefined == Internals::kUndefinedOddballKind);
9774 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
9778 class Cell: public HeapObject {
9780 // [value]: value of the global property.
9781 DECL_ACCESSORS(value, Object)
9784 static inline Cell* cast(Object* obj);
9786 static inline Cell* FromValueAddress(Address value) {
9787 Object* result = FromAddress(value - kValueOffset);
9788 ASSERT(result->IsCell() || result->IsPropertyCell());
9789 return static_cast<Cell*>(result);
9792 inline Address ValueAddress() {
9793 return address() + kValueOffset;
9796 // Dispatched behavior.
9797 DECLARE_PRINTER(Cell)
9798 DECLARE_VERIFIER(Cell)
9800 // Layout description.
9801 static const int kValueOffset = HeapObject::kHeaderSize;
9802 static const int kSize = kValueOffset + kPointerSize;
9804 typedef FixedBodyDescriptor<kValueOffset,
9805 kValueOffset + kPointerSize,
9806 kSize> BodyDescriptor;
9809 DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9813 class PropertyCell: public Cell {
9815 // [type]: type of the global property.
9817 void set_type(HeapType* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9819 // [dependent_code]: dependent code that depends on the type of the global
9821 DECL_ACCESSORS(dependent_code, DependentCode)
9823 // Sets the value of the cell and updates the type field to be the union
9824 // of the cell's current type and the value's type. If the change causes
9825 // a change of the type of the cell's contents, code dependent on the cell
9826 // will be deoptimized.
9827 static void SetValueInferType(Handle<PropertyCell> cell,
9828 Handle<Object> value);
9830 // Computes the new type of the cell's contents for the given value, but
9831 // without actually modifying the 'type' field.
9832 static Handle<HeapType> UpdatedType(Handle<PropertyCell> cell,
9833 Handle<Object> value);
9835 void AddDependentCompilationInfo(CompilationInfo* info);
9837 void AddDependentCode(Handle<Code> code);
9840 static inline PropertyCell* cast(Object* obj);
9842 inline Address TypeAddress() {
9843 return address() + kTypeOffset;
9846 // Dispatched behavior.
9847 DECLARE_PRINTER(PropertyCell)
9848 DECLARE_VERIFIER(PropertyCell)
9850 // Layout description.
9851 static const int kTypeOffset = kValueOffset + kPointerSize;
9852 static const int kDependentCodeOffset = kTypeOffset + kPointerSize;
9853 static const int kSize = kDependentCodeOffset + kPointerSize;
9855 static const int kPointerFieldsBeginOffset = kValueOffset;
9856 static const int kPointerFieldsEndOffset = kDependentCodeOffset;
9858 typedef FixedBodyDescriptor<kValueOffset,
9860 kSize> BodyDescriptor;
9863 DECL_ACCESSORS(type_raw, Object)
9864 DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9868 // The JSProxy describes EcmaScript Harmony proxies
9869 class JSProxy: public JSReceiver {
9871 // [handler]: The handler property.
9872 DECL_ACCESSORS(handler, Object)
9874 // [hash]: The hash code property (undefined if not initialized yet).
9875 DECL_ACCESSORS(hash, Object)
9878 static inline JSProxy* cast(Object* obj);
9880 MUST_USE_RESULT MaybeObject* GetPropertyWithHandler(
9883 MUST_USE_RESULT MaybeObject* GetElementWithHandler(
9887 // If the handler defines an accessor property with a setter, invoke it.
9888 // If it defines an accessor property without a setter, or a data property
9889 // that is read-only, throw. In all these cases set '*done' to true,
9890 // otherwise set it to false.
9891 static Handle<Object> SetPropertyViaPrototypesWithHandler(
9892 Handle<JSProxy> proxy,
9893 Handle<JSReceiver> receiver,
9895 Handle<Object> value,
9896 PropertyAttributes attributes,
9897 StrictModeFlag strict_mode,
9900 MUST_USE_RESULT PropertyAttributes GetPropertyAttributeWithHandler(
9901 JSReceiver* receiver,
9903 MUST_USE_RESULT PropertyAttributes GetElementAttributeWithHandler(
9904 JSReceiver* receiver,
9907 // Turn the proxy into an (empty) JSObject.
9908 static void Fix(Handle<JSProxy> proxy);
9910 // Initializes the body after the handler slot.
9911 inline void InitializeBody(int object_size, Object* value);
9913 // Invoke a trap by name. If the trap does not exist on this's handler,
9914 // but derived_trap is non-NULL, invoke that instead. May cause GC.
9915 Handle<Object> CallTrap(const char* name,
9916 Handle<Object> derived_trap,
9918 Handle<Object> args[]);
9920 // Dispatched behavior.
9921 DECLARE_PRINTER(JSProxy)
9922 DECLARE_VERIFIER(JSProxy)
9924 // Layout description. We add padding so that a proxy has the same
9925 // size as a virgin JSObject. This is essential for becoming a JSObject
9927 static const int kHandlerOffset = HeapObject::kHeaderSize;
9928 static const int kHashOffset = kHandlerOffset + kPointerSize;
9929 static const int kPaddingOffset = kHashOffset + kPointerSize;
9930 static const int kSize = JSObject::kHeaderSize;
9931 static const int kHeaderSize = kPaddingOffset;
9932 static const int kPaddingSize = kSize - kPaddingOffset;
9934 STATIC_CHECK(kPaddingSize >= 0);
9936 typedef FixedBodyDescriptor<kHandlerOffset,
9938 kSize> BodyDescriptor;
9941 friend class JSReceiver;
9943 static Handle<Object> SetPropertyWithHandler(Handle<JSProxy> proxy,
9944 Handle<JSReceiver> receiver,
9946 Handle<Object> value,
9947 PropertyAttributes attributes,
9948 StrictModeFlag strict_mode);
9949 static Handle<Object> SetElementWithHandler(Handle<JSProxy> proxy,
9950 Handle<JSReceiver> receiver,
9952 Handle<Object> value,
9953 StrictModeFlag strict_mode);
9955 static bool HasPropertyWithHandler(Handle<JSProxy> proxy, Handle<Name> name);
9956 static bool HasElementWithHandler(Handle<JSProxy> proxy, uint32_t index);
9958 static Handle<Object> DeletePropertyWithHandler(Handle<JSProxy> proxy,
9961 static Handle<Object> DeleteElementWithHandler(Handle<JSProxy> proxy,
9965 MUST_USE_RESULT Object* GetIdentityHash();
9967 static Handle<Object> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
9969 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
9973 class JSFunctionProxy: public JSProxy {
9975 // [call_trap]: The call trap.
9976 DECL_ACCESSORS(call_trap, Object)
9978 // [construct_trap]: The construct trap.
9979 DECL_ACCESSORS(construct_trap, Object)
9982 static inline JSFunctionProxy* cast(Object* obj);
9984 // Dispatched behavior.
9985 DECLARE_PRINTER(JSFunctionProxy)
9986 DECLARE_VERIFIER(JSFunctionProxy)
9988 // Layout description.
9989 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
9990 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
9991 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
9992 static const int kSize = JSFunction::kSize;
9993 static const int kPaddingSize = kSize - kPaddingOffset;
9995 STATIC_CHECK(kPaddingSize >= 0);
9997 typedef FixedBodyDescriptor<kHandlerOffset,
9998 kConstructTrapOffset + kPointerSize,
9999 kSize> BodyDescriptor;
10002 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
10006 // The JSSet describes EcmaScript Harmony sets
10007 class JSSet: public JSObject {
10009 // [set]: the backing hash set containing keys.
10010 DECL_ACCESSORS(table, Object)
10013 static inline JSSet* cast(Object* obj);
10015 // Dispatched behavior.
10016 DECLARE_PRINTER(JSSet)
10017 DECLARE_VERIFIER(JSSet)
10019 static const int kTableOffset = JSObject::kHeaderSize;
10020 static const int kSize = kTableOffset + kPointerSize;
10023 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
10027 // The JSMap describes EcmaScript Harmony maps
10028 class JSMap: public JSObject {
10030 // [table]: the backing hash table mapping keys to values.
10031 DECL_ACCESSORS(table, Object)
10034 static inline JSMap* cast(Object* obj);
10036 // Dispatched behavior.
10037 DECLARE_PRINTER(JSMap)
10038 DECLARE_VERIFIER(JSMap)
10040 static const int kTableOffset = JSObject::kHeaderSize;
10041 static const int kSize = kTableOffset + kPointerSize;
10044 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
10048 // Base class for both JSWeakMap and JSWeakSet
10049 class JSWeakCollection: public JSObject {
10051 // [table]: the backing hash table mapping keys to values.
10052 DECL_ACCESSORS(table, Object)
10054 // [next]: linked list of encountered weak maps during GC.
10055 DECL_ACCESSORS(next, Object)
10057 static const int kTableOffset = JSObject::kHeaderSize;
10058 static const int kNextOffset = kTableOffset + kPointerSize;
10059 static const int kSize = kNextOffset + kPointerSize;
10062 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
10066 // The JSWeakMap describes EcmaScript Harmony weak maps
10067 class JSWeakMap: public JSWeakCollection {
10070 static inline JSWeakMap* cast(Object* obj);
10072 // Dispatched behavior.
10073 DECLARE_PRINTER(JSWeakMap)
10074 DECLARE_VERIFIER(JSWeakMap)
10077 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
10081 // The JSWeakSet describes EcmaScript Harmony weak sets
10082 class JSWeakSet: public JSWeakCollection {
10085 static inline JSWeakSet* cast(Object* obj);
10087 // Dispatched behavior.
10088 DECLARE_PRINTER(JSWeakSet)
10089 DECLARE_VERIFIER(JSWeakSet)
10092 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
10096 class JSArrayBuffer: public JSObject {
10098 // [backing_store]: backing memory for this array
10099 DECL_ACCESSORS(backing_store, void)
10101 // [byte_length]: length in bytes
10102 DECL_ACCESSORS(byte_length, Object)
10105 DECL_ACCESSORS(flag, Smi)
10107 inline bool is_external();
10108 inline void set_is_external(bool value);
10110 inline bool should_be_freed();
10111 inline void set_should_be_freed(bool value);
10113 // [weak_next]: linked list of array buffers.
10114 DECL_ACCESSORS(weak_next, Object)
10116 // [weak_first_array]: weak linked list of views.
10117 DECL_ACCESSORS(weak_first_view, Object)
10120 static inline JSArrayBuffer* cast(Object* obj);
10122 // Neutering. Only neuters the buffer, not associated typed arrays.
10125 // Dispatched behavior.
10126 DECLARE_PRINTER(JSArrayBuffer)
10127 DECLARE_VERIFIER(JSArrayBuffer)
10129 static const int kBackingStoreOffset = JSObject::kHeaderSize;
10130 static const int kByteLengthOffset = kBackingStoreOffset + kPointerSize;
10131 static const int kFlagOffset = kByteLengthOffset + kPointerSize;
10132 static const int kWeakNextOffset = kFlagOffset + kPointerSize;
10133 static const int kWeakFirstViewOffset = kWeakNextOffset + kPointerSize;
10134 static const int kSize = kWeakFirstViewOffset + kPointerSize;
10136 static const int kSizeWithInternalFields =
10137 kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
10140 // Bit position in a flag
10141 static const int kIsExternalBit = 0;
10142 static const int kShouldBeFreed = 1;
10144 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
10148 class JSArrayBufferView: public JSObject {
10150 // [buffer]: ArrayBuffer that this typed array views.
10151 DECL_ACCESSORS(buffer, Object)
10153 // [byte_length]: offset of typed array in bytes.
10154 DECL_ACCESSORS(byte_offset, Object)
10156 // [byte_length]: length of typed array in bytes.
10157 DECL_ACCESSORS(byte_length, Object)
10159 // [weak_next]: linked list of typed arrays over the same array buffer.
10160 DECL_ACCESSORS(weak_next, Object)
10163 static inline JSArrayBufferView* cast(Object* obj);
10165 DECLARE_VERIFIER(JSArrayBufferView)
10167 static const int kBufferOffset = JSObject::kHeaderSize;
10168 static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
10169 static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
10170 static const int kWeakNextOffset = kByteLengthOffset + kPointerSize;
10171 static const int kViewSize = kWeakNextOffset + kPointerSize;
10177 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
10181 class JSTypedArray: public JSArrayBufferView {
10183 // [length]: length of typed array in elements.
10184 DECL_ACCESSORS(length, Object)
10186 // Neutering. Only neuters this typed array.
10190 static inline JSTypedArray* cast(Object* obj);
10192 ExternalArrayType type();
10193 size_t element_size();
10195 // Dispatched behavior.
10196 DECLARE_PRINTER(JSTypedArray)
10197 DECLARE_VERIFIER(JSTypedArray)
10199 static const int kLengthOffset = kViewSize + kPointerSize;
10200 static const int kSize = kLengthOffset + kPointerSize;
10202 static const int kSizeWithInternalFields =
10203 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
10206 DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
10210 class JSDataView: public JSArrayBufferView {
10212 // Only neuters this DataView
10216 static inline JSDataView* cast(Object* obj);
10218 // Dispatched behavior.
10219 DECLARE_PRINTER(JSDataView)
10220 DECLARE_VERIFIER(JSDataView)
10222 static const int kSize = kViewSize;
10224 static const int kSizeWithInternalFields =
10225 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
10228 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
10232 // Foreign describes objects pointing from JavaScript to C structures.
10233 // Since they cannot contain references to JS HeapObjects they can be
10234 // placed in old_data_space.
10235 class Foreign: public HeapObject {
10237 // [address]: field containing the address.
10238 inline Address foreign_address();
10239 inline void set_foreign_address(Address value);
10242 static inline Foreign* cast(Object* obj);
10244 // Dispatched behavior.
10245 inline void ForeignIterateBody(ObjectVisitor* v);
10247 template<typename StaticVisitor>
10248 inline void ForeignIterateBody();
10250 // Dispatched behavior.
10251 DECLARE_PRINTER(Foreign)
10252 DECLARE_VERIFIER(Foreign)
10254 // Layout description.
10256 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
10257 static const int kSize = kForeignAddressOffset + kPointerSize;
10259 STATIC_CHECK(kForeignAddressOffset == Internals::kForeignAddressOffset);
10262 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
10266 // The JSArray describes JavaScript Arrays
10267 // Such an array can be in one of two modes:
10268 // - fast, backing storage is a FixedArray and length <= elements.length();
10269 // Please note: push and pop can be used to grow and shrink the array.
10270 // - slow, backing storage is a HashTable with numbers as keys.
10271 class JSArray: public JSObject {
10273 // [length]: The length property.
10274 DECL_ACCESSORS(length, Object)
10276 // Overload the length setter to skip write barrier when the length
10277 // is set to a smi. This matches the set function on FixedArray.
10278 inline void set_length(Smi* length);
10280 static void JSArrayUpdateLengthFromIndex(Handle<JSArray> array,
10282 Handle<Object> value);
10284 MUST_USE_RESULT MaybeObject* JSArrayUpdateLengthFromIndex(uint32_t index,
10287 // Initialize the array with the given capacity. The function may
10288 // fail due to out-of-memory situations, but only if the requested
10289 // capacity is non-zero.
10290 MUST_USE_RESULT MaybeObject* Initialize(int capacity, int length = 0);
10292 // Initializes the array to a certain length.
10293 inline bool AllowsSetElementsLength();
10295 MUST_USE_RESULT MaybeObject* SetElementsLength(Object* length);
10297 // Set the content of the array to the content of storage.
10298 MUST_USE_RESULT inline MaybeObject* SetContent(FixedArrayBase* storage);
10301 static inline JSArray* cast(Object* obj);
10303 // Uses handles. Ensures that the fixed array backing the JSArray has at
10304 // least the stated size.
10305 inline void EnsureSize(int minimum_size_of_backing_fixed_array);
10307 // Dispatched behavior.
10308 DECLARE_PRINTER(JSArray)
10309 DECLARE_VERIFIER(JSArray)
10311 // Number of element slots to pre-allocate for an empty array.
10312 static const int kPreallocatedArrayElements = 4;
10314 // Layout description.
10315 static const int kLengthOffset = JSObject::kHeaderSize;
10316 static const int kSize = kLengthOffset + kPointerSize;
10319 // Expand the fixed array backing of a fast-case JSArray to at least
10320 // the requested size.
10321 void Expand(int minimum_size_of_backing_fixed_array);
10323 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
10327 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
10328 Handle<Map> initial_map);
10331 // JSRegExpResult is just a JSArray with a specific initial map.
10332 // This initial map adds in-object properties for "index" and "input"
10333 // properties, as assigned by RegExp.prototype.exec, which allows
10334 // faster creation of RegExp exec results.
10335 // This class just holds constants used when creating the result.
10336 // After creation the result must be treated as a JSArray in all regards.
10337 class JSRegExpResult: public JSArray {
10339 // Offsets of object fields.
10340 static const int kIndexOffset = JSArray::kSize;
10341 static const int kInputOffset = kIndexOffset + kPointerSize;
10342 static const int kSize = kInputOffset + kPointerSize;
10343 // Indices of in-object properties.
10344 static const int kIndexIndex = 0;
10345 static const int kInputIndex = 1;
10347 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
10351 class AccessorInfo: public Struct {
10353 DECL_ACCESSORS(name, Object)
10354 DECL_ACCESSORS(flag, Smi)
10355 DECL_ACCESSORS(expected_receiver_type, Object)
10357 inline bool all_can_read();
10358 inline void set_all_can_read(bool value);
10360 inline bool all_can_write();
10361 inline void set_all_can_write(bool value);
10363 inline bool prohibits_overwriting();
10364 inline void set_prohibits_overwriting(bool value);
10366 inline PropertyAttributes property_attributes();
10367 inline void set_property_attributes(PropertyAttributes attributes);
10369 // Checks whether the given receiver is compatible with this accessor.
10370 inline bool IsCompatibleReceiver(Object* receiver);
10372 static inline AccessorInfo* cast(Object* obj);
10374 // Dispatched behavior.
10375 DECLARE_VERIFIER(AccessorInfo)
10377 // Append all descriptors to the array that are not already there.
10378 // Return number added.
10379 static int AppendUnique(Handle<Object> descriptors,
10380 Handle<FixedArray> array,
10381 int valid_descriptors);
10383 static const int kNameOffset = HeapObject::kHeaderSize;
10384 static const int kFlagOffset = kNameOffset + kPointerSize;
10385 static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
10386 static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
10389 // Bit positions in flag.
10390 static const int kAllCanReadBit = 0;
10391 static const int kAllCanWriteBit = 1;
10392 static const int kProhibitsOverwritingBit = 2;
10393 class AttributesField: public BitField<PropertyAttributes, 3, 3> {};
10395 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
10399 enum AccessorDescriptorType {
10400 kDescriptorBitmaskCompare,
10401 kDescriptorPointerCompare,
10402 kDescriptorPrimitiveValue,
10403 kDescriptorObjectDereference,
10404 kDescriptorPointerDereference,
10405 kDescriptorPointerShift,
10406 kDescriptorReturnObject
10410 struct BitmaskCompareDescriptor {
10412 uint32_t compare_value;
10413 uint8_t size; // Must be in {1,2,4}.
10417 struct PointerCompareDescriptor {
10418 void* compare_value;
10422 struct PrimitiveValueDescriptor {
10423 v8::DeclaredAccessorDescriptorDataType data_type;
10424 uint8_t bool_offset; // Must be in [0,7], used for kDescriptorBoolType.
10428 struct ObjectDerefenceDescriptor {
10429 uint8_t internal_field;
10433 struct PointerShiftDescriptor {
10434 int16_t byte_offset;
10438 struct DeclaredAccessorDescriptorData {
10439 AccessorDescriptorType type;
10441 struct BitmaskCompareDescriptor bitmask_compare_descriptor;
10442 struct PointerCompareDescriptor pointer_compare_descriptor;
10443 struct PrimitiveValueDescriptor primitive_value_descriptor;
10444 struct ObjectDerefenceDescriptor object_dereference_descriptor;
10445 struct PointerShiftDescriptor pointer_shift_descriptor;
10450 class DeclaredAccessorDescriptor;
10453 class DeclaredAccessorDescriptorIterator {
10455 explicit DeclaredAccessorDescriptorIterator(
10456 DeclaredAccessorDescriptor* descriptor);
10457 const DeclaredAccessorDescriptorData* Next();
10458 bool Complete() const { return length_ == offset_; }
10463 DISALLOW_IMPLICIT_CONSTRUCTORS(DeclaredAccessorDescriptorIterator);
10467 class DeclaredAccessorDescriptor: public Struct {
10469 DECL_ACCESSORS(serialized_data, ByteArray)
10471 static inline DeclaredAccessorDescriptor* cast(Object* obj);
10473 static Handle<DeclaredAccessorDescriptor> Create(
10475 const DeclaredAccessorDescriptorData& data,
10476 Handle<DeclaredAccessorDescriptor> previous);
10478 // Dispatched behavior.
10479 DECLARE_PRINTER(DeclaredAccessorDescriptor)
10480 DECLARE_VERIFIER(DeclaredAccessorDescriptor)
10482 static const int kSerializedDataOffset = HeapObject::kHeaderSize;
10483 static const int kSize = kSerializedDataOffset + kPointerSize;
10486 DISALLOW_IMPLICIT_CONSTRUCTORS(DeclaredAccessorDescriptor);
10490 class DeclaredAccessorInfo: public AccessorInfo {
10492 DECL_ACCESSORS(descriptor, DeclaredAccessorDescriptor)
10494 static inline DeclaredAccessorInfo* cast(Object* obj);
10496 // Dispatched behavior.
10497 DECLARE_PRINTER(DeclaredAccessorInfo)
10498 DECLARE_VERIFIER(DeclaredAccessorInfo)
10500 static const int kDescriptorOffset = AccessorInfo::kSize;
10501 static const int kSize = kDescriptorOffset + kPointerSize;
10504 DISALLOW_IMPLICIT_CONSTRUCTORS(DeclaredAccessorInfo);
10508 // An accessor must have a getter, but can have no setter.
10510 // When setting a property, V8 searches accessors in prototypes.
10511 // If an accessor was found and it does not have a setter,
10512 // the request is ignored.
10514 // If the accessor in the prototype has the READ_ONLY property attribute, then
10515 // a new value is added to the local object when the property is set.
10516 // This shadows the accessor in the prototype.
10517 class ExecutableAccessorInfo: public AccessorInfo {
10519 DECL_ACCESSORS(getter, Object)
10520 DECL_ACCESSORS(setter, Object)
10521 DECL_ACCESSORS(data, Object)
10523 static inline ExecutableAccessorInfo* cast(Object* obj);
10525 // Dispatched behavior.
10526 DECLARE_PRINTER(ExecutableAccessorInfo)
10527 DECLARE_VERIFIER(ExecutableAccessorInfo)
10529 static const int kGetterOffset = AccessorInfo::kSize;
10530 static const int kSetterOffset = kGetterOffset + kPointerSize;
10531 static const int kDataOffset = kSetterOffset + kPointerSize;
10532 static const int kSize = kDataOffset + kPointerSize;
10535 DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
10539 // Support for JavaScript accessors: A pair of a getter and a setter. Each
10540 // accessor can either be
10541 // * a pointer to a JavaScript function or proxy: a real accessor
10542 // * undefined: considered an accessor by the spec, too, strangely enough
10543 // * the hole: an accessor which has not been set
10544 // * a pointer to a map: a transition used to ensure map sharing
10545 // access_flags provides the ability to override access checks on access check
10547 class AccessorPair: public Struct {
10549 DECL_ACCESSORS(getter, Object)
10550 DECL_ACCESSORS(setter, Object)
10551 DECL_ACCESSORS(access_flags, Smi)
10553 inline void set_access_flags(v8::AccessControl access_control);
10554 inline bool all_can_read();
10555 inline bool all_can_write();
10556 inline bool prohibits_overwriting();
10558 static inline AccessorPair* cast(Object* obj);
10560 static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
10562 Object* get(AccessorComponent component) {
10563 return component == ACCESSOR_GETTER ? getter() : setter();
10566 void set(AccessorComponent component, Object* value) {
10567 if (component == ACCESSOR_GETTER) {
10574 // Note: Returns undefined instead in case of a hole.
10575 Object* GetComponent(AccessorComponent component);
10577 // Set both components, skipping arguments which are a JavaScript null.
10578 void SetComponents(Object* getter, Object* setter) {
10579 if (!getter->IsNull()) set_getter(getter);
10580 if (!setter->IsNull()) set_setter(setter);
10583 bool ContainsAccessor() {
10584 return IsJSAccessor(getter()) || IsJSAccessor(setter());
10587 // Dispatched behavior.
10588 DECLARE_PRINTER(AccessorPair)
10589 DECLARE_VERIFIER(AccessorPair)
10591 static const int kGetterOffset = HeapObject::kHeaderSize;
10592 static const int kSetterOffset = kGetterOffset + kPointerSize;
10593 static const int kAccessFlagsOffset = kSetterOffset + kPointerSize;
10594 static const int kSize = kAccessFlagsOffset + kPointerSize;
10597 static const int kAllCanReadBit = 0;
10598 static const int kAllCanWriteBit = 1;
10599 static const int kProhibitsOverwritingBit = 2;
10601 // Strangely enough, in addition to functions and harmony proxies, the spec
10602 // requires us to consider undefined as a kind of accessor, too:
10604 // Object.defineProperty(obj, "foo", {get: undefined});
10605 // assertTrue("foo" in obj);
10606 bool IsJSAccessor(Object* obj) {
10607 return obj->IsSpecFunction() || obj->IsUndefined();
10610 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
10614 class AccessCheckInfo: public Struct {
10616 DECL_ACCESSORS(named_callback, Object)
10617 DECL_ACCESSORS(indexed_callback, Object)
10618 DECL_ACCESSORS(data, Object)
10620 static inline AccessCheckInfo* cast(Object* obj);
10622 // Dispatched behavior.
10623 DECLARE_PRINTER(AccessCheckInfo)
10624 DECLARE_VERIFIER(AccessCheckInfo)
10626 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
10627 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
10628 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
10629 static const int kSize = kDataOffset + kPointerSize;
10632 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
10636 class InterceptorInfo: public Struct {
10638 DECL_ACCESSORS(getter, Object)
10639 DECL_ACCESSORS(setter, Object)
10640 DECL_ACCESSORS(query, Object)
10641 DECL_ACCESSORS(deleter, Object)
10642 DECL_ACCESSORS(enumerator, Object)
10643 DECL_ACCESSORS(data, Object)
10645 static inline InterceptorInfo* cast(Object* obj);
10647 // Dispatched behavior.
10648 DECLARE_PRINTER(InterceptorInfo)
10649 DECLARE_VERIFIER(InterceptorInfo)
10651 static const int kGetterOffset = HeapObject::kHeaderSize;
10652 static const int kSetterOffset = kGetterOffset + kPointerSize;
10653 static const int kQueryOffset = kSetterOffset + kPointerSize;
10654 static const int kDeleterOffset = kQueryOffset + kPointerSize;
10655 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
10656 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
10657 static const int kSize = kDataOffset + kPointerSize;
10660 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
10664 class CallHandlerInfo: public Struct {
10666 DECL_ACCESSORS(callback, Object)
10667 DECL_ACCESSORS(data, Object)
10669 static inline CallHandlerInfo* cast(Object* obj);
10671 // Dispatched behavior.
10672 DECLARE_PRINTER(CallHandlerInfo)
10673 DECLARE_VERIFIER(CallHandlerInfo)
10675 static const int kCallbackOffset = HeapObject::kHeaderSize;
10676 static const int kDataOffset = kCallbackOffset + kPointerSize;
10677 static const int kSize = kDataOffset + kPointerSize;
10680 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
10684 class TemplateInfo: public Struct {
10686 DECL_ACCESSORS(tag, Object)
10687 DECL_ACCESSORS(property_list, Object)
10688 DECL_ACCESSORS(property_accessors, Object)
10690 DECLARE_VERIFIER(TemplateInfo)
10692 static const int kTagOffset = HeapObject::kHeaderSize;
10693 static const int kPropertyListOffset = kTagOffset + kPointerSize;
10694 static const int kPropertyAccessorsOffset =
10695 kPropertyListOffset + kPointerSize;
10696 static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
10699 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
10703 class FunctionTemplateInfo: public TemplateInfo {
10705 DECL_ACCESSORS(serial_number, Object)
10706 DECL_ACCESSORS(call_code, Object)
10707 DECL_ACCESSORS(prototype_template, Object)
10708 DECL_ACCESSORS(parent_template, Object)
10709 DECL_ACCESSORS(named_property_handler, Object)
10710 DECL_ACCESSORS(indexed_property_handler, Object)
10711 DECL_ACCESSORS(instance_template, Object)
10712 DECL_ACCESSORS(class_name, Object)
10713 DECL_ACCESSORS(signature, Object)
10714 DECL_ACCESSORS(instance_call_handler, Object)
10715 DECL_ACCESSORS(access_check_info, Object)
10716 DECL_ACCESSORS(flag, Smi)
10718 inline int length();
10719 inline void set_length(int value);
10721 // Following properties use flag bits.
10722 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
10723 DECL_BOOLEAN_ACCESSORS(undetectable)
10724 // If the bit is set, object instances created by this function
10725 // requires access check.
10726 DECL_BOOLEAN_ACCESSORS(needs_access_check)
10727 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
10728 DECL_BOOLEAN_ACCESSORS(remove_prototype)
10729 DECL_BOOLEAN_ACCESSORS(do_not_cache)
10731 static inline FunctionTemplateInfo* cast(Object* obj);
10733 // Dispatched behavior.
10734 DECLARE_PRINTER(FunctionTemplateInfo)
10735 DECLARE_VERIFIER(FunctionTemplateInfo)
10737 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
10738 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
10739 static const int kPrototypeTemplateOffset =
10740 kCallCodeOffset + kPointerSize;
10741 static const int kParentTemplateOffset =
10742 kPrototypeTemplateOffset + kPointerSize;
10743 static const int kNamedPropertyHandlerOffset =
10744 kParentTemplateOffset + kPointerSize;
10745 static const int kIndexedPropertyHandlerOffset =
10746 kNamedPropertyHandlerOffset + kPointerSize;
10747 static const int kInstanceTemplateOffset =
10748 kIndexedPropertyHandlerOffset + kPointerSize;
10749 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
10750 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
10751 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
10752 static const int kAccessCheckInfoOffset =
10753 kInstanceCallHandlerOffset + kPointerSize;
10754 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
10755 static const int kLengthOffset = kFlagOffset + kPointerSize;
10756 static const int kSize = kLengthOffset + kPointerSize;
10758 // Returns true if |object| is an instance of this function template.
10759 bool IsTemplateFor(Object* object);
10760 bool IsTemplateFor(Map* map);
10763 // Bit position in the flag, from least significant bit position.
10764 static const int kHiddenPrototypeBit = 0;
10765 static const int kUndetectableBit = 1;
10766 static const int kNeedsAccessCheckBit = 2;
10767 static const int kReadOnlyPrototypeBit = 3;
10768 static const int kRemovePrototypeBit = 4;
10769 static const int kDoNotCacheBit = 5;
10771 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
10775 class ObjectTemplateInfo: public TemplateInfo {
10777 DECL_ACCESSORS(constructor, Object)
10778 DECL_ACCESSORS(internal_field_count, Object)
10780 static inline ObjectTemplateInfo* cast(Object* obj);
10782 // Dispatched behavior.
10783 DECLARE_PRINTER(ObjectTemplateInfo)
10784 DECLARE_VERIFIER(ObjectTemplateInfo)
10786 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10787 static const int kInternalFieldCountOffset =
10788 kConstructorOffset + kPointerSize;
10789 static const int kSize = kInternalFieldCountOffset + kPointerSize;
10793 class SignatureInfo: public Struct {
10795 DECL_ACCESSORS(receiver, Object)
10796 DECL_ACCESSORS(args, Object)
10798 static inline SignatureInfo* cast(Object* obj);
10800 // Dispatched behavior.
10801 DECLARE_PRINTER(SignatureInfo)
10802 DECLARE_VERIFIER(SignatureInfo)
10804 static const int kReceiverOffset = Struct::kHeaderSize;
10805 static const int kArgsOffset = kReceiverOffset + kPointerSize;
10806 static const int kSize = kArgsOffset + kPointerSize;
10809 DISALLOW_IMPLICIT_CONSTRUCTORS(SignatureInfo);
10813 class TypeSwitchInfo: public Struct {
10815 DECL_ACCESSORS(types, Object)
10817 static inline TypeSwitchInfo* cast(Object* obj);
10819 // Dispatched behavior.
10820 DECLARE_PRINTER(TypeSwitchInfo)
10821 DECLARE_VERIFIER(TypeSwitchInfo)
10823 static const int kTypesOffset = Struct::kHeaderSize;
10824 static const int kSize = kTypesOffset + kPointerSize;
10828 #ifdef ENABLE_DEBUGGER_SUPPORT
10829 // The DebugInfo class holds additional information for a function being
10831 class DebugInfo: public Struct {
10833 // The shared function info for the source being debugged.
10834 DECL_ACCESSORS(shared, SharedFunctionInfo)
10835 // Code object for the original code.
10836 DECL_ACCESSORS(original_code, Code)
10837 // Code object for the patched code. This code object is the code object
10838 // currently active for the function.
10839 DECL_ACCESSORS(code, Code)
10840 // Fixed array holding status information for each active break point.
10841 DECL_ACCESSORS(break_points, FixedArray)
10843 // Check if there is a break point at a code position.
10844 bool HasBreakPoint(int code_position);
10845 // Get the break point info object for a code position.
10846 Object* GetBreakPointInfo(int code_position);
10847 // Clear a break point.
10848 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
10850 Handle<Object> break_point_object);
10851 // Set a break point.
10852 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
10853 int source_position, int statement_position,
10854 Handle<Object> break_point_object);
10855 // Get the break point objects for a code position.
10856 Object* GetBreakPointObjects(int code_position);
10857 // Find the break point info holding this break point object.
10858 static Object* FindBreakPointInfo(Handle<DebugInfo> debug_info,
10859 Handle<Object> break_point_object);
10860 // Get the number of break points for this function.
10861 int GetBreakPointCount();
10863 static inline DebugInfo* cast(Object* obj);
10865 // Dispatched behavior.
10866 DECLARE_PRINTER(DebugInfo)
10867 DECLARE_VERIFIER(DebugInfo)
10869 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
10870 static const int kOriginalCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
10871 static const int kPatchedCodeIndex = kOriginalCodeIndex + kPointerSize;
10872 static const int kActiveBreakPointsCountIndex =
10873 kPatchedCodeIndex + kPointerSize;
10874 static const int kBreakPointsStateIndex =
10875 kActiveBreakPointsCountIndex + kPointerSize;
10876 static const int kSize = kBreakPointsStateIndex + kPointerSize;
10879 static const int kNoBreakPointInfo = -1;
10881 // Lookup the index in the break_points array for a code position.
10882 int GetBreakPointInfoIndex(int code_position);
10884 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
10888 // The BreakPointInfo class holds information for break points set in a
10889 // function. The DebugInfo object holds a BreakPointInfo object for each code
10890 // position with one or more break points.
10891 class BreakPointInfo: public Struct {
10893 // The position in the code for the break point.
10894 DECL_ACCESSORS(code_position, Smi)
10895 // The position in the source for the break position.
10896 DECL_ACCESSORS(source_position, Smi)
10897 // The position in the source for the last statement before this break
10899 DECL_ACCESSORS(statement_position, Smi)
10900 // List of related JavaScript break points.
10901 DECL_ACCESSORS(break_point_objects, Object)
10903 // Removes a break point.
10904 static void ClearBreakPoint(Handle<BreakPointInfo> info,
10905 Handle<Object> break_point_object);
10906 // Set a break point.
10907 static void SetBreakPoint(Handle<BreakPointInfo> info,
10908 Handle<Object> break_point_object);
10909 // Check if break point info has this break point object.
10910 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
10911 Handle<Object> break_point_object);
10912 // Get the number of break points for this code position.
10913 int GetBreakPointCount();
10915 static inline BreakPointInfo* cast(Object* obj);
10917 // Dispatched behavior.
10918 DECLARE_PRINTER(BreakPointInfo)
10919 DECLARE_VERIFIER(BreakPointInfo)
10921 static const int kCodePositionIndex = Struct::kHeaderSize;
10922 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
10923 static const int kStatementPositionIndex =
10924 kSourcePositionIndex + kPointerSize;
10925 static const int kBreakPointObjectsIndex =
10926 kStatementPositionIndex + kPointerSize;
10927 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
10930 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
10932 #endif // ENABLE_DEBUGGER_SUPPORT
10935 #undef DECL_BOOLEAN_ACCESSORS
10936 #undef DECL_ACCESSORS
10937 #undef DECLARE_VERIFIER
10939 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
10940 V(kStringTable, "string_table", "(Internalized strings)") \
10941 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
10942 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
10943 V(kInternalizedString, "internalized_string", "(Internal string)") \
10944 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
10945 V(kTop, "top", "(Isolate)") \
10946 V(kRelocatable, "relocatable", "(Relocatable)") \
10947 V(kDebug, "debug", "(Debugger)") \
10948 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
10949 V(kHandleScope, "handlescope", "(Handle scope)") \
10950 V(kBuiltins, "builtins", "(Builtins)") \
10951 V(kGlobalHandles, "globalhandles", "(Global handles)") \
10952 V(kEternalHandles, "eternalhandles", "(Eternal handles)") \
10953 V(kThreadManager, "threadmanager", "(Thread manager)") \
10954 V(kExtensions, "Extensions", "(Extensions)")
10956 class VisitorSynchronization : public AllStatic {
10958 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
10960 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
10963 #undef DECLARE_ENUM
10965 static const char* const kTags[kNumberOfSyncTags];
10966 static const char* const kTagNames[kNumberOfSyncTags];
10969 // Abstract base class for visiting, and optionally modifying, the
10970 // pointers contained in Objects. Used in GC and serialization/deserialization.
10971 class ObjectVisitor BASE_EMBEDDED {
10973 virtual ~ObjectVisitor() {}
10975 // Visits a contiguous arrays of pointers in the half-open range
10976 // [start, end). Any or all of the values may be modified on return.
10977 virtual void VisitPointers(Object** start, Object** end) = 0;
10979 // Handy shorthand for visiting a single pointer.
10980 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
10982 // To allow lazy clearing of inline caches the visitor has
10983 // a rich interface for iterating over Code objects..
10985 // Visits a code target in the instruction stream.
10986 virtual void VisitCodeTarget(RelocInfo* rinfo);
10988 // Visits a code entry in a JS function.
10989 virtual void VisitCodeEntry(Address entry_address);
10991 // Visits a global property cell reference in the instruction stream.
10992 virtual void VisitCell(RelocInfo* rinfo);
10994 // Visits a runtime entry in the instruction stream.
10995 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
10997 // Visits the resource of an ASCII or two-byte string.
10998 virtual void VisitExternalAsciiString(
10999 v8::String::ExternalAsciiStringResource** resource) {}
11000 virtual void VisitExternalTwoByteString(
11001 v8::String::ExternalStringResource** resource) {}
11003 // Visits a debug call target in the instruction stream.
11004 virtual void VisitDebugTarget(RelocInfo* rinfo);
11006 // Visits the byte sequence in a function's prologue that contains information
11007 // about the code's age.
11008 virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
11010 // Visit pointer embedded into a code object.
11011 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
11013 // Visits an external reference embedded into a code object.
11014 virtual void VisitExternalReference(RelocInfo* rinfo);
11016 // Visits an external reference. The value may be modified on return.
11017 virtual void VisitExternalReference(Address* p) {}
11019 // Visits a handle that has an embedder-assigned class ID.
11020 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
11022 // Intended for serialization/deserialization checking: insert, or
11023 // check for the presence of, a tag at this position in the stream.
11024 // Also used for marking up GC roots in heap snapshots.
11025 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
11029 class StructBodyDescriptor : public
11030 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
11032 static inline int SizeOf(Map* map, HeapObject* object) {
11033 return map->instance_size();
11038 // BooleanBit is a helper class for setting and getting a bit in an
11040 class BooleanBit : public AllStatic {
11042 static inline bool get(Smi* smi, int bit_position) {
11043 return get(smi->value(), bit_position);
11046 static inline bool get(int value, int bit_position) {
11047 return (value & (1 << bit_position)) != 0;
11050 static inline Smi* set(Smi* smi, int bit_position, bool v) {
11051 return Smi::FromInt(set(smi->value(), bit_position, v));
11054 static inline int set(int value, int bit_position, bool v) {
11056 value |= (1 << bit_position);
11058 value &= ~(1 << bit_position);
11064 } } // namespace v8::internal
11066 #endif // V8_OBJECTS_H_